title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Swapping Characters of a String in Java - GeeksforGeeks
|
28 Jan, 2022
As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.In this article we would go through some methods to swap character of a given String and get a new String (with swapped characters) while the original String remains unaffected.Through the examples below lets see some of the method by which we can swap character an generate new String Examples: Method 1 (Using toCharArray) In this method we convert the String into the Character array and perform the required Swapping.
Java
// Java program to demonstrate character swap// using toCharArray().public class GFG { static char[] swap(String str, int i, int j) { char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return ch; } public static void main(String args[]) { String s = "geeksforgeeks"; System.out.println(swap(s, 6, s.length() - 2)); System.out.println(swap(s, 0, s.length() - 1)); System.out.println(s); }}
geeksfkrgeeos
seeksforgeekg
geeksforgeeks
Method 2 (Using subString()) We build the modified string using substrings of given string.
Java
// Java program to demonstrate character swap// using subString() public class GFG { static String swap(String str, int i, int j) { if (j == str.length() - 1) return str.substring(0, i) + str.charAt(j) + str.substring(i + 1, j) + str.charAt(i); return str.substring(0, i) + str.charAt(j) + str.substring(i + 1, j) + str.charAt(i) + str.substring(j + 1, str.length()); } public static void main(String args[]) { String s = "geeksforgeeks"; System.out.println(swap(s, 6, s.length() - 2)); System.out.println(swap(s, 0, s.length() - 1)); // Original String doesn't change System.out.println(s); }}
geeksfkrgeeos
seeksforgeekg
geeksforgeeks
Method 3 (Using StringBuilder or StringBuffer) In this method either you can use StringBuilder or StringBuffer depending on the situation. See String vs StringBuilder vs StringBuffer in Java to decide when to use which one.
Java
// Java program to demonstrate character swap// using StringBuilder public class GFG { static String swap(String str, int i, int j) { StringBuilder sb = new StringBuilder(str); sb.setCharAt(i, str.charAt(j)); sb.setCharAt(j, str.charAt(i)); return sb.toString(); } public static void main(String args[]) { String s = "geeksforgeeks"; System.out.println(swap(s, 6, s.length() - 2)); System.out.println(swap(s, 0, s.length() - 1)); // Original String doesn't change System.out.println(s); }}
geeksfkrgeeos
seeksforgeekg
geeksforgeeks
Output:
geeksfkrgeeos
seeksforgeekg
geeksforgeeks
This article is contributed by Sumit Ghosh. 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.
saurabh1990aror
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Internal Working of HashMap in Java
|
[
{
"code": null,
"e": 25262,
"s": 25234,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 25944,
"s": 25262,
"text": "As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.In this article we would go through some methods to swap character of a given String and get a new String (with swapped characters) while the original String remains unaffected.Through the examples below lets see some of the method by which we can swap character an generate new String Examples: Method 1 (Using toCharArray) In this method we convert the String into the Character array and perform the required Swapping. "
},
{
"code": null,
"e": 25949,
"s": 25944,
"text": "Java"
},
{
"code": "// Java program to demonstrate character swap// using toCharArray().public class GFG { static char[] swap(String str, int i, int j) { char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return ch; } public static void main(String args[]) { String s = \"geeksforgeeks\"; System.out.println(swap(s, 6, s.length() - 2)); System.out.println(swap(s, 0, s.length() - 1)); System.out.println(s); }}",
"e": 26450,
"s": 25949,
"text": null
},
{
"code": null,
"e": 26492,
"s": 26450,
"text": "geeksfkrgeeos\nseeksforgeekg\ngeeksforgeeks"
},
{
"code": null,
"e": 26587,
"s": 26494,
"text": "Method 2 (Using subString()) We build the modified string using substrings of given string. "
},
{
"code": null,
"e": 26592,
"s": 26587,
"text": "Java"
},
{
"code": "// Java program to demonstrate character swap// using subString() public class GFG { static String swap(String str, int i, int j) { if (j == str.length() - 1) return str.substring(0, i) + str.charAt(j) + str.substring(i + 1, j) + str.charAt(i); return str.substring(0, i) + str.charAt(j) + str.substring(i + 1, j) + str.charAt(i) + str.substring(j + 1, str.length()); } public static void main(String args[]) { String s = \"geeksforgeeks\"; System.out.println(swap(s, 6, s.length() - 2)); System.out.println(swap(s, 0, s.length() - 1)); // Original String doesn't change System.out.println(s); }}",
"e": 27306,
"s": 26592,
"text": null
},
{
"code": null,
"e": 27348,
"s": 27306,
"text": "geeksfkrgeeos\nseeksforgeekg\ngeeksforgeeks"
},
{
"code": null,
"e": 27576,
"s": 27350,
"text": "Method 3 (Using StringBuilder or StringBuffer) In this method either you can use StringBuilder or StringBuffer depending on the situation. See String vs StringBuilder vs StringBuffer in Java to decide when to use which one. "
},
{
"code": null,
"e": 27581,
"s": 27576,
"text": "Java"
},
{
"code": "// Java program to demonstrate character swap// using StringBuilder public class GFG { static String swap(String str, int i, int j) { StringBuilder sb = new StringBuilder(str); sb.setCharAt(i, str.charAt(j)); sb.setCharAt(j, str.charAt(i)); return sb.toString(); } public static void main(String args[]) { String s = \"geeksforgeeks\"; System.out.println(swap(s, 6, s.length() - 2)); System.out.println(swap(s, 0, s.length() - 1)); // Original String doesn't change System.out.println(s); }}",
"e": 28155,
"s": 27581,
"text": null
},
{
"code": null,
"e": 28197,
"s": 28155,
"text": "geeksfkrgeeos\nseeksforgeekg\ngeeksforgeeks"
},
{
"code": null,
"e": 28209,
"s": 28199,
"text": "Output: "
},
{
"code": null,
"e": 28251,
"s": 28209,
"text": "geeksfkrgeeos\nseeksforgeekg\ngeeksforgeeks"
},
{
"code": null,
"e": 28671,
"s": 28251,
"text": "This article is contributed by Sumit Ghosh. 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": 28687,
"s": 28671,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28708,
"s": 28687,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 28721,
"s": 28708,
"text": "Java-Strings"
},
{
"code": null,
"e": 28726,
"s": 28721,
"text": "Java"
},
{
"code": null,
"e": 28739,
"s": 28726,
"text": "Java-Strings"
},
{
"code": null,
"e": 28744,
"s": 28739,
"text": "Java"
},
{
"code": null,
"e": 28842,
"s": 28744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28857,
"s": 28842,
"text": "Stream In Java"
},
{
"code": null,
"e": 28878,
"s": 28857,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28897,
"s": 28878,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28927,
"s": 28897,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28973,
"s": 28927,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28990,
"s": 28973,
"text": "Generics in Java"
},
{
"code": null,
"e": 29011,
"s": 28990,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29054,
"s": 29011,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29076,
"s": 29054,
"text": "PriorityQueue in Java"
}
] |
Osi.Ig – Information Gathering Instagram Tool in Kali Linux - GeeksforGeeks
|
20 Apr, 2021
Osi.Ig stands for Open Source Intelligence. Osi is a free and open-source tool used to perform reconnaissance on Instagram account/profiles. This is a free and open-source tool used for performing reconnaissance on Instagram accounts. As this tool is open source, so you can contribute to this tool. This tool is very useful when you want to get information about Instagram that you normally wouldn’t be able to get from just looking at their profile. You can get so much information about an account that is not easily visible on the profile of the person. There are various parameters on which you can get information. These included accessibility caption, location, timestamp, caption, picture URL, etc. location will give you a complete list of locations over where the user has tagged that location, the timestamp will give you the actual timestamp of the post. This tool even gives the email address of the user if an email is used anywhere it’ll be displayed. Tags & Mentions will give you the most used hashtags and mentioned accounts. Osi.Ig is written in python language. You must have python language installed in your kali Linux operating system.
Features of Osi.ig:
Osi.Ig stands for Open Source Intelligence. This is an open-source intelligence tool.
Osi.Ig is free tool. This means you don’t have to give any money to the developer you can download it and use it free of cost.
Osi.Ig is an open-source tool. This is an open-source tool that is available on GitHub you can download this tool from Github even contribute in its source code.
Osi.Ig is a lightweight tool for Kali Linux.
Osi.Ig is an information-gathering tool for instagram accounts.
Osi.Ig is used to perform reconnaissance on instagram accounts/profiles.
Osi.Ig is written in python language. You must have python language installed in your kali linux operating system.
Uses of Osi.Ig:
Osi.Ig is used to perform reconnnansnce on Instagram accounts.
Osi.Ig is used for information gathering of Instagram accounts.
Osi.Ig is used to get information about the user id of a profile.
Osi.Ig is used to get information about a number of uploads from an account.
Osi.Ig is used to get information about profile img URL of an instagram account.
Osi.Ig is used to get information about business enum, external URL of an account.
Osi.Ig is used to get information about Tags & Mentions.
Osi.Ig is used to get information about most used hashtags and mentioned accounts of an instagram profile.
Osi.Ig is used to get information about Email address of an account. If any email is used anywhere it’ll be displayed.
Osi.Ig is used to get information of accessibility caption of an instagram profile/account.
Osi.Ig is used to get information locations on which user has posted their photos/videos/stories.
Osi.Ig is used to get information on timestamp on which the user has posted photos and videos.
Osi.Ig is used to get information of caption, picture url, etc.
Step 1: Open your kali Linux operating system. Move to desktop. Here you have to create a directory called Osi.ig. In this directory, you have to install the tool.
To move to desktop use the following command.
cd Desktop
Step 2: Now you are on the desktop. Here you have to create a directory called Osi.ig. To create Osi.ig directory uses the following command.
mkdir Osi.ig
Step 3: You have created a directory. Now use the following command to move into that directory.
cd Osi.ig
Step 4: Now you are in Osi.ig directory. In this directory you have to download the tool means you have to clone the tool from GitHub. Use the following command to clone the tool from GitHub.
git clone https://github.com/th3unkn0n/osi.ig.git
Step 5: The tool has been downloaded in the directory Osi.ig. Now to list out the contents of the tool that has been downloaded using the following command.
ls
Step 6: When you listed out the contents of the tool you can see that a new directory has been generated by the tool that is Osi.ig. You have to move in this directory to view the contents of the tool. To move in this directory using the following command.
cd osi.ig
Step 7: To list out the contents of this directory using the following command.
ls
Step 8: Now you have to install some dependencies using the following command.
apt install python python3 python3-pip
Step 9: Now you have to install the requirements of the Osi.ig tool. To install requirements use the following command.
python3 -m pip install requirements.txt
Step 10: All the requirements has been downloaded. Now have to give permission to the tool.
chmod +x main.py
Step 11: All the permission has been given to them too. Now it’s time to run the tool. Use the following command to run the tool. This command will give you the help section of the tool. This means the tool is perfectly installed and running successfully.
./main.py -h
Congratulations you have finally installed the tool now we will see some examples of how to use this tool.
Example 1: Use Osi.ig tool to get an instagram account.
python3 main.py -u < username >
These are the details which we got after performing reconnaissance on an Instagram account. You can perform reconnaissance using your own target. You can also see the user’s picture with the link provided by this tool which may be one of the best features of this tool.
Example 2: Use Osi.ig tool to find In-Depth Description of Uploaded Photos & Videos of an instagram account/profile.
python3 main.py -u < username > -p
Use this command for Depth Description of Uploaded Photos & Videos of an Instagram account/profile.
Conclusion: These are the details which we are getting after performing Reconnaissance on this user profile. Similarly, you can perform recognisance on your Instagram accounts/profiles. This tool is very useful when you want to get information about Instagram that you normally wouldn’t be able to get from just looking at their profile. You can get so much information about an account that is not easily visible on the profile of the person. There are various parameters on which you can get information. These included accessibility caption, location, timestamp, caption, picture URL, etc. location will give you a complete list of locations over where the user has tagged that location, timestamp will give you the actual timestamp of the post. This tool even gives the email address of the user if an email is used anywhere it’ll be displayed. Tags & Mentions will give you the most used hashtags and mentioned accounts. Osi.Ig is written in python language. You must have python language installed in your kali Linux operating system.
Cyber-security
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
|
[
{
"code": null,
"e": 25707,
"s": 25679,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 26867,
"s": 25707,
"text": "Osi.Ig stands for Open Source Intelligence. Osi is a free and open-source tool used to perform reconnaissance on Instagram account/profiles. This is a free and open-source tool used for performing reconnaissance on Instagram accounts. As this tool is open source, so you can contribute to this tool. This tool is very useful when you want to get information about Instagram that you normally wouldn’t be able to get from just looking at their profile. You can get so much information about an account that is not easily visible on the profile of the person. There are various parameters on which you can get information. These included accessibility caption, location, timestamp, caption, picture URL, etc. location will give you a complete list of locations over where the user has tagged that location, the timestamp will give you the actual timestamp of the post. This tool even gives the email address of the user if an email is used anywhere it’ll be displayed. Tags & Mentions will give you the most used hashtags and mentioned accounts. Osi.Ig is written in python language. You must have python language installed in your kali Linux operating system."
},
{
"code": null,
"e": 26887,
"s": 26867,
"text": "Features of Osi.ig:"
},
{
"code": null,
"e": 26973,
"s": 26887,
"text": "Osi.Ig stands for Open Source Intelligence. This is an open-source intelligence tool."
},
{
"code": null,
"e": 27100,
"s": 26973,
"text": "Osi.Ig is free tool. This means you don’t have to give any money to the developer you can download it and use it free of cost."
},
{
"code": null,
"e": 27262,
"s": 27100,
"text": "Osi.Ig is an open-source tool. This is an open-source tool that is available on GitHub you can download this tool from Github even contribute in its source code."
},
{
"code": null,
"e": 27307,
"s": 27262,
"text": "Osi.Ig is a lightweight tool for Kali Linux."
},
{
"code": null,
"e": 27371,
"s": 27307,
"text": "Osi.Ig is an information-gathering tool for instagram accounts."
},
{
"code": null,
"e": 27444,
"s": 27371,
"text": "Osi.Ig is used to perform reconnaissance on instagram accounts/profiles."
},
{
"code": null,
"e": 27559,
"s": 27444,
"text": "Osi.Ig is written in python language. You must have python language installed in your kali linux operating system."
},
{
"code": null,
"e": 27575,
"s": 27559,
"text": "Uses of Osi.Ig:"
},
{
"code": null,
"e": 27638,
"s": 27575,
"text": "Osi.Ig is used to perform reconnnansnce on Instagram accounts."
},
{
"code": null,
"e": 27702,
"s": 27638,
"text": "Osi.Ig is used for information gathering of Instagram accounts."
},
{
"code": null,
"e": 27768,
"s": 27702,
"text": "Osi.Ig is used to get information about the user id of a profile."
},
{
"code": null,
"e": 27845,
"s": 27768,
"text": "Osi.Ig is used to get information about a number of uploads from an account."
},
{
"code": null,
"e": 27926,
"s": 27845,
"text": "Osi.Ig is used to get information about profile img URL of an instagram account."
},
{
"code": null,
"e": 28009,
"s": 27926,
"text": "Osi.Ig is used to get information about business enum, external URL of an account."
},
{
"code": null,
"e": 28066,
"s": 28009,
"text": "Osi.Ig is used to get information about Tags & Mentions."
},
{
"code": null,
"e": 28173,
"s": 28066,
"text": "Osi.Ig is used to get information about most used hashtags and mentioned accounts of an instagram profile."
},
{
"code": null,
"e": 28292,
"s": 28173,
"text": "Osi.Ig is used to get information about Email address of an account. If any email is used anywhere it’ll be displayed."
},
{
"code": null,
"e": 28384,
"s": 28292,
"text": "Osi.Ig is used to get information of accessibility caption of an instagram profile/account."
},
{
"code": null,
"e": 28482,
"s": 28384,
"text": "Osi.Ig is used to get information locations on which user has posted their photos/videos/stories."
},
{
"code": null,
"e": 28577,
"s": 28482,
"text": "Osi.Ig is used to get information on timestamp on which the user has posted photos and videos."
},
{
"code": null,
"e": 28641,
"s": 28577,
"text": "Osi.Ig is used to get information of caption, picture url, etc."
},
{
"code": null,
"e": 28805,
"s": 28641,
"text": "Step 1: Open your kali Linux operating system. Move to desktop. Here you have to create a directory called Osi.ig. In this directory, you have to install the tool."
},
{
"code": null,
"e": 28851,
"s": 28805,
"text": "To move to desktop use the following command."
},
{
"code": null,
"e": 28862,
"s": 28851,
"text": "cd Desktop"
},
{
"code": null,
"e": 29004,
"s": 28862,
"text": "Step 2: Now you are on the desktop. Here you have to create a directory called Osi.ig. To create Osi.ig directory uses the following command."
},
{
"code": null,
"e": 29017,
"s": 29004,
"text": "mkdir Osi.ig"
},
{
"code": null,
"e": 29114,
"s": 29017,
"text": "Step 3: You have created a directory. Now use the following command to move into that directory."
},
{
"code": null,
"e": 29124,
"s": 29114,
"text": "cd Osi.ig"
},
{
"code": null,
"e": 29316,
"s": 29124,
"text": "Step 4: Now you are in Osi.ig directory. In this directory you have to download the tool means you have to clone the tool from GitHub. Use the following command to clone the tool from GitHub."
},
{
"code": null,
"e": 29366,
"s": 29316,
"text": "git clone https://github.com/th3unkn0n/osi.ig.git"
},
{
"code": null,
"e": 29523,
"s": 29366,
"text": "Step 5: The tool has been downloaded in the directory Osi.ig. Now to list out the contents of the tool that has been downloaded using the following command."
},
{
"code": null,
"e": 29526,
"s": 29523,
"text": "ls"
},
{
"code": null,
"e": 29783,
"s": 29526,
"text": "Step 6: When you listed out the contents of the tool you can see that a new directory has been generated by the tool that is Osi.ig. You have to move in this directory to view the contents of the tool. To move in this directory using the following command."
},
{
"code": null,
"e": 29793,
"s": 29783,
"text": "cd osi.ig"
},
{
"code": null,
"e": 29873,
"s": 29793,
"text": "Step 7: To list out the contents of this directory using the following command."
},
{
"code": null,
"e": 29876,
"s": 29873,
"text": "ls"
},
{
"code": null,
"e": 29955,
"s": 29876,
"text": "Step 8: Now you have to install some dependencies using the following command."
},
{
"code": null,
"e": 29994,
"s": 29955,
"text": "apt install python python3 python3-pip"
},
{
"code": null,
"e": 30114,
"s": 29994,
"text": "Step 9: Now you have to install the requirements of the Osi.ig tool. To install requirements use the following command."
},
{
"code": null,
"e": 30154,
"s": 30114,
"text": "python3 -m pip install requirements.txt"
},
{
"code": null,
"e": 30246,
"s": 30154,
"text": "Step 10: All the requirements has been downloaded. Now have to give permission to the tool."
},
{
"code": null,
"e": 30263,
"s": 30246,
"text": "chmod +x main.py"
},
{
"code": null,
"e": 30519,
"s": 30263,
"text": "Step 11: All the permission has been given to them too. Now it’s time to run the tool. Use the following command to run the tool. This command will give you the help section of the tool. This means the tool is perfectly installed and running successfully."
},
{
"code": null,
"e": 30532,
"s": 30519,
"text": "./main.py -h"
},
{
"code": null,
"e": 30639,
"s": 30532,
"text": "Congratulations you have finally installed the tool now we will see some examples of how to use this tool."
},
{
"code": null,
"e": 30695,
"s": 30639,
"text": "Example 1: Use Osi.ig tool to get an instagram account."
},
{
"code": null,
"e": 30727,
"s": 30695,
"text": "python3 main.py -u < username >"
},
{
"code": null,
"e": 30997,
"s": 30727,
"text": "These are the details which we got after performing reconnaissance on an Instagram account. You can perform reconnaissance using your own target. You can also see the user’s picture with the link provided by this tool which may be one of the best features of this tool."
},
{
"code": null,
"e": 31114,
"s": 30997,
"text": "Example 2: Use Osi.ig tool to find In-Depth Description of Uploaded Photos & Videos of an instagram account/profile."
},
{
"code": null,
"e": 31150,
"s": 31114,
"text": " python3 main.py -u < username > -p"
},
{
"code": null,
"e": 31250,
"s": 31150,
"text": "Use this command for Depth Description of Uploaded Photos & Videos of an Instagram account/profile."
},
{
"code": null,
"e": 32292,
"s": 31250,
"text": "Conclusion: These are the details which we are getting after performing Reconnaissance on this user profile. Similarly, you can perform recognisance on your Instagram accounts/profiles. This tool is very useful when you want to get information about Instagram that you normally wouldn’t be able to get from just looking at their profile. You can get so much information about an account that is not easily visible on the profile of the person. There are various parameters on which you can get information. These included accessibility caption, location, timestamp, caption, picture URL, etc. location will give you a complete list of locations over where the user has tagged that location, timestamp will give you the actual timestamp of the post. This tool even gives the email address of the user if an email is used anywhere it’ll be displayed. Tags & Mentions will give you the most used hashtags and mentioned accounts. Osi.Ig is written in python language. You must have python language installed in your kali Linux operating system."
},
{
"code": null,
"e": 32307,
"s": 32292,
"text": "Cyber-security"
},
{
"code": null,
"e": 32318,
"s": 32307,
"text": "Kali-Linux"
},
{
"code": null,
"e": 32330,
"s": 32318,
"text": "Linux-Tools"
},
{
"code": null,
"e": 32341,
"s": 32330,
"text": "Linux-Unix"
},
{
"code": null,
"e": 32439,
"s": 32341,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32474,
"s": 32439,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 32512,
"s": 32474,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 32553,
"s": 32512,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 32588,
"s": 32553,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 32624,
"s": 32588,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 32662,
"s": 32624,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 32695,
"s": 32662,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 32731,
"s": 32695,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 32769,
"s": 32731,
"text": "UDP Server-Client implementation in C"
}
] |
Python | Pandas Series.dt.time - GeeksforGeeks
|
20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.time attribute return a numpy array of python datetime.time objects.
Syntax: Series.dt.time
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.time attribute to return the time property of the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.time attribute to return the time property of the underlying data of the given Series object.
# return the timeresult = sr.dt.time # print the resultprint(result)
Output :As we can see in the output, the Series.dt.time attribute has successfully accessed and returned the time property of the underlying data in the given series object. Example #2 : Use Series.dt.time attribute to return the time property of the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.time attribute to return the time property of the underlying data of the given Series object.
# return the timeresult = sr.dt.time # print the resultprint(result)
Output :As we can see in the output, the Series.dt.time attribute has successfully accessed and returned the time property of the underlying data in the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 25727,
"s": 25537,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.time attribute return a numpy array of python datetime.time objects."
},
{
"code": null,
"e": 25750,
"s": 25727,
"text": "Syntax: Series.dt.time"
},
{
"code": null,
"e": 25767,
"s": 25750,
"text": "Parameter : None"
},
{
"code": null,
"e": 25789,
"s": 25767,
"text": "Returns : numpy array"
},
{
"code": null,
"e": 25909,
"s": 25789,
"text": "Example #1: Use Series.dt.time attribute to return the time property of the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 26303,
"s": 25909,
"text": null
},
{
"code": null,
"e": 26312,
"s": 26303,
"text": "Output :"
},
{
"code": null,
"e": 26432,
"s": 26312,
"text": "Now we will use Series.dt.time attribute to return the time property of the underlying data of the given Series object."
},
{
"code": "# return the timeresult = sr.dt.time # print the resultprint(result)",
"e": 26502,
"s": 26432,
"text": null
},
{
"code": null,
"e": 26797,
"s": 26502,
"text": "Output :As we can see in the output, the Series.dt.time attribute has successfully accessed and returned the time property of the underlying data in the given series object. Example #2 : Use Series.dt.time attribute to return the time property of the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 27093,
"s": 26797,
"text": null
},
{
"code": null,
"e": 27102,
"s": 27093,
"text": "Output :"
},
{
"code": null,
"e": 27222,
"s": 27102,
"text": "Now we will use Series.dt.time attribute to return the time property of the underlying data of the given Series object."
},
{
"code": "# return the timeresult = sr.dt.time # print the resultprint(result)",
"e": 27292,
"s": 27222,
"text": null
},
{
"code": null,
"e": 27466,
"s": 27292,
"text": "Output :As we can see in the output, the Series.dt.time attribute has successfully accessed and returned the time property of the underlying data in the given series object."
},
{
"code": null,
"e": 27496,
"s": 27466,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 27510,
"s": 27496,
"text": "Python-pandas"
},
{
"code": null,
"e": 27517,
"s": 27510,
"text": "Python"
},
{
"code": null,
"e": 27615,
"s": 27517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27647,
"s": 27615,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27689,
"s": 27647,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27731,
"s": 27689,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27758,
"s": 27731,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27814,
"s": 27758,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27836,
"s": 27814,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27875,
"s": 27836,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27906,
"s": 27875,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27935,
"s": 27906,
"text": "Create a directory in Python"
}
] |
Batch Script - Deleting Folders
|
For deleting folders, Batch Script provides the DEL command.
DEL [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names
Following are the description of the options which can be presented to the DEL command.
Names
Specifies a list of one or more files or directories. Wildcards may be used to delete multiple files. If a directory is specified, all files within the directory will be deleted
/P
Prompts for confirmation before deleting each file.
/F
Force deletes read-only files.
/S
Deletes specified files from all subdirectories.
/Q
Quiet mode, do not ask if ok to delete on global wildcard.
/A
Selects files to delete based on attributes.
attributes
R - Read-only files, S - System files, H - Hidden files, A - Files ready for archiving - Prefix meaning not
Let’s look at some examples of how the DEL command can be used for folders.
del Example
The above command will delete the folder called Example in the current working directory.
del C:\Example
The above command will delete the folder called Example in C drive.
Del Example1 , Example2
The above command will delete the folder called Example1 and Example2 in the current working directory.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2230,
"s": 2169,
"text": "For deleting folders, Batch Script provides the DEL command."
},
{
"code": null,
"e": 2281,
"s": 2230,
"text": "DEL [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names\n"
},
{
"code": null,
"e": 2369,
"s": 2281,
"text": "Following are the description of the options which can be presented to the DEL command."
},
{
"code": null,
"e": 2375,
"s": 2369,
"text": "Names"
},
{
"code": null,
"e": 2553,
"s": 2375,
"text": "Specifies a list of one or more files or directories. Wildcards may be used to delete multiple files. If a directory is specified, all files within the directory will be deleted"
},
{
"code": null,
"e": 2556,
"s": 2553,
"text": "/P"
},
{
"code": null,
"e": 2608,
"s": 2556,
"text": "Prompts for confirmation before deleting each file."
},
{
"code": null,
"e": 2611,
"s": 2608,
"text": "/F"
},
{
"code": null,
"e": 2642,
"s": 2611,
"text": "Force deletes read-only files."
},
{
"code": null,
"e": 2645,
"s": 2642,
"text": "/S"
},
{
"code": null,
"e": 2694,
"s": 2645,
"text": "Deletes specified files from all subdirectories."
},
{
"code": null,
"e": 2697,
"s": 2694,
"text": "/Q"
},
{
"code": null,
"e": 2756,
"s": 2697,
"text": "Quiet mode, do not ask if ok to delete on global wildcard."
},
{
"code": null,
"e": 2759,
"s": 2756,
"text": "/A"
},
{
"code": null,
"e": 2804,
"s": 2759,
"text": "Selects files to delete based on attributes."
},
{
"code": null,
"e": 2815,
"s": 2804,
"text": "attributes"
},
{
"code": null,
"e": 2923,
"s": 2815,
"text": "R - Read-only files, S - System files, H - Hidden files, A - Files ready for archiving - Prefix meaning not"
},
{
"code": null,
"e": 2999,
"s": 2923,
"text": "Let’s look at some examples of how the DEL command can be used for folders."
},
{
"code": null,
"e": 3012,
"s": 2999,
"text": "del Example\n"
},
{
"code": null,
"e": 3102,
"s": 3012,
"text": "The above command will delete the folder called Example in the current working directory."
},
{
"code": null,
"e": 3118,
"s": 3102,
"text": "del C:\\Example\n"
},
{
"code": null,
"e": 3186,
"s": 3118,
"text": "The above command will delete the folder called Example in C drive."
},
{
"code": null,
"e": 3211,
"s": 3186,
"text": "Del Example1 , Example2\n"
},
{
"code": null,
"e": 3315,
"s": 3211,
"text": "The above command will delete the folder called Example1 and Example2 in the current working directory."
},
{
"code": null,
"e": 3322,
"s": 3315,
"text": " Print"
},
{
"code": null,
"e": 3333,
"s": 3322,
"text": " Add Notes"
}
] |
What are Rest parameters in JavaScript?
|
ES6 brought rest parameter to ease the work of developers. For arguments objects, rest parameters are indicated by three dots ... and precedes a parameter.With this, set indefinite number of arguments as an array, which areArray instances.
Let’s see the following code snippet:
<html>
<body>
<script>
function addition(...numbers) {
var res = 0;
numbers.forEach(function (number) {
res += number;
});
return res;
}
document.write(addition(3));
document.write(addition(5,6,7,8,9));
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1302,
"s": 1062,
"text": "ES6 brought rest parameter to ease the work of developers. For arguments objects, rest parameters are indicated by three dots ... and precedes a parameter.With this, set indefinite number of arguments as an array, which areArray instances."
},
{
"code": null,
"e": 1340,
"s": 1302,
"text": "Let’s see the following code snippet:"
},
{
"code": null,
"e": 1686,
"s": 1340,
"text": "<html>\n <body>\n <script>\n function addition(...numbers) {\n var res = 0;\n numbers.forEach(function (number) {\n res += number;\n });\n return res;\n }\n document.write(addition(3));\n document.write(addition(5,6,7,8,9));\n </script>\n </body>\n</html>"
}
] |
Kubernetes - Replication Controller
|
Replication Controller is one of the key features of Kubernetes, which is responsible for managing the pod lifecycle. It is responsible for making sure that the specified number of pod replicas are running at any point of time. It is used in time when one wants to make sure that the specified number of pod or at least one pod is running. It has the capability to bring up or down the specified no of pod.
It is a best practice to use the replication controller to manage the pod life cycle rather than creating a pod again and again.
apiVersion: v1
kind: ReplicationController --------------------------> 1
metadata:
name: Tomcat-ReplicationController --------------------------> 2
spec:
replicas: 3 ------------------------> 3
template:
metadata:
name: Tomcat-ReplicationController
labels:
app: App
component: neo4j
spec:
containers:
- name: Tomcat- -----------------------> 4
image: tomcat: 8.0
ports:
- containerPort: 7474 ------------------------> 5
Kind: ReplicationController → In the above code, we have defined the kind as replication controller which tells the kubectl that the yaml file is going to be used for creating the replication controller.
Kind: ReplicationController → In the above code, we have defined the kind as replication controller which tells the kubectl that the yaml file is going to be used for creating the replication controller.
name: Tomcat-ReplicationController → This helps in identifying the name with which the replication controller will be created. If we run the kubctl, get rc < Tomcat-ReplicationController > it will show the replication controller details.
name: Tomcat-ReplicationController → This helps in identifying the name with which the replication controller will be created. If we run the kubctl, get rc < Tomcat-ReplicationController > it will show the replication controller details.
replicas: 3 → This helps the replication controller to understand that it needs to maintain three replicas of a pod at any point of time in the pod lifecycle.
replicas: 3 → This helps the replication controller to understand that it needs to maintain three replicas of a pod at any point of time in the pod lifecycle.
name: Tomcat → In the spec section, we have defined the name as tomcat which will tell the replication controller that the container present inside the pods is tomcat.
name: Tomcat → In the spec section, we have defined the name as tomcat which will tell the replication controller that the container present inside the pods is tomcat.
containerPort: 7474 → It helps in making sure that all the nodes in the cluster where the pod is running the container inside the pod will be exposed on the same port 7474.
containerPort: 7474 → It helps in making sure that all the nodes in the cluster where the pod is running the container inside the pod will be exposed on the same port 7474.
Here, the Kubernetes service is working as a load balancer for three tomcat replicas.
41 Lectures
5 hours
AR Shankar
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
18 Lectures
1.5 hours
Nigel Poulton
25 Lectures
1.5 hours
Pranjal Srivastava
18 Lectures
1 hours
Pranjal Srivastava
26 Lectures
1.5 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2602,
"s": 2195,
"text": "Replication Controller is one of the key features of Kubernetes, which is responsible for managing the pod lifecycle. It is responsible for making sure that the specified number of pod replicas are running at any point of time. It is used in time when one wants to make sure that the specified number of pod or at least one pod is running. It has the capability to bring up or down the specified no of pod."
},
{
"code": null,
"e": 2731,
"s": 2602,
"text": "It is a best practice to use the replication controller to manage the pod life cycle rather than creating a pod again and again."
},
{
"code": null,
"e": 3254,
"s": 2731,
"text": "apiVersion: v1\nkind: ReplicationController --------------------------> 1\nmetadata:\n name: Tomcat-ReplicationController --------------------------> 2\nspec:\n replicas: 3 ------------------------> 3\n template:\n metadata:\n name: Tomcat-ReplicationController\n labels:\n app: App\n component: neo4j\n spec:\n containers:\n - name: Tomcat- -----------------------> 4\n image: tomcat: 8.0\n ports:\n - containerPort: 7474 ------------------------> 5\n"
},
{
"code": null,
"e": 3458,
"s": 3254,
"text": "Kind: ReplicationController → In the above code, we have defined the kind as replication controller which tells the kubectl that the yaml file is going to be used for creating the replication controller."
},
{
"code": null,
"e": 3662,
"s": 3458,
"text": "Kind: ReplicationController → In the above code, we have defined the kind as replication controller which tells the kubectl that the yaml file is going to be used for creating the replication controller."
},
{
"code": null,
"e": 3900,
"s": 3662,
"text": "name: Tomcat-ReplicationController → This helps in identifying the name with which the replication controller will be created. If we run the kubctl, get rc < Tomcat-ReplicationController > it will show the replication controller details."
},
{
"code": null,
"e": 4138,
"s": 3900,
"text": "name: Tomcat-ReplicationController → This helps in identifying the name with which the replication controller will be created. If we run the kubctl, get rc < Tomcat-ReplicationController > it will show the replication controller details."
},
{
"code": null,
"e": 4297,
"s": 4138,
"text": "replicas: 3 → This helps the replication controller to understand that it needs to maintain three replicas of a pod at any point of time in the pod lifecycle."
},
{
"code": null,
"e": 4456,
"s": 4297,
"text": "replicas: 3 → This helps the replication controller to understand that it needs to maintain three replicas of a pod at any point of time in the pod lifecycle."
},
{
"code": null,
"e": 4624,
"s": 4456,
"text": "name: Tomcat → In the spec section, we have defined the name as tomcat which will tell the replication controller that the container present inside the pods is tomcat."
},
{
"code": null,
"e": 4792,
"s": 4624,
"text": "name: Tomcat → In the spec section, we have defined the name as tomcat which will tell the replication controller that the container present inside the pods is tomcat."
},
{
"code": null,
"e": 4965,
"s": 4792,
"text": "containerPort: 7474 → It helps in making sure that all the nodes in the cluster where the pod is running the container inside the pod will be exposed on the same port 7474."
},
{
"code": null,
"e": 5138,
"s": 4965,
"text": "containerPort: 7474 → It helps in making sure that all the nodes in the cluster where the pod is running the container inside the pod will be exposed on the same port 7474."
},
{
"code": null,
"e": 5224,
"s": 5138,
"text": "Here, the Kubernetes service is working as a load balancer for three tomcat replicas."
},
{
"code": null,
"e": 5257,
"s": 5224,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5269,
"s": 5257,
"text": " AR Shankar"
},
{
"code": null,
"e": 5302,
"s": 5269,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5342,
"s": 5302,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 5377,
"s": 5342,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5392,
"s": 5377,
"text": " Nigel Poulton"
},
{
"code": null,
"e": 5427,
"s": 5392,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5447,
"s": 5427,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5480,
"s": 5447,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5500,
"s": 5480,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5535,
"s": 5500,
"text": "\n 26 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5555,
"s": 5535,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5562,
"s": 5555,
"text": " Print"
},
{
"code": null,
"e": 5573,
"s": 5562,
"text": " Add Notes"
}
] |
BigInteger max() and min() Methods in Java - GeeksforGeeks
|
04 Dec, 2018
Prerequisite: BigInteger Basics
BigInteger max() method: The max() method of the BigInteger returns the BigInteger whose value is the greater between current BigInteger and BigInteger passed as a parameter to the method. If both the values are equal, either may be returned.There is a similar method compareTo() available on BigInteger class. The max() method is different than compareTo() in a way that in the compareTo() method we have to interpret the result while on the max method, the biggest BigInteger is already returned.Syntax:public BigInteger max(BigInteger val)Parameters: The method accepts one parameter val which refers to the value with which the maximum is to be computed.Return Value: The method returns the BigInteger whose value is the greater of this and val. If they are equal, either may be returned.Below program illustrate max() method of BigInteger class./* *Program Demonstrate max() method of BigInteger */import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigInteger objects BigInteger biginteger=new BigInteger("8976543245"); BigInteger val=new BigInteger("9248040402"); // Call max() method to find greater value // between two BigIntegers. BigInteger biggerInteger = biginteger.max(val); String result = "Bigger Integer between "+biginteger+" and " +val+ " is " +biggerInteger; // Prints the result System.out.println(result); }}Output:Bigger Integer between 8976543245 and 9248040402 is 9248040402
There is a similar method compareTo() available on BigInteger class. The max() method is different than compareTo() in a way that in the compareTo() method we have to interpret the result while on the max method, the biggest BigInteger is already returned.
Syntax:
public BigInteger max(BigInteger val)
Parameters: The method accepts one parameter val which refers to the value with which the maximum is to be computed.
Return Value: The method returns the BigInteger whose value is the greater of this and val. If they are equal, either may be returned.
Below program illustrate max() method of BigInteger class.
/* *Program Demonstrate max() method of BigInteger */import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigInteger objects BigInteger biginteger=new BigInteger("8976543245"); BigInteger val=new BigInteger("9248040402"); // Call max() method to find greater value // between two BigIntegers. BigInteger biggerInteger = biginteger.max(val); String result = "Bigger Integer between "+biginteger+" and " +val+ " is " +biggerInteger; // Prints the result System.out.println(result); }}
Bigger Integer between 8976543245 and 9248040402 is 9248040402
BigInteger min() method: The min() method of the BigInteger returns the BigInteger whose value is the lesser between current BigInteger and BigInteger passed as parameter to method. If both the values are equal, either may be returned.There is a similar method compareTo() available on BigInteger class . The min() method different than compareTo() in a way that in the compareTo() method we have to interpret the result while on the min() method, the smallest BigInteger will be returned.Syntax:public BigInteger min(BigInteger val)Parameters: The method accepts one parameter val which refers to the value with which the minimum is to be computed.Return Value: The method returns the BigInteger whose value is the lesser of this and val. If the values are equal, either may be returned.Below program illustrate min() method of BigInteger class./* *Program Demonstrate min() method of BigInteger */import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigInteger objects BigInteger biginteger=new BigInteger("5782539631"); BigInteger val=new BigInteger("3592633823"); // Call min() method to find lesser value // between two BigIntegers. BigInteger biggerInteger = biginteger.min(val); String result = "lesser Integer between "+biginteger+" and " +val+ " is " +biggerInteger; // Prints the result System.out.println(result); }}Output:lesser Integer between 5782539631 and 3592633823 is 3592633823
There is a similar method compareTo() available on BigInteger class . The min() method different than compareTo() in a way that in the compareTo() method we have to interpret the result while on the min() method, the smallest BigInteger will be returned.
Syntax:
public BigInteger min(BigInteger val)
Parameters: The method accepts one parameter val which refers to the value with which the minimum is to be computed.
Return Value: The method returns the BigInteger whose value is the lesser of this and val. If the values are equal, either may be returned.
Below program illustrate min() method of BigInteger class.
/* *Program Demonstrate min() method of BigInteger */import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigInteger objects BigInteger biginteger=new BigInteger("5782539631"); BigInteger val=new BigInteger("3592633823"); // Call min() method to find lesser value // between two BigIntegers. BigInteger biggerInteger = biginteger.min(val); String result = "lesser Integer between "+biginteger+" and " +val+ " is " +biggerInteger; // Prints the result System.out.println(result); }}
lesser Integer between 5782539631 and 3592633823 is 3592633823
Reference:
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#max(java.math.BigInteger)
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#min(java.math.BigInteger)
Java-BigInteger
Java-Functions
Java-lang package
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Internal Working of HashMap in Java
Checked vs Unchecked Exceptions in Java
Strings in Java
StringBuilder Class in Java with Examples
|
[
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 23900,
"s": 23868,
"text": "Prerequisite: BigInteger Basics"
},
{
"code": null,
"e": 25444,
"s": 23900,
"text": "BigInteger max() method: The max() method of the BigInteger returns the BigInteger whose value is the greater between current BigInteger and BigInteger passed as a parameter to the method. If both the values are equal, either may be returned.There is a similar method compareTo() available on BigInteger class. The max() method is different than compareTo() in a way that in the compareTo() method we have to interpret the result while on the max method, the biggest BigInteger is already returned.Syntax:public BigInteger max(BigInteger val)Parameters: The method accepts one parameter val which refers to the value with which the maximum is to be computed.Return Value: The method returns the BigInteger whose value is the greater of this and val. If they are equal, either may be returned.Below program illustrate max() method of BigInteger class./* *Program Demonstrate max() method of BigInteger */import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigInteger objects BigInteger biginteger=new BigInteger(\"8976543245\"); BigInteger val=new BigInteger(\"9248040402\"); // Call max() method to find greater value // between two BigIntegers. BigInteger biggerInteger = biginteger.max(val); String result = \"Bigger Integer between \"+biginteger+\" and \" +val+ \" is \" +biggerInteger; // Prints the result System.out.println(result); }}Output:Bigger Integer between 8976543245 and 9248040402 is 9248040402\n"
},
{
"code": null,
"e": 25701,
"s": 25444,
"text": "There is a similar method compareTo() available on BigInteger class. The max() method is different than compareTo() in a way that in the compareTo() method we have to interpret the result while on the max method, the biggest BigInteger is already returned."
},
{
"code": null,
"e": 25709,
"s": 25701,
"text": "Syntax:"
},
{
"code": null,
"e": 25747,
"s": 25709,
"text": "public BigInteger max(BigInteger val)"
},
{
"code": null,
"e": 25864,
"s": 25747,
"text": "Parameters: The method accepts one parameter val which refers to the value with which the maximum is to be computed."
},
{
"code": null,
"e": 25999,
"s": 25864,
"text": "Return Value: The method returns the BigInteger whose value is the greater of this and val. If they are equal, either may be returned."
},
{
"code": null,
"e": 26058,
"s": 25999,
"text": "Below program illustrate max() method of BigInteger class."
},
{
"code": "/* *Program Demonstrate max() method of BigInteger */import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigInteger objects BigInteger biginteger=new BigInteger(\"8976543245\"); BigInteger val=new BigInteger(\"9248040402\"); // Call max() method to find greater value // between two BigIntegers. BigInteger biggerInteger = biginteger.max(val); String result = \"Bigger Integer between \"+biginteger+\" and \" +val+ \" is \" +biggerInteger; // Prints the result System.out.println(result); }}",
"e": 26682,
"s": 26058,
"text": null
},
{
"code": null,
"e": 26746,
"s": 26682,
"text": "Bigger Integer between 8976543245 and 9248040402 is 9248040402\n"
},
{
"code": null,
"e": 28274,
"s": 26746,
"text": "BigInteger min() method: The min() method of the BigInteger returns the BigInteger whose value is the lesser between current BigInteger and BigInteger passed as parameter to method. If both the values are equal, either may be returned.There is a similar method compareTo() available on BigInteger class . The min() method different than compareTo() in a way that in the compareTo() method we have to interpret the result while on the min() method, the smallest BigInteger will be returned.Syntax:public BigInteger min(BigInteger val)Parameters: The method accepts one parameter val which refers to the value with which the minimum is to be computed.Return Value: The method returns the BigInteger whose value is the lesser of this and val. If the values are equal, either may be returned.Below program illustrate min() method of BigInteger class./* *Program Demonstrate min() method of BigInteger */import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigInteger objects BigInteger biginteger=new BigInteger(\"5782539631\"); BigInteger val=new BigInteger(\"3592633823\"); // Call min() method to find lesser value // between two BigIntegers. BigInteger biggerInteger = biginteger.min(val); String result = \"lesser Integer between \"+biginteger+\" and \" +val+ \" is \" +biggerInteger; // Prints the result System.out.println(result); }}Output:lesser Integer between 5782539631 and 3592633823 is 3592633823\n"
},
{
"code": null,
"e": 28529,
"s": 28274,
"text": "There is a similar method compareTo() available on BigInteger class . The min() method different than compareTo() in a way that in the compareTo() method we have to interpret the result while on the min() method, the smallest BigInteger will be returned."
},
{
"code": null,
"e": 28537,
"s": 28529,
"text": "Syntax:"
},
{
"code": null,
"e": 28575,
"s": 28537,
"text": "public BigInteger min(BigInteger val)"
},
{
"code": null,
"e": 28692,
"s": 28575,
"text": "Parameters: The method accepts one parameter val which refers to the value with which the minimum is to be computed."
},
{
"code": null,
"e": 28832,
"s": 28692,
"text": "Return Value: The method returns the BigInteger whose value is the lesser of this and val. If the values are equal, either may be returned."
},
{
"code": null,
"e": 28891,
"s": 28832,
"text": "Below program illustrate min() method of BigInteger class."
},
{
"code": "/* *Program Demonstrate min() method of BigInteger */import java.math.*; public class GFG { public static void main(String[] args) { // Create 2 BigInteger objects BigInteger biginteger=new BigInteger(\"5782539631\"); BigInteger val=new BigInteger(\"3592633823\"); // Call min() method to find lesser value // between two BigIntegers. BigInteger biggerInteger = biginteger.min(val); String result = \"lesser Integer between \"+biginteger+\" and \" +val+ \" is \" +biggerInteger; // Prints the result System.out.println(result); }}",
"e": 29503,
"s": 28891,
"text": null
},
{
"code": null,
"e": 29567,
"s": 29503,
"text": "lesser Integer between 5782539631 and 3592633823 is 3592633823\n"
},
{
"code": null,
"e": 29578,
"s": 29567,
"text": "Reference:"
},
{
"code": null,
"e": 29672,
"s": 29578,
"text": "https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#max(java.math.BigInteger)"
},
{
"code": null,
"e": 29766,
"s": 29672,
"text": "https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#min(java.math.BigInteger)"
},
{
"code": null,
"e": 29782,
"s": 29766,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 29797,
"s": 29782,
"text": "Java-Functions"
},
{
"code": null,
"e": 29815,
"s": 29797,
"text": "Java-lang package"
},
{
"code": null,
"e": 29825,
"s": 29815,
"text": "java-math"
},
{
"code": null,
"e": 29843,
"s": 29825,
"text": "Java-math-package"
},
{
"code": null,
"e": 29848,
"s": 29843,
"text": "Java"
},
{
"code": null,
"e": 29864,
"s": 29848,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 29869,
"s": 29864,
"text": "Java"
},
{
"code": null,
"e": 29967,
"s": 29869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29976,
"s": 29967,
"text": "Comments"
},
{
"code": null,
"e": 29989,
"s": 29976,
"text": "Old Comments"
},
{
"code": null,
"e": 30010,
"s": 29989,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30025,
"s": 30010,
"text": "Stream In Java"
},
{
"code": null,
"e": 30044,
"s": 30025,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30074,
"s": 30044,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30120,
"s": 30074,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30146,
"s": 30120,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30182,
"s": 30146,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 30222,
"s": 30182,
"text": "Checked vs Unchecked Exceptions in Java"
},
{
"code": null,
"e": 30238,
"s": 30222,
"text": "Strings in Java"
}
] |
Powershell - Create XML File
|
New-Item cmdlet is used to create a xml file and Set-Content cmdlet to put content into it.
In this example, we're creating a new xml file named test.xml
Type the following command in PowerShell ISE Console
New-Item D:\temp\test\test.xml -ItemType File
You can see the test.xml created in D:\temp\test directory.
In this example, we're adding content to test.xml.
Type the following command in PowerShell ISE Console
Set-Content D:\temp\test\test.xml '<title>Welcome to TutorialsPoint</title>'
In this example, we're reading content of test.xml.
Get-Content D:\temp\test\test.xml
You can see following output in PowerShell console.
<title>Welcome to TutorialsPoint</title>
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2126,
"s": 2034,
"text": "New-Item cmdlet is used to create a xml file and Set-Content cmdlet to put content into it."
},
{
"code": null,
"e": 2188,
"s": 2126,
"text": "In this example, we're creating a new xml file named test.xml"
},
{
"code": null,
"e": 2241,
"s": 2188,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2287,
"s": 2241,
"text": "New-Item D:\\temp\\test\\test.xml -ItemType File"
},
{
"code": null,
"e": 2347,
"s": 2287,
"text": "You can see the test.xml created in D:\\temp\\test directory."
},
{
"code": null,
"e": 2398,
"s": 2347,
"text": "In this example, we're adding content to test.xml."
},
{
"code": null,
"e": 2451,
"s": 2398,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2528,
"s": 2451,
"text": "Set-Content D:\\temp\\test\\test.xml '<title>Welcome to TutorialsPoint</title>'"
},
{
"code": null,
"e": 2580,
"s": 2528,
"text": "In this example, we're reading content of test.xml."
},
{
"code": null,
"e": 2615,
"s": 2580,
"text": "Get-Content D:\\temp\\test\\test.xml\n"
},
{
"code": null,
"e": 2667,
"s": 2615,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 2709,
"s": 2667,
"text": "<title>Welcome to TutorialsPoint</title>\n"
},
{
"code": null,
"e": 2744,
"s": 2709,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2765,
"s": 2744,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2800,
"s": 2765,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2813,
"s": 2800,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2850,
"s": 2813,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2862,
"s": 2850,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2869,
"s": 2862,
"text": " Print"
},
{
"code": null,
"e": 2880,
"s": 2869,
"text": " Add Notes"
}
] |
How to create dismissible alerts in Bootstrap ? - GeeksforGeeks
|
04 Oct, 2021
Alerts are a very important component in the Bootstrap library. They are used to display any message to the users like a form being submitted, OTP is sent or incorrect input entered in the form. In other words, alerts are used to provide feedback messages to the user based on their interaction with the website.
In this article, we will learn how to create a dismissible alert using the bootstrap library. Dismissible alerts make our website like a modern website where we can dismiss the alert after reading it. We will need to load the alert plugin by including the compiled Bootstrap JavaScript on our HTML page.
We can add the close button and use the .alert-dismissible class, which adds extra padding to the right of the alert and positions the close button. On the close button, we use the data-bs-dismiss=”alert” attribute, which triggers the JavaScript functionality. The <button> element is recommended here for proper behavior across all devices. We can use the .fade and .show classes to animate alerts when they are dismissed.
Syntax:
<div class="alert alert-warning alert-dismissible" role="alert">
<strong>Alert!</strong>This is a dismissable alert
<button type="button" class="btn-close"
data-bs-dismiss="alert"
aria-label="Close">
</button>
</div>
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js"> </script> </head> <body class="container"> <h1>Dismissible Alert</h1> <div class="alert alert-warning alert-dismissible fade show" role="alert"> <strong>Alert!</strong> This is a dismissable alert that can be dismissed after clicking on the close button. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"> </button> </div> <p>This is some page text.</p> </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bootstrap-Questions
HTML-Questions
Picked
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to keep gap between columns using Bootstrap?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 25227,
"s": 25199,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 25540,
"s": 25227,
"text": "Alerts are a very important component in the Bootstrap library. They are used to display any message to the users like a form being submitted, OTP is sent or incorrect input entered in the form. In other words, alerts are used to provide feedback messages to the user based on their interaction with the website."
},
{
"code": null,
"e": 25844,
"s": 25540,
"text": "In this article, we will learn how to create a dismissible alert using the bootstrap library. Dismissible alerts make our website like a modern website where we can dismiss the alert after reading it. We will need to load the alert plugin by including the compiled Bootstrap JavaScript on our HTML page."
},
{
"code": null,
"e": 26268,
"s": 25844,
"text": "We can add the close button and use the .alert-dismissible class, which adds extra padding to the right of the alert and positions the close button. On the close button, we use the data-bs-dismiss=”alert” attribute, which triggers the JavaScript functionality. The <button> element is recommended here for proper behavior across all devices. We can use the .fade and .show classes to animate alerts when they are dismissed."
},
{
"code": null,
"e": 26276,
"s": 26268,
"text": "Syntax:"
},
{
"code": null,
"e": 26518,
"s": 26276,
"text": "<div class=\"alert alert-warning alert-dismissible\" role=\"alert\">\n <strong>Alert!</strong>This is a dismissable alert\n <button type=\"button\" class=\"btn-close\" \n data-bs-dismiss=\"alert\"\n aria-label=\"Close\">\n </button>\n</div>"
},
{
"code": null,
"e": 26527,
"s": 26518,
"text": "Example:"
},
{
"code": null,
"e": 26532,
"s": 26527,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Bootstrap CSS --> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css\" rel=\"stylesheet\"> <!-- Bootstrap JS --> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js\"> </script> </head> <body class=\"container\"> <h1>Dismissible Alert</h1> <div class=\"alert alert-warning alert-dismissible fade show\" role=\"alert\"> <strong>Alert!</strong> This is a dismissable alert that can be dismissed after clicking on the close button. <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"alert\" aria-label=\"Close\"> </button> </div> <p>This is some page text.</p> </body></html>",
"e": 27374,
"s": 26532,
"text": null
},
{
"code": null,
"e": 27382,
"s": 27374,
"text": "Output:"
},
{
"code": null,
"e": 27519,
"s": 27382,
"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": 27539,
"s": 27519,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 27554,
"s": 27539,
"text": "HTML-Questions"
},
{
"code": null,
"e": 27561,
"s": 27554,
"text": "Picked"
},
{
"code": null,
"e": 27571,
"s": 27561,
"text": "Bootstrap"
},
{
"code": null,
"e": 27576,
"s": 27571,
"text": "HTML"
},
{
"code": null,
"e": 27593,
"s": 27576,
"text": "Web Technologies"
},
{
"code": null,
"e": 27598,
"s": 27593,
"text": "HTML"
},
{
"code": null,
"e": 27696,
"s": 27598,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27705,
"s": 27696,
"text": "Comments"
},
{
"code": null,
"e": 27718,
"s": 27705,
"text": "Old Comments"
},
{
"code": null,
"e": 27759,
"s": 27718,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 27822,
"s": 27759,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 27855,
"s": 27822,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 27881,
"s": 27855,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 27930,
"s": 27881,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 27992,
"s": 27930,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28042,
"s": 27992,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28102,
"s": 28042,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28150,
"s": 28102,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Getting Min and Max values from a Stream | Java 8 Stream min() max()
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Getting Min and Max values from a Stream in Java 8 is not a big deal, here we will see how it can be done.
Here are our use cases to get min and max values from the stream.
// Numbers
Collection<Integer> elements = Arrays.asList(1,2,3,4,5);
Min = 1
Max = 5
//Strings
Collection<String> strings = Arrays.asList("a1","a2","a3","a4");
Min = a1
max = a4
// Objects
Collection<Student> students = Arrays.asList(new Student("Chandra",30),new Student("Rahul",25)
,new Student("Robert",20));
Younger = Robert
Elder = Chandra
Finding min and max numbers from an integer stream using stream().min() and stream().max() methods.
// Numbers
Collection<Integer> elements = Arrays.asList(1,2,3,4,5);
Integer min = elements.stream().min(Integer::compareTo).get();
Integer max = elements.stream().max(Integer::compareTo).get();
System.out.println("Min value : "+min);
System.out.println("Max value : "+max);
Output:
Min value : 1
Max value : 5
We can even get the min and max values for string; it internally compares the ASCII values.
// Strings
Collection<String> strings = Arrays.asList("a1","a2","a3","a4");
String min_string = strings.stream().min(String::compareTo).get();
String max_string = strings.stream().max(String::compareTo).get();
System.out.println("Min value : "+min_string);
System.out.println("Max value : "+max_string);
Output:
Min value : a1
Max value : a4
Finding the min and max ages from a list of student objects. Create a Student object.
public class Student{
private String name;
private Integer age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Finding elder and younger students based on age.
// Objects
Collection<Student> students = Arrays.asList(new Student("Chandra",30),new Student("Rahul",25)
,new Student("Robert",20));
Student younger = students.stream().min((s1,s2)->s1.getAge().compareTo(s2.getAge())).get();
Student elder = students.stream().max((s1,s2)->s1.getAge().compareTo(s2.getAge())).get();
System.out.println("Younger is : "+younger.getName());
System.out.println("Elder is : "+elder.getName());
Output:
Younger is : Robert
Elder is : Chandra
Java 8 Streams
Happy Learning 🙂
Java 8 How to get common elements from two lists
User defined sorting with Java 8 Comparator
Java 8 Array contains a specific value ?
How to Filter null values from Java8 Stream
How to convert List to Map in Java 8
How to get Stream count in Java 8
How to Convert Iterable to Stream Java 8
Java 8 How to Convert List to String comma separated values
How Java 8 Stream generate random String and Numbers
Java 8 How to convert Stream to List
How to Convert Java 8 Stream to Array
Java 8 Stream API and Parallelism
Java 8 Stream Filter Example with Objects
Java8 Concatenate Arrays Example using Stream
How to Merge Streams in Java 8
Java 8 How to get common elements from two lists
User defined sorting with Java 8 Comparator
Java 8 Array contains a specific value ?
How to Filter null values from Java8 Stream
How to convert List to Map in Java 8
How to get Stream count in Java 8
How to Convert Iterable to Stream Java 8
Java 8 How to Convert List to String comma separated values
How Java 8 Stream generate random String and Numbers
Java 8 How to convert Stream to List
How to Convert Java 8 Stream to Array
Java 8 Stream API and Parallelism
Java 8 Stream Filter Example with Objects
Java8 Concatenate Arrays Example using Stream
How to Merge Streams in Java 8
Δ
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 505,
"s": 398,
"text": "Getting Min and Max values from a Stream in Java 8 is not a big deal, here we will see how it can be done."
},
{
"code": null,
"e": 571,
"s": 505,
"text": "Here are our use cases to get min and max values from the stream."
},
{
"code": null,
"e": 931,
"s": 571,
"text": "// Numbers\nCollection<Integer> elements = Arrays.asList(1,2,3,4,5);\nMin = 1\nMax = 5\n//Strings\nCollection<String> strings = Arrays.asList(\"a1\",\"a2\",\"a3\",\"a4\");\nMin = a1\nmax = a4\n// Objects\nCollection<Student> students = Arrays.asList(new Student(\"Chandra\",30),new Student(\"Rahul\",25)\n ,new Student(\"Robert\",20));\nYounger = Robert\nElder = Chandra"
},
{
"code": null,
"e": 1031,
"s": 931,
"text": "Finding min and max numbers from an integer stream using stream().min() and stream().max() methods."
},
{
"code": null,
"e": 1305,
"s": 1031,
"text": "// Numbers\nCollection<Integer> elements = Arrays.asList(1,2,3,4,5);\nInteger min = elements.stream().min(Integer::compareTo).get();\nInteger max = elements.stream().max(Integer::compareTo).get();\nSystem.out.println(\"Min value : \"+min);\nSystem.out.println(\"Max value : \"+max);"
},
{
"code": null,
"e": 1313,
"s": 1305,
"text": "Output:"
},
{
"code": null,
"e": 1341,
"s": 1313,
"text": "Min value : 1\nMax value : 5"
},
{
"code": null,
"e": 1433,
"s": 1341,
"text": "We can even get the min and max values for string; it internally compares the ASCII values."
},
{
"code": null,
"e": 1737,
"s": 1433,
"text": "// Strings\nCollection<String> strings = Arrays.asList(\"a1\",\"a2\",\"a3\",\"a4\");\nString min_string = strings.stream().min(String::compareTo).get();\nString max_string = strings.stream().max(String::compareTo).get();\nSystem.out.println(\"Min value : \"+min_string);\nSystem.out.println(\"Max value : \"+max_string);"
},
{
"code": null,
"e": 1745,
"s": 1737,
"text": "Output:"
},
{
"code": null,
"e": 1775,
"s": 1745,
"text": "Min value : a1\nMax value : a4"
},
{
"code": null,
"e": 1861,
"s": 1775,
"text": "Finding the min and max ages from a list of student objects. Create a Student object."
},
{
"code": null,
"e": 2291,
"s": 1861,
"text": "public class Student{\n private String name;\n private Integer age;\n\n public Student(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Integer getAge() {\n return age;\n }\n\n public void setAge(Integer age) {\n this.age = age;\n }\n}"
},
{
"code": null,
"e": 2340,
"s": 2291,
"text": "Finding elder and younger students based on age."
},
{
"code": null,
"e": 2770,
"s": 2340,
"text": "// Objects\nCollection<Student> students = Arrays.asList(new Student(\"Chandra\",30),new Student(\"Rahul\",25)\n ,new Student(\"Robert\",20));\nStudent younger = students.stream().min((s1,s2)->s1.getAge().compareTo(s2.getAge())).get();\nStudent elder = students.stream().max((s1,s2)->s1.getAge().compareTo(s2.getAge())).get();\nSystem.out.println(\"Younger is : \"+younger.getName());\nSystem.out.println(\"Elder is : \"+elder.getName());"
},
{
"code": null,
"e": 2778,
"s": 2770,
"text": "Output:"
},
{
"code": null,
"e": 2817,
"s": 2778,
"text": "Younger is : Robert\nElder is : Chandra"
},
{
"code": null,
"e": 2832,
"s": 2817,
"text": "Java 8 Streams"
},
{
"code": null,
"e": 2849,
"s": 2832,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3482,
"s": 2849,
"text": "\nJava 8 How to get common elements from two lists\nUser defined sorting with Java 8 Comparator\nJava 8 Array contains a specific value ?\nHow to Filter null values from Java8 Stream\nHow to convert List to Map in Java 8\nHow to get Stream count in Java 8\nHow to Convert Iterable to Stream Java 8\nJava 8 How to Convert List to String comma separated values\nHow Java 8 Stream generate random String and Numbers\nJava 8 How to convert Stream to List\nHow to Convert Java 8 Stream to Array\nJava 8 Stream API and Parallelism\nJava 8 Stream Filter Example with Objects\nJava8 Concatenate Arrays Example using Stream\nHow to Merge Streams in Java 8\n"
},
{
"code": null,
"e": 3531,
"s": 3482,
"text": "Java 8 How to get common elements from two lists"
},
{
"code": null,
"e": 3575,
"s": 3531,
"text": "User defined sorting with Java 8 Comparator"
},
{
"code": null,
"e": 3616,
"s": 3575,
"text": "Java 8 Array contains a specific value ?"
},
{
"code": null,
"e": 3660,
"s": 3616,
"text": "How to Filter null values from Java8 Stream"
},
{
"code": null,
"e": 3697,
"s": 3660,
"text": "How to convert List to Map in Java 8"
},
{
"code": null,
"e": 3731,
"s": 3697,
"text": "How to get Stream count in Java 8"
},
{
"code": null,
"e": 3772,
"s": 3731,
"text": "How to Convert Iterable to Stream Java 8"
},
{
"code": null,
"e": 3832,
"s": 3772,
"text": "Java 8 How to Convert List to String comma separated values"
},
{
"code": null,
"e": 3885,
"s": 3832,
"text": "How Java 8 Stream generate random String and Numbers"
},
{
"code": null,
"e": 3922,
"s": 3885,
"text": "Java 8 How to convert Stream to List"
},
{
"code": null,
"e": 3960,
"s": 3922,
"text": "How to Convert Java 8 Stream to Array"
},
{
"code": null,
"e": 3994,
"s": 3960,
"text": "Java 8 Stream API and Parallelism"
},
{
"code": null,
"e": 4036,
"s": 3994,
"text": "Java 8 Stream Filter Example with Objects"
},
{
"code": null,
"e": 4082,
"s": 4036,
"text": "Java8 Concatenate Arrays Example using Stream"
},
{
"code": null,
"e": 4113,
"s": 4082,
"text": "How to Merge Streams in Java 8"
},
{
"code": null,
"e": 4119,
"s": 4117,
"text": "Δ"
},
{
"code": null,
"e": 4144,
"s": 4119,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 4161,
"s": 4144,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 4189,
"s": 4161,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 4220,
"s": 4189,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 4252,
"s": 4220,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 4272,
"s": 4252,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 4292,
"s": 4272,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 4316,
"s": 4292,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 4346,
"s": 4316,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 4378,
"s": 4346,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 4414,
"s": 4378,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 4458,
"s": 4414,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 4490,
"s": 4458,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 4531,
"s": 4490,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 4568,
"s": 4531,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4608,
"s": 4568,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 4637,
"s": 4608,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 4669,
"s": 4637,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 4689,
"s": 4669,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 4711,
"s": 4689,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 4741,
"s": 4711,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 4792,
"s": 4741,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 4828,
"s": 4792,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 4860,
"s": 4828,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 4895,
"s": 4860,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 4918,
"s": 4895,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 4965,
"s": 4918,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 4990,
"s": 4965,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 5034,
"s": 4990,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
Russian Car Plate Detection with OpenCV and TesseractOCR | by Kenneth Leung | Towards Data Science
|
1) Motivation and Introduction2) Getting Started3) Car Plate Detection with OpenCV and Haar Cascade4) Plate Number Recognition and Extraction with TesseractOCR
Click here to view the Jupyter Notebook, and here to visit the GitHub repo.
When we talk about AI, computer vision is definitely one of the top applications in people’s minds. Hype aside, I have always been fascinated by it because it pertains to human sight, arguably the most important organ of human sense.
I have come across plenty of computer vision projects involving the human face and/or body. As such, I decided to pursue a project on car license plates instead, which is slightly less explored.
Another reason I worked on this topic is that right after detecting the license plate, it allows for a natural transition into the use of optical character recognition (OCR) to recognize, extract, and display the detected car plate number. Let’s get started!
We will be using Python Jupyter notebook to build our project, along with two open-source software to make the magic happen, namely OpenCV and TesseractOCR. Before we proceed further, here are the steps to get these tools fully set up on your machine.
(i) OpenCVOpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. It mainly focuses on image processing, video capture and analysis, including features like face detection and object detection, and it helps to provide a common infrastructure for computer vision applications.
We install the Python version of OpenCV (in your virtual environment) with the following command:
pip install opencv-python
(ii) Haar Cascade XML FileBesides installing the OpenCV library, another important thing to retrieve is the Haar Cascade XML file.
Let’s first talk about the theory behind Haar Cascades since it is an important concept. In 2001, Paul Viola and Michael Jones came up with the object detection technique using Haar feature-based cascade classifiers. It is a machine learning based approach (involving AdaBoost) where a cascade function is trained from many positive and negative images. It extracts numerical values for features (e.g. edges, lines) efficiently with the concept of integral image (or summed-area table), which trumps the default computationally-heavy way of subtracting sums of pixels across multiple regions of an entire image.
In addition, it uses the ‘Cascade of Classifiers’. This means that instead of applying hundreds of classifiers for the many features within the image at one go (which is very inefficient), the classifiers are applied one by one.
Take for example, an image of a human face. If the first classifier for the ‘eyes’ feature has failed (i.e. fail to detect human eyes in the image), the algorithm does not bother applying the subsequent classifiers (e.g., nose, mouth, etc.). Instead, it stops and declares that no face is detected.
On the other hand, if this first ‘eyes’ feature is detected, the algorithm will apply the second stage of feature classification and continue with the classification process. In the end, if the image passes all classification stages, the algorithm can declare that a face region is present.
OpenCV actually comes with pre-trained XML files of various Haar Cascades, where each XML file contains the feature set. We will be using the Haar Cascade XML file containing the features for Russian car plates, and here’s how you can download the Haar Cascade XML file:
Visit the OpenCV GitHub page containing the Russian car plate Haar Cascade by clicking here.Right-click on the screen (which should be displaying a wall of text with the top line being <?xml version=”1.0"?>), and click ‘Save as..’In the Save option pop-up, you should see the default file name of ‘haarcascade_russian_plate_number’ and file type ‘XML document’. Leave them as the default, and save this XML file in the path where your Jupyter notebook is located.
Visit the OpenCV GitHub page containing the Russian car plate Haar Cascade by clicking here.
Right-click on the screen (which should be displaying a wall of text with the top line being <?xml version=”1.0"?>), and click ‘Save as..’
In the Save option pop-up, you should see the default file name of ‘haarcascade_russian_plate_number’ and file type ‘XML document’. Leave them as the default, and save this XML file in the path where your Jupyter notebook is located.
To explore other XML files available for experimentation, check out the OpenCV Haar Cascades GitHub resource here. If you would like to find out more about the theory of Haar Cascade, visit the OpenCV tutorial here.
(iii) TesseractOCRTesseractOCR is an open-source optical character recognition (OCR) engine. It is recognized as one of the most popular and most accurate open-source OCR engines. The fun fact is that this engine actually started as proprietary software developed by Hewlett Packard but was later open-sourced in 2005, and Google has since sponsored its development.
Here are the instructions for installing TesseractOCR (for Windows):
Install the TesseractOCR application using the Windows installer available at: https://github.com/UB-Mannheim/tesseract/wiki. At the point of this project, I downloaded the 27 Nov 2020 (64 bit) version (tesseract-ocr-w64-setup-v5.0.0-alpha.20201127.exe)Run the downloaded installer and take note of where the application is installed. For me, I installed it inside folderD:\Program Files\Tesseract-OCR . We will be using this folder path later, which is important because we will need to point directly to the tesseract.exe inside the folder.Install the Python version of TesseractOCR (i.e. PyTesseract) in your environment with the following command:
Install the TesseractOCR application using the Windows installer available at: https://github.com/UB-Mannheim/tesseract/wiki. At the point of this project, I downloaded the 27 Nov 2020 (64 bit) version (tesseract-ocr-w64-setup-v5.0.0-alpha.20201127.exe)
Run the downloaded installer and take note of where the application is installed. For me, I installed it inside folderD:\Program Files\Tesseract-OCR . We will be using this folder path later, which is important because we will need to point directly to the tesseract.exe inside the folder.
Install the Python version of TesseractOCR (i.e. PyTesseract) in your environment with the following command:
pip install pytesseract
We can then initialize the above dependencies with the following code:
# Import dependenciesimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport cv2 # This is the OpenCV Python libraryimport pytesseract # This is the TesseractOCR Python library# Set Tesseract CMD path to the location of tesseract.exe filepytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
First of all, we import the input car image we want to work with. Because OpenCV imports images as BGR (Blue-Green-Red) format by default, we will need to run cv2.cvtColor to switch it to RGB format before we ask matplotlib to display the image.
# Read car image and convert color to RGBcarplate_img = cv2.imread('./images/car_image.png')carplate_img_rgb = cv2.cvtColor(carplate_img, cv2.COLOR_BGR2RGB)plt.imshow(carplate_img_rgb)
It’s now time to bring in the Haar Cascade feature set (XML file) for Russian car plates, using OpenCV’s CascadeClassifier function.
# Import Haar Cascade XML file for Russian car plate numberscarplate_haar_cascade = cv2.CascadeClassifier('./haar_cascades/haarcascade_russian_plate_number.xml')
Next, we make use of the detectMultiScale method of the CascadeClassifier to run the detection.
# Setup function to detect car platedef carplate_detect(image): carplate_overlay = image.copy() carplate_rects = carplate_haar_cascade.detectMultiScale(carplate_overlay,scaleFactor=1.1, minNeighbors=3)for x,y,w,h in carplate_rects: cv2.rectangle(carplate_overlay, (x,y), (x+w,y+h), (255,0,0), 5) return carplate_overlay
Let’s briefly talk about the OpenCVdetectMultiScale method. The method allows us to detect objects of different sizes in the input image, and it returns a list of rectangle bounds where objects are detected. For each rectangle, there will be 4 values returned, and they correspond to the following respectively:
x-coordinate of the bottom-left corner of rectangle (x)
y-coordinate of the bottom-left corner of rectangle (y)
width of rectangle (w)
height of the rectangle (h)
The key parameters involved in the detectMultiScale function are scaleFactor and minNeighbors.
scaleFactor specifies how much the image size is reduced at each image scale (as part of the scale pyramid, which is a multi-scale representation of an image). In essence, when object detection models are trained, they are trained to detect objects (i.e. car plates in our case) of a fixed size and might miss car plates that are bigger or smaller than expected. As part of the scale pyramid, the image is resized several times in the hopes that a car plate will end up being a “detectable” size. I used the default scale factor of 1.1, which means that OpenCV will scale the image down by 10% to try and match the car plates better.
minNeighbors allows us to specify how many neighbors each candidate rectangle should have for the candidate rectangle to be retained. In simpler terms, this parameter influences the quality of the detected objects. A higher value results in fewer detections, but the detections come with higher quality and accuracy. This means that a higher value can actually help with reducing the number of false positives. For my case, the default value of 3 gave me several false positives, so I increased it to 5.
We can tune these two parameters accordingly to improve your results. For more details, check out the OpenCV documentation here.
Let’s now run our function for car plate detection:
detected_carplate_img = carplate_detect(carplate_img_rgb)plt.imshow(detected_carplate_img)
We can see that our function worked a treat! The car license plate has been successfully detected and bounded by a red rectangle. Our next step is to focus on the license plate and work towards extracting the numbers and text of the car plate using OCR capabilities.
To ensure the success of the OCR function, we need to perform a series of image processing steps. Let’s start by isolating the car license plate as an image. We do that by setting up a function similar to what we have done earlier with car plate detection, just that this time we will be extracting and returning the region of interest (car plate) as a new image.
# Create function to retrieve only the car plate region itselfdef carplate_extract(image): carplate_rects = carplate_haar_cascade.detectMultiScale(image,scaleFactor=1.1, minNeighbors=5)for x,y,w,h in carplate_rects: carplate_img = image[y+15:y+h-10 ,x+15:x+w-20] # Adjusted to extract specific region of interest i.e. car license plate return carplate_img
In addition, we will also want to enlarge our car license plate (using OpenCV’s resizemethod) since it was only a small segment of the original input image.
# Enlarge image for further processing later ondef enlarge_img(image, scale_percent): width = int(image.shape[1] * scale_percent / 100) height = int(image.shape[0] * scale_percent / 100) dim = (width, height) resized_image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA) return resized_image
Running these two functions will give us our region of interest, the car license plate itself (termed as carplate_extract_img).
# Display extracted car license plate imagecarplate_extract_img = carplate_extract(carplate_img_rgb)carplate_extract_img = enlarge_img(carplate_extract_img, 150)plt.imshow(carplate_extract_img);
Next up is to convert the image from RGB color to grayscale. The purpose of this is to decrease the amount of colors in the image, which may interfere with the OCR detection. This is because we want to focus on the important edges and shapes of the image, and converting to grayscale helps to optimize this detection process.
# Convert image to grayscalecarplate_extract_img_gray = cv2.cvtColor(carplate_extract_img, cv2.COLOR_RGB2GRAY)plt.axis('off') plt.imshow(carplate_extract_img_gray, cmap = 'gray');
Next, we apply smoothing on the image. The smoothing technique helps to get rid of noise and makes the application focus on the general details of the image. This is essentially what we call a denoising step, making the text characters in the image more distinct and recognizable.
I used median blur for the smoothing (usingcv2.medianBlur), which computes the median of all the pixels under the kernel window and replaces the central pixel with this median value. For this project, I discovered that median blur was particularly effective (definitely more so than Gaussian blur), and therefore median blur was demonstrated here.
# Apply median blurcarplate_extract_img_gray_blur = cv2.medianBlur(carplate_extract_img_gray,3) # kernel size 3plt.axis('off') plt.imshow(carplate_extract_img_gray_blur, cmap = 'gray');
The visual difference is perhaps subtle, but if you were to compare the two images closely, you would notice that the edges of the characters are slightly smoother and less jagged. After these transformations, our image is now ready for OCR application. For other images, if a higher degree of smoothing is required, you can always increase the kernel size from the size 3 I used here. Let’s pass the image into the PyTesseract image_to_string function:
# Display the text extracted from the car plateprint(pytesseract.image_to_string(carplate_extract_img_gray_blur, config = f'--psm 8 --oem 3 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'))
Woohoo, the printed text of ‘T111TT97’ does match the characters on our car license plate image!
Some additional details about the above PyTesseract image_to_string function. You might have noticed that the config parameter contains several other parameters (aka flags):
tessedit_char_whitelist helps to restrict the TesseractOCR function to a set of pre-defined (white-listed) characters. Since we know that the license plate text ranges from 0–9 and A-Z, we can specify it.
--oem refers to OCR Engine Mode (OEM), and the value corresponds to whichever engine mode we want. For this case, I used the default engine based on what is available, which is mode number 3 (--oem 3). Here are the details of the various OCR Engine Modes we can utilize:
--psm refers to Page Segmentation Modes (PSM), which allows us to get TesseractOCR to run a subset of layout analysis and assume a certain form of an image. Details of the various supported options are shown below:
Since our car license image is to be treated as a single word (i.e. PSM option number 8), I used the value of --psm 8 within the config parameter. Out of curiosity, I also experimented with all the different possible PSM options:
# Testing all PSM valuesfor i in range(3,14): print(f'PSM: {i}') print(pytesseract.image_to_string(carplate_extract_img_gray_blur, config = f'--psm {i} --oem 3 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'))
We can see that different PSM options lead to varying outcomes, so it is crucial to set the appropriate PSM option for your particular image.
In this tutorial, we covered how to set up OpenCV and TesseractOCR (in the form of PyTesseract) within Python and how to use their powerful in-built functions to detect car license plates (of Russian cars) and extract the text from these number plates.
On top of that, we also discussed several theoretical concepts such as Haar Cascades, multi-scale detection parameters, image processing for optimized recognition, and TesseractOCR’s page segmentation modes (PSM).
This project serves as a stepping stone for larger scale (and more advanced) computer vision projects, such as bulk extraction of car license plate text from large image quantities and applying these concepts on video files or live feed.
I welcome you to join me on a data science learning journey! Follow this Medium page and check out my GitHub to stay in the loop of more exciting data science content. Have fun applying OCR on vehicle plate numbers!
|
[
{
"code": null,
"e": 332,
"s": 172,
"text": "1) Motivation and Introduction2) Getting Started3) Car Plate Detection with OpenCV and Haar Cascade4) Plate Number Recognition and Extraction with TesseractOCR"
},
{
"code": null,
"e": 408,
"s": 332,
"text": "Click here to view the Jupyter Notebook, and here to visit the GitHub repo."
},
{
"code": null,
"e": 642,
"s": 408,
"text": "When we talk about AI, computer vision is definitely one of the top applications in people’s minds. Hype aside, I have always been fascinated by it because it pertains to human sight, arguably the most important organ of human sense."
},
{
"code": null,
"e": 837,
"s": 642,
"text": "I have come across plenty of computer vision projects involving the human face and/or body. As such, I decided to pursue a project on car license plates instead, which is slightly less explored."
},
{
"code": null,
"e": 1096,
"s": 837,
"text": "Another reason I worked on this topic is that right after detecting the license plate, it allows for a natural transition into the use of optical character recognition (OCR) to recognize, extract, and display the detected car plate number. Let’s get started!"
},
{
"code": null,
"e": 1348,
"s": 1096,
"text": "We will be using Python Jupyter notebook to build our project, along with two open-source software to make the magic happen, namely OpenCV and TesseractOCR. Before we proceed further, here are the steps to get these tools fully set up on your machine."
},
{
"code": null,
"e": 1686,
"s": 1348,
"text": "(i) OpenCVOpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. It mainly focuses on image processing, video capture and analysis, including features like face detection and object detection, and it helps to provide a common infrastructure for computer vision applications."
},
{
"code": null,
"e": 1784,
"s": 1686,
"text": "We install the Python version of OpenCV (in your virtual environment) with the following command:"
},
{
"code": null,
"e": 1810,
"s": 1784,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 1941,
"s": 1810,
"text": "(ii) Haar Cascade XML FileBesides installing the OpenCV library, another important thing to retrieve is the Haar Cascade XML file."
},
{
"code": null,
"e": 2553,
"s": 1941,
"text": "Let’s first talk about the theory behind Haar Cascades since it is an important concept. In 2001, Paul Viola and Michael Jones came up with the object detection technique using Haar feature-based cascade classifiers. It is a machine learning based approach (involving AdaBoost) where a cascade function is trained from many positive and negative images. It extracts numerical values for features (e.g. edges, lines) efficiently with the concept of integral image (or summed-area table), which trumps the default computationally-heavy way of subtracting sums of pixels across multiple regions of an entire image."
},
{
"code": null,
"e": 2782,
"s": 2553,
"text": "In addition, it uses the ‘Cascade of Classifiers’. This means that instead of applying hundreds of classifiers for the many features within the image at one go (which is very inefficient), the classifiers are applied one by one."
},
{
"code": null,
"e": 3081,
"s": 2782,
"text": "Take for example, an image of a human face. If the first classifier for the ‘eyes’ feature has failed (i.e. fail to detect human eyes in the image), the algorithm does not bother applying the subsequent classifiers (e.g., nose, mouth, etc.). Instead, it stops and declares that no face is detected."
},
{
"code": null,
"e": 3372,
"s": 3081,
"text": "On the other hand, if this first ‘eyes’ feature is detected, the algorithm will apply the second stage of feature classification and continue with the classification process. In the end, if the image passes all classification stages, the algorithm can declare that a face region is present."
},
{
"code": null,
"e": 3643,
"s": 3372,
"text": "OpenCV actually comes with pre-trained XML files of various Haar Cascades, where each XML file contains the feature set. We will be using the Haar Cascade XML file containing the features for Russian car plates, and here’s how you can download the Haar Cascade XML file:"
},
{
"code": null,
"e": 4107,
"s": 3643,
"text": "Visit the OpenCV GitHub page containing the Russian car plate Haar Cascade by clicking here.Right-click on the screen (which should be displaying a wall of text with the top line being <?xml version=”1.0\"?>), and click ‘Save as..’In the Save option pop-up, you should see the default file name of ‘haarcascade_russian_plate_number’ and file type ‘XML document’. Leave them as the default, and save this XML file in the path where your Jupyter notebook is located."
},
{
"code": null,
"e": 4200,
"s": 4107,
"text": "Visit the OpenCV GitHub page containing the Russian car plate Haar Cascade by clicking here."
},
{
"code": null,
"e": 4339,
"s": 4200,
"text": "Right-click on the screen (which should be displaying a wall of text with the top line being <?xml version=”1.0\"?>), and click ‘Save as..’"
},
{
"code": null,
"e": 4573,
"s": 4339,
"text": "In the Save option pop-up, you should see the default file name of ‘haarcascade_russian_plate_number’ and file type ‘XML document’. Leave them as the default, and save this XML file in the path where your Jupyter notebook is located."
},
{
"code": null,
"e": 4789,
"s": 4573,
"text": "To explore other XML files available for experimentation, check out the OpenCV Haar Cascades GitHub resource here. If you would like to find out more about the theory of Haar Cascade, visit the OpenCV tutorial here."
},
{
"code": null,
"e": 5156,
"s": 4789,
"text": "(iii) TesseractOCRTesseractOCR is an open-source optical character recognition (OCR) engine. It is recognized as one of the most popular and most accurate open-source OCR engines. The fun fact is that this engine actually started as proprietary software developed by Hewlett Packard but was later open-sourced in 2005, and Google has since sponsored its development."
},
{
"code": null,
"e": 5225,
"s": 5156,
"text": "Here are the instructions for installing TesseractOCR (for Windows):"
},
{
"code": null,
"e": 5877,
"s": 5225,
"text": "Install the TesseractOCR application using the Windows installer available at: https://github.com/UB-Mannheim/tesseract/wiki. At the point of this project, I downloaded the 27 Nov 2020 (64 bit) version (tesseract-ocr-w64-setup-v5.0.0-alpha.20201127.exe)Run the downloaded installer and take note of where the application is installed. For me, I installed it inside folderD:\\Program Files\\Tesseract-OCR . We will be using this folder path later, which is important because we will need to point directly to the tesseract.exe inside the folder.Install the Python version of TesseractOCR (i.e. PyTesseract) in your environment with the following command:"
},
{
"code": null,
"e": 6131,
"s": 5877,
"text": "Install the TesseractOCR application using the Windows installer available at: https://github.com/UB-Mannheim/tesseract/wiki. At the point of this project, I downloaded the 27 Nov 2020 (64 bit) version (tesseract-ocr-w64-setup-v5.0.0-alpha.20201127.exe)"
},
{
"code": null,
"e": 6421,
"s": 6131,
"text": "Run the downloaded installer and take note of where the application is installed. For me, I installed it inside folderD:\\Program Files\\Tesseract-OCR . We will be using this folder path later, which is important because we will need to point directly to the tesseract.exe inside the folder."
},
{
"code": null,
"e": 6531,
"s": 6421,
"text": "Install the Python version of TesseractOCR (i.e. PyTesseract) in your environment with the following command:"
},
{
"code": null,
"e": 6555,
"s": 6531,
"text": "pip install pytesseract"
},
{
"code": null,
"e": 6626,
"s": 6555,
"text": "We can then initialize the above dependencies with the following code:"
},
{
"code": null,
"e": 6970,
"s": 6626,
"text": "# Import dependenciesimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlineimport cv2 # This is the OpenCV Python libraryimport pytesseract # This is the TesseractOCR Python library# Set Tesseract CMD path to the location of tesseract.exe filepytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'"
},
{
"code": null,
"e": 7216,
"s": 6970,
"text": "First of all, we import the input car image we want to work with. Because OpenCV imports images as BGR (Blue-Green-Red) format by default, we will need to run cv2.cvtColor to switch it to RGB format before we ask matplotlib to display the image."
},
{
"code": null,
"e": 7401,
"s": 7216,
"text": "# Read car image and convert color to RGBcarplate_img = cv2.imread('./images/car_image.png')carplate_img_rgb = cv2.cvtColor(carplate_img, cv2.COLOR_BGR2RGB)plt.imshow(carplate_img_rgb)"
},
{
"code": null,
"e": 7534,
"s": 7401,
"text": "It’s now time to bring in the Haar Cascade feature set (XML file) for Russian car plates, using OpenCV’s CascadeClassifier function."
},
{
"code": null,
"e": 7696,
"s": 7534,
"text": "# Import Haar Cascade XML file for Russian car plate numberscarplate_haar_cascade = cv2.CascadeClassifier('./haar_cascades/haarcascade_russian_plate_number.xml')"
},
{
"code": null,
"e": 7792,
"s": 7696,
"text": "Next, we make use of the detectMultiScale method of the CascadeClassifier to run the detection."
},
{
"code": null,
"e": 8135,
"s": 7792,
"text": "# Setup function to detect car platedef carplate_detect(image): carplate_overlay = image.copy() carplate_rects = carplate_haar_cascade.detectMultiScale(carplate_overlay,scaleFactor=1.1, minNeighbors=3)for x,y,w,h in carplate_rects: cv2.rectangle(carplate_overlay, (x,y), (x+w,y+h), (255,0,0), 5) return carplate_overlay"
},
{
"code": null,
"e": 8447,
"s": 8135,
"text": "Let’s briefly talk about the OpenCVdetectMultiScale method. The method allows us to detect objects of different sizes in the input image, and it returns a list of rectangle bounds where objects are detected. For each rectangle, there will be 4 values returned, and they correspond to the following respectively:"
},
{
"code": null,
"e": 8503,
"s": 8447,
"text": "x-coordinate of the bottom-left corner of rectangle (x)"
},
{
"code": null,
"e": 8559,
"s": 8503,
"text": "y-coordinate of the bottom-left corner of rectangle (y)"
},
{
"code": null,
"e": 8582,
"s": 8559,
"text": "width of rectangle (w)"
},
{
"code": null,
"e": 8610,
"s": 8582,
"text": "height of the rectangle (h)"
},
{
"code": null,
"e": 8705,
"s": 8610,
"text": "The key parameters involved in the detectMultiScale function are scaleFactor and minNeighbors."
},
{
"code": null,
"e": 9339,
"s": 8705,
"text": "scaleFactor specifies how much the image size is reduced at each image scale (as part of the scale pyramid, which is a multi-scale representation of an image). In essence, when object detection models are trained, they are trained to detect objects (i.e. car plates in our case) of a fixed size and might miss car plates that are bigger or smaller than expected. As part of the scale pyramid, the image is resized several times in the hopes that a car plate will end up being a “detectable” size. I used the default scale factor of 1.1, which means that OpenCV will scale the image down by 10% to try and match the car plates better."
},
{
"code": null,
"e": 9843,
"s": 9339,
"text": "minNeighbors allows us to specify how many neighbors each candidate rectangle should have for the candidate rectangle to be retained. In simpler terms, this parameter influences the quality of the detected objects. A higher value results in fewer detections, but the detections come with higher quality and accuracy. This means that a higher value can actually help with reducing the number of false positives. For my case, the default value of 3 gave me several false positives, so I increased it to 5."
},
{
"code": null,
"e": 9972,
"s": 9843,
"text": "We can tune these two parameters accordingly to improve your results. For more details, check out the OpenCV documentation here."
},
{
"code": null,
"e": 10024,
"s": 9972,
"text": "Let’s now run our function for car plate detection:"
},
{
"code": null,
"e": 10115,
"s": 10024,
"text": "detected_carplate_img = carplate_detect(carplate_img_rgb)plt.imshow(detected_carplate_img)"
},
{
"code": null,
"e": 10382,
"s": 10115,
"text": "We can see that our function worked a treat! The car license plate has been successfully detected and bounded by a red rectangle. Our next step is to focus on the license plate and work towards extracting the numbers and text of the car plate using OCR capabilities."
},
{
"code": null,
"e": 10746,
"s": 10382,
"text": "To ensure the success of the OCR function, we need to perform a series of image processing steps. Let’s start by isolating the car license plate as an image. We do that by setting up a function similar to what we have done earlier with car plate detection, just that this time we will be extracting and returning the region of interest (car plate) as a new image."
},
{
"code": null,
"e": 11128,
"s": 10746,
"text": "# Create function to retrieve only the car plate region itselfdef carplate_extract(image): carplate_rects = carplate_haar_cascade.detectMultiScale(image,scaleFactor=1.1, minNeighbors=5)for x,y,w,h in carplate_rects: carplate_img = image[y+15:y+h-10 ,x+15:x+w-20] # Adjusted to extract specific region of interest i.e. car license plate return carplate_img"
},
{
"code": null,
"e": 11285,
"s": 11128,
"text": "In addition, we will also want to enlarge our car license plate (using OpenCV’s resizemethod) since it was only a small segment of the original input image."
},
{
"code": null,
"e": 11601,
"s": 11285,
"text": "# Enlarge image for further processing later ondef enlarge_img(image, scale_percent): width = int(image.shape[1] * scale_percent / 100) height = int(image.shape[0] * scale_percent / 100) dim = (width, height) resized_image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA) return resized_image"
},
{
"code": null,
"e": 11729,
"s": 11601,
"text": "Running these two functions will give us our region of interest, the car license plate itself (termed as carplate_extract_img)."
},
{
"code": null,
"e": 11924,
"s": 11729,
"text": "# Display extracted car license plate imagecarplate_extract_img = carplate_extract(carplate_img_rgb)carplate_extract_img = enlarge_img(carplate_extract_img, 150)plt.imshow(carplate_extract_img);"
},
{
"code": null,
"e": 12250,
"s": 11924,
"text": "Next up is to convert the image from RGB color to grayscale. The purpose of this is to decrease the amount of colors in the image, which may interfere with the OCR detection. This is because we want to focus on the important edges and shapes of the image, and converting to grayscale helps to optimize this detection process."
},
{
"code": null,
"e": 12430,
"s": 12250,
"text": "# Convert image to grayscalecarplate_extract_img_gray = cv2.cvtColor(carplate_extract_img, cv2.COLOR_RGB2GRAY)plt.axis('off') plt.imshow(carplate_extract_img_gray, cmap = 'gray');"
},
{
"code": null,
"e": 12711,
"s": 12430,
"text": "Next, we apply smoothing on the image. The smoothing technique helps to get rid of noise and makes the application focus on the general details of the image. This is essentially what we call a denoising step, making the text characters in the image more distinct and recognizable."
},
{
"code": null,
"e": 13059,
"s": 12711,
"text": "I used median blur for the smoothing (usingcv2.medianBlur), which computes the median of all the pixels under the kernel window and replaces the central pixel with this median value. For this project, I discovered that median blur was particularly effective (definitely more so than Gaussian blur), and therefore median blur was demonstrated here."
},
{
"code": null,
"e": 13245,
"s": 13059,
"text": "# Apply median blurcarplate_extract_img_gray_blur = cv2.medianBlur(carplate_extract_img_gray,3) # kernel size 3plt.axis('off') plt.imshow(carplate_extract_img_gray_blur, cmap = 'gray');"
},
{
"code": null,
"e": 13699,
"s": 13245,
"text": "The visual difference is perhaps subtle, but if you were to compare the two images closely, you would notice that the edges of the characters are slightly smoother and less jagged. After these transformations, our image is now ready for OCR application. For other images, if a higher degree of smoothing is required, you can always increase the kernel size from the size 3 I used here. Let’s pass the image into the PyTesseract image_to_string function:"
},
{
"code": null,
"e": 13940,
"s": 13699,
"text": "# Display the text extracted from the car plateprint(pytesseract.image_to_string(carplate_extract_img_gray_blur, config = f'--psm 8 --oem 3 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'))"
},
{
"code": null,
"e": 14037,
"s": 13940,
"text": "Woohoo, the printed text of ‘T111TT97’ does match the characters on our car license plate image!"
},
{
"code": null,
"e": 14211,
"s": 14037,
"text": "Some additional details about the above PyTesseract image_to_string function. You might have noticed that the config parameter contains several other parameters (aka flags):"
},
{
"code": null,
"e": 14416,
"s": 14211,
"text": "tessedit_char_whitelist helps to restrict the TesseractOCR function to a set of pre-defined (white-listed) characters. Since we know that the license plate text ranges from 0–9 and A-Z, we can specify it."
},
{
"code": null,
"e": 14687,
"s": 14416,
"text": "--oem refers to OCR Engine Mode (OEM), and the value corresponds to whichever engine mode we want. For this case, I used the default engine based on what is available, which is mode number 3 (--oem 3). Here are the details of the various OCR Engine Modes we can utilize:"
},
{
"code": null,
"e": 14902,
"s": 14687,
"text": "--psm refers to Page Segmentation Modes (PSM), which allows us to get TesseractOCR to run a subset of layout analysis and assume a certain form of an image. Details of the various supported options are shown below:"
},
{
"code": null,
"e": 15132,
"s": 14902,
"text": "Since our car license image is to be treated as a single word (i.e. PSM option number 8), I used the value of --psm 8 within the config parameter. Out of curiosity, I also experimented with all the different possible PSM options:"
},
{
"code": null,
"e": 15400,
"s": 15132,
"text": "# Testing all PSM valuesfor i in range(3,14): print(f'PSM: {i}') print(pytesseract.image_to_string(carplate_extract_img_gray_blur, config = f'--psm {i} --oem 3 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'))"
},
{
"code": null,
"e": 15542,
"s": 15400,
"text": "We can see that different PSM options lead to varying outcomes, so it is crucial to set the appropriate PSM option for your particular image."
},
{
"code": null,
"e": 15795,
"s": 15542,
"text": "In this tutorial, we covered how to set up OpenCV and TesseractOCR (in the form of PyTesseract) within Python and how to use their powerful in-built functions to detect car license plates (of Russian cars) and extract the text from these number plates."
},
{
"code": null,
"e": 16009,
"s": 15795,
"text": "On top of that, we also discussed several theoretical concepts such as Haar Cascades, multi-scale detection parameters, image processing for optimized recognition, and TesseractOCR’s page segmentation modes (PSM)."
},
{
"code": null,
"e": 16247,
"s": 16009,
"text": "This project serves as a stepping stone for larger scale (and more advanced) computer vision projects, such as bulk extraction of car license plate text from large image quantities and applying these concepts on video files or live feed."
}
] |
JDBC - Quick Guide
|
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage.
Making a connection to a database.
Making a connection to a database.
Creating SQL or MySQL statements.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as −
Java Applications
Java Applications
Java Applets
Java Applets
Java Servlets
Java Servlets
Java ServerPages (JSPs)
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.
Before moving further, you need to have a good understanding of the following two subjects −
Core JAVA Programming
Core JAVA Programming
SQL or MySQL Database
SQL or MySQL Database
The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers −
JDBC API − This provides the application-to-JDBC Manager connection.
JDBC API − This provides the application-to-JDBC Manager connection.
JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application −
The JDBC API provides the following interfaces and classes −
DriverManager − This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
DriverManager − This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
Driver − This interface handles the communications with the database server. You will interact directly with Driver
objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.
Driver − This interface handles the communications with the database server. You will interact directly with Driver
objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.
Connection − This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only.
Connection − This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only.
Statement − You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures.
Statement − You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures.
ResultSet − These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data.
ResultSet − These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data.
SQLException − This class handles any errors that occur in a database application.
SQLException − This class handles any errors that occur in a database application.
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at the time of writing this tutorial. It offers the main classes for interacting with your data sources.
The new features in these packages include changes in the following areas −
Automatic database driver loading.
Automatic database driver loading.
Exception handling improvements.
Exception handling improvements.
Enhanced BLOB/CLOB functionality.
Enhanced BLOB/CLOB functionality.
Connection and statement interface enhancements.
Connection and statement interface enhancements.
National character set support.
National character set support.
SQL ROWID access.
SQL ROWID access.
SQL 2003 XML data type support.
SQL 2003 XML data type support.
Annotations.
Annotations.
Structured Query Language (SQL) is a standardized language that allows you to perform operations on a database, such as creating entries, reading content, updating content, and deleting entries.
SQL is supported by almost any database you will likely use, and it allows you to write database code independently of the underlying database.
This chapter gives an overview of SQL, which is a prerequisite to understand JDBC concepts. After going through this chapter, you will be able to Create, Create, Read, Update, and Delete (often referred to as CRUD operations) data from a database.
For a detailed understanding on SQL, you can read our MySQL Tutorial.
The CREATE DATABASE statement is used for creating a new database. The syntax is −
SQL> CREATE DATABASE DATABASE_NAME;
The following SQL statement creates a Database named EMP −
SQL> CREATE DATABASE EMP;
The DROP DATABASE statement is used for deleting an existing database. The syntax is −
SQL> DROP DATABASE DATABASE_NAME;
Note − To create or drop a database you should have administrator privilege on your database server. Be careful, deleting a database would loss all the data stored in the database.
The CREATE TABLE statement is used for creating a new table. The syntax is −
SQL> CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type
...
);
The following SQL statement creates a table named Employees with four columns −
SQL> CREATE TABLE Employees
(
id INT NOT NULL,
age INT NOT NULL,
first VARCHAR(255),
last VARCHAR(255),
PRIMARY KEY ( id )
);
The DROP TABLE statement is used for deleting an existing table. The syntax is −
SQL> DROP TABLE table_name;
The following SQL statement deletes a table named Employees −
SQL> DROP TABLE Employees;
The syntax for INSERT, looks similar to the following, where column1, column2, and so on represents the new data to appear in the
respective columns −
SQL> INSERT INTO table_name VALUES (column1, column2, ...);
The following SQL INSERT statement inserts a new row in the Employees database created earlier −
SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
The SELECT statement is used to retrieve data from a database. The syntax for SELECT is −
SQL> SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators.
The following SQL statement selects the age, first and last columns from the Employees table, where id column is 100 −
SQL> SELECT first, last, age
FROM Employees
WHERE id = 100;
The following SQL statement selects the age, first and last columns from the Employees table where first column contains Zara −
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%Zara%';
The UPDATE statement is used to update data. The syntax for UPDATE is −
SQL> UPDATE table_name
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators.
The following SQL UPDATE statement changes the age column of the employee whose id is 100 −
SQL> UPDATE Employees SET age=20 WHERE id=100;
The DELETE statement is used to delete data from tables. The syntax for DELETE is −
SQL> DELETE FROM table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators.
The following SQL DELETE statement deletes the record of the employee whose id is 100 −
SQL> DELETE FROM Employees WHERE id=100;
To start developing with JDBC, you should setup your JDBC environment by following the steps shown below. We assume that you are working on a Windows platform.
Java SE is available for download for free. To download click here, please download a version compatible with your operating system.
Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Edit the 'C:\autoexec.bat' file and add the following line at the end −
Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH = %PATH%;C:\Program Files\java\jdk\bin
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −
export PATH = /path/to/java:$PATH'
You automatically get both JDBC packages java.sql and javax.sql, when you install J2SE Development Kit.
The most important thing you will need, of course is an actual running database with a table that you can query and modify.
Install a database that is most suitable for you. You can have plenty of choices and most common are −
MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation.
In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier.
Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8.
Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation.
MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation.
In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier.
Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8.
Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation.
When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice.
Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application.
There are various database operations like database creation and deletion, which would need administrator ID and password.
For rest of the JDBC tutorial, we would use MySQL Database with guest as ID and guest123 as password.
If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you.
To create the TUTORIALSPOINT database, use the following steps −
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server.
Start the database server by executing the following command, if it is already not running.
C:\Program Files\MySQL\bin>mysqld
C:\Program Files\MySQL\bin>
Create the TUTORIALSPOINT database by executing the following command −
C:\Program Files\MySQL\bin> mysqladmin create TUTORIALSPOINT -u guest -p
Enter password: ********
C:\Program Files\MySQL\bin>
To create the Employees table in TUTORIALSPOINT database, use the following steps −
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u guest -p
Enter password: ********
mysql>
Create the table Employees as follows −
mysql> use TUTORIALSPOINT;
mysql> create table Employees
-> (
-> id int not null,
-> age int not null,
-> first varchar (255),
-> last varchar (255)
-> );
Query OK, 0 rows affected (0.08 sec)
mysql>
Finally you create few records in Employee table as follows −
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)
mysql>
For a complete understanding on MySQL database, study the MySQL Tutorial.
Now you are ready to start experimenting with JDBC. Next chapter gives you a sample example on JDBC Programming.
This chapter provides an example of how to create a simple JDBC application. This will show you how to open a database connection, execute a SQL query, and display the results.
All the steps mentioned in this template example, would be explained in subsequent chapters of this tutorial.
There are following six steps involved in building a JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to
retrieve the data from the result set.
Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to
retrieve the data from the result set.
Clean up the environment − Requires explicitly closing all database resources versus relying on the JVM's garbage collection.
Clean up the environment − Requires explicitly closing all database resources versus relying on the JVM's garbage collection.
This sample example can serve as a template when you need to create your own JDBC application in the future.
This sample code has been written based on the environment and database setup done in the previous chapter.
Copy and paste the following example in FirstExample.java, compile and run as follows −
import java.sql.*;
public class FirstExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces the following result −
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server.
For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driver interface in their database driver.
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is explained below −
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine.
If we change the Database, we have to change the native API, as it is specific to a database and they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the nuances will prove helpful.
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database through socket connection. This is the highest performance driver
available for the database and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only.
After you've installed the appropriate driver, it is time to establish a database connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps −
Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code.
Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code.
Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.
Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.
Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect.
Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect.
Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection.
Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection.
The Import statements tell the Java compiler where to find the classes you reference in your code and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL tables, add the following imports to your source code −
import java.sql.* ; // for standard JDBC programs
import java.math.* ; // for BigDecimal and BigInteger support
You must register the driver in your program before you use it. Registering the driver is the process by which the Oracle driver's class file is loaded into the memory,
so it can be utilized as an implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a driver in one of two ways.
The most common approach to register a driver is to use Java's Class.forName() method, to dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver −
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
You can use getInstance() method to work around noncompliant JVMs, but then you'll have to code for two extra Exceptions as follows −
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}
The second approach you can use to register a driver, is to use the static DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver −
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
After you've loaded the driver, you can establish a connection using the DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods −
getConnection(String url)
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your database.
Formulating a database URL is where most of the problems associated with establishing a connection occurs.
Following table lists down the popular JDBC driver names and database URL.
All the highlighted part in URL format is static and you need to change only the remaining part as per your database setup.
We have listed down three forms of DriverManager.getConnection() method to create a connection object.
The most commonly used form of getConnection() requires you to pass a database URL, a username, and a password −
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for the database portion of the URL.
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle listener is configured to listen on port 1521, and your database name is EMP, then complete database URL would be −
jdbc:oracle:thin:@amrood:1521:EMP
Now you have to call getConnection() method with appropriate username and password to get a Connection object as follows −
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
A second form of the DriverManager.getConnection( ) method requires only a database URL −
DriverManager.getConnection(String url);
However, in this case, the database URL includes the username and password and has the following general form −
jdbc:oracle:driver:username/password@database
So, the above connection can be created as follows −
String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = DriverManager.getConnection(URL);
A third form of the DriverManager.getConnection( ) method requires a database URL and a Properties object −
DriverManager.getConnection(String url, Properties info);
A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to the driver during a call to the getConnection() method.
To make the same connection made by the previous examples, use the following code −
import java.util.*;
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );
Connection conn = DriverManager.getConnection(URL, info);
At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if
you forget, Java's garbage collector will close the connection when it cleans up stale objects.
Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object.
To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless of an exception occurs or not.
To close the above opened connection, you should call close() method as follows −
conn.close();
Explicitly closing a connection conserves DBMS resources, which will make your database administrator happy.
For a better understanding, we suggest you to study our JDBC - Sample Code tutorial.
Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database.
They also define methods that help bridge data type differences between Java and SQL data types used in a database.
The following table provides a summary of each interface's purpose to decide on the interface to use.
Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement( ) method, as in the following example −
Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three execute methods.
boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.
boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.
int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.
int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.
ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.
ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.
Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the Statement object as well. However, you should always explicitly close the Statement object to ensure proper cleanup.
Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
stmt.close();
}
For a better understanding, we suggest you to study the Statement - Example tutorial.
The PreparedStatement interface extends the Statement interface, which gives you added functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must supply values for every parameter before executing the SQL statement.
The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException.
Each parameter marker is referred by its ordinal position. The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java array indices, which starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use SQL statements that can input the parameters.
Just as you close a Statement object, for the same reason you should also close the PreparedStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
pstmt.close();
}
For a better understanding, let us study Prepare - Example Code.
Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure.
Suppose, you need to execute the following Oracle stored procedure −
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
NOTE − Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database −
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three.
Here are the definitions of each −
The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
The String variable SQL, represents the stored procedure, with parameter placeholders.
Using the CallableStatement objects is much like using the PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding.
When you use OUT and INOUT parameters you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type, to the data type that the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type.
Just as you close other Statement object, for the same reason you should also close the CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
cstmt.close();
}
For a better understanding, I would suggest to study Callable - Example Code.
The SQL statements that read data from a database query, return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The java.sql.ResultSet interface represents the result set of a database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The term "result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
Navigational methods − Used to move the cursor around.
Navigational methods − Used to move the cursor around.
Get methods − Used to view the data in the columns of the current row being pointed by the cursor.
Get methods − Used to view the data in the columns of the current row being pointed by the cursor.
Update methods − Used to update the data in the columns of the current row. The updates can then be updated in the underlying database as well.
Update methods − Used to update the data in the columns of the current row. The updates can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are designated when the corresponding Statement that generates the ResultSet is created.
JDBC provides the following connection methods to create statements with desired ResultSet −
createStatement(int RSType, int RSConcurrency);
createStatement(int RSType, int RSConcurrency);
prepareStatement(String SQL, int RSType, int RSConcurrency);
prepareStatement(String SQL, int RSType, int RSConcurrency);
prepareCall(String sql, int RSType, int RSConcurrency);
prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable.
The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get one that is TYPE_FORWARD_ONLY.
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY.
All our examples written so far can be written as follows, which initializes a Statement object to create a forward-only, read only ResultSet object −
try {
Statement stmt = conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally {
....
}
There are several methods in the ResultSet interface that involve moving the cursor, including −
Moves the cursor just before the first row.
Moves the cursor just after the last row.
Moves the cursor to the first row.
Moves the cursor to the last row.
Moves the cursor to the specified row.
Moves the cursor the given number of rows forward or backward, from where it is currently
pointing.
Moves the cursor to the previous row. This method returns false if the previous row is off the
result set.
Moves the cursor to the next row. This method returns false if there are no more rows in the
result set.
Returns the row number that the cursor is pointing to.
Moves the cursor to a special row in the result set that can be used to insert a new row
into the database. The current cursor location is remembered.
Moves the cursor back to the current row if the cursor is currently at the insert row;
otherwise, this method does nothing
For a better understanding, let us study Navigate - Example Code.
The ResultSet interface contains dozens of methods for getting the data of the current row.
There is a get method for each of the possible data types, and each get method has two versions −
One that takes in a column name.
One that takes in a column name.
One that takes in a column index.
One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the getInt() methods of ResultSet −
Returns the int in the current row in the column named columnName.
Returns the int in the current row in the specified column index. The column index
starts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on.
Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL.
There are also methods for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more information about using these SQL data types.
For a better understanding, let us study Viewing - Example Code.
The ResultSet interface contains a collection of update methods for updating the data of a result set.
As with the get methods, there are two update methods for each data type −
One that takes in a column name.
One that takes in a column name.
One that takes in a column index.
One that takes in a column index.
For example, to update a String column of the current row of a result set, you would use one of the following updateString() methods −
Changes the String in the specified column to the value of s.
Similar to the previous method, except that the column is
specified by its name instead of its index.
There are update methods for the eight primitive data types, as well as String, Object, URL, and the SQL data types in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet object, but not in the underlying database. To update your changes to the row in the database, you need to invoke one of the following methods.
Updates the current row by updating the corresponding row in the database.
Deletes the current row from the database
Refreshes the data in the result set to reflect any recent changes in the database.
Cancels any updates made on the current row.
Inserts a row into the database. This method can only be invoked when the cursor is pointing to the insert row.
For a better understanding, let us study the Updating - Example Code .
The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL INTEGER. Default mappings were created to provide consistency between drivers.
The following table summarizes the default JDBC data type that the Java data type is converted to, when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method.
JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable you to directly manipulate the respective data on the server.
The setXXX() and updateXXX() methods enable you to convert specific Java types to specific JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java type to a JDBC data type.
ResultSet object provides corresponding getXXX() method for each data type to retrieve column value. Each method can be used with column name or by its ordinal position.
The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and java.sql.Timestamp classes map to the SQL TIME and SQL TIMESTAMP data types, respectively.
Following example shows how the Date and Time classes format the standard Java date and time values to match the SQL data type requirements.
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.*;
public class SqlDateTime {
public static void main(String[] args) {
//Get standard date and time
java.util.Date javaDate = new java.util.Date();
long javaTime = javaDate.getTime();
System.out.println("The Java Date is:" +
javaDate.toString());
//Get and display SQL DATE
java.sql.Date sqlDate = new java.sql.Date(javaTime);
System.out.println("The SQL DATE is: " +
sqlDate.toString());
//Get and display SQL TIME
java.sql.Time sqlTime = new java.sql.Time(javaTime);
System.out.println("The SQL TIME is: " +
sqlTime.toString());
//Get and display SQL TIMESTAMP
java.sql.Timestamp sqlTimestamp =
new java.sql.Timestamp(javaTime);
System.out.println("The SQL TIMESTAMP is: " +
sqlTimestamp.toString());
}//end main
}//end SqlDateTime
Now let us compile the above example as follows −
C:\>javac SqlDateTime.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java SqlDateTime
The Java Date is:Tue Aug 18 13:46:02 GMT+04:00 2009
The SQL DATE is: 2009-08-18
The SQL TIME is: 13:46:02
The SQL TIMESTAMP is: 2009-08-18 13:46:02.828
C:\>
SQL's use of NULL values and Java's use of null are different concepts. So, to handle SQL NULL values in Java, there are three tactics you can use −
Avoid using getXXX( ) methods that return primitive data types.
Avoid using getXXX( ) methods that return primitive data types.
Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value
returned by the getXXX( ) method should be set to null.
Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value
returned by the getXXX( ) method should be set to null.
Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( )
method should be set to an acceptable value that you've chosen to represent a NULL.
Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( )
method should be set to an acceptable value that you've chosen to represent a NULL.
Here is one example to handle a NULL value −
Statement stmt = conn.createStatement( );
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
int id = rs.getInt(1);
if( rs.wasNull( ) ) {
id = 0;
}
If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion.
That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions −
To increase performance.
To increase performance.
To maintain the integrity of business processes.
To maintain the integrity of business processes.
To use distributed transactions.
To use distributed transactions.
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off auto-commit −
conn.setAutoCommit(false);
Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −
conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −
conn.rollback( );
The following example illustrates the use of a commit and rollback object −
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
For a better understanding, let us study the Commit - Example Code.
The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern DBMS, support savepoints within their environments such as Oracle's PL/SQL.
When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint.
The Connection object has two new methods that help you manage savepoints −
setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.
releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.
There is one rollback (String savepointName) method, which rolls back work to the specified savepoint.
The following example illustrates the use of a Savepoint object −
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
//set a Savepoint
Savepoint savepoint1 = conn.setSavepoint("Savepoint1");
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Tez')";
stmt.executeUpdate(SQL);
// If there is no error, commit the changes.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback(savepoint1);
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
For a better understanding, let us study the Savepoints - Example Code.
Exception handling allows you to handle exceptional conditions such as program-defined errors in a controlled fashion.
When an exception condition occurs, an exception is thrown. The term thrown means that current program execution stops, and the control is redirected to the nearest
applicable catch clause. If no applicable catch clause exists, then the program's execution ends.
JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most common exception you'll deal with is java.sql.SQLException.
An SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving additional information about the exception −
By utilizing the information available from the Exception object, you can catch an exception and continue your program appropriately. Here is the general form of a try block −
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
Study the following example code to understand the usage of try....catch...finally blocks.
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "{call getEmpName (?, ?)}";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
CallableStatement stmt = conn.prepareCall(QUERY);
) {
// Bind values into the parameters.
stmt.setInt(1, 1); // This would set ID
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
//Retrieve employee name with getXXX method
String empName = stmt.getString(2);
System.out.println("Emp Name with ID: 1 is " + empName);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now, let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result if there is no problem, otherwise the corresponding error would be caught and error message would be displayed −
C:\>java JDBCExample
Executing stored procedure...
Emp Name with ID: 1 is Zara
C:\>
Try the above example by passing wrong database name or wrong username or password and check the result.
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database.
When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.
JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.
Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.
Here is a typical sequence of steps to use Batch Processing with Statement Object −
Create a Statement object using either createStatement() methods.
Create a Statement object using either createStatement() methods.
Set auto-commit to false using setAutoCommit().
Set auto-commit to false using setAutoCommit().
Add as many as SQL statements you like into batch using addBatch() method on created statement object.
Add as many as SQL statements you like into batch using addBatch() method on created statement object.
Execute all the SQL statements using executeBatch() method on created statement object.
Execute all the SQL statements using executeBatch() method on created statement object.
Finally, commit all the changes using commit() method.
Finally, commit all the changes using commit() method.
The following code snippet provides an example of a batch update using Statement object −
// Create statement object
Statement stmt = conn.createStatement();
// Set auto-commit to false
conn.setAutoCommit(false);
// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(200,'Zia', 'Ali', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create one more SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Raj', 'Kumar', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create one more SQL statement
String SQL = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
For a better understanding, let us study the Batching - Example Code.
Here is a typical sequence of steps to use Batch Processing with PrepareStatement Object −
Create SQL statements with placeholders.
Create PrepareStatement object using either prepareStatement() methods.
Set auto-commit to false using setAutoCommit().
Add as many as SQL statements you like into batch using addBatch() method on created statement object.
Execute all the SQL statements using executeBatch() method on created statement object.
Finally, commit all the changes using commit() method.
Create SQL statements with placeholders.
Create SQL statements with placeholders.
Create PrepareStatement object using either prepareStatement() methods.
Create PrepareStatement object using either prepareStatement() methods.
Set auto-commit to false using setAutoCommit().
Set auto-commit to false using setAutoCommit().
Add as many as SQL statements you like into batch using addBatch() method on created statement object.
Add as many as SQL statements you like into batch using addBatch() method on created statement object.
Execute all the SQL statements using executeBatch() method on created statement object.
Execute all the SQL statements using executeBatch() method on created statement object.
Finally, commit all the changes using commit() method.
Finally, commit all the changes using commit() method.
The following code snippet provides an example of a batch update using PrepareStatement object −
// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(?, ?, ?, ?)";
// Create PrepareStatement object
PreparedStatemen pstmt = conn.prepareStatement(SQL);
//Set auto-commit to false
conn.setAutoCommit(false);
// Set the variables
pstmt.setInt( 1, 400 );
pstmt.setString( 2, "Pappu" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 33 );
// Add it to the batch
pstmt.addBatch();
// Set the variables
pstmt.setInt( 1, 401 );
pstmt.setString( 2, "Pawan" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 31 );
// Add it to the batch
pstmt.addBatch();
//add more batches
.
.
.
.
//Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
For a better understanding, let us study the Batching - Example Code.
We have learnt how to use Stored Procedures in JDBC while discussing the JDBC - Statements chapter. This chapter is similar to that section, but it would give you additional information about JDBC SQL escape syntax.
Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure.
Suppose, you need to execute the following Oracle stored procedure −
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
NOTE − Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database.
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Three types of parameters exist − IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three.
Here are the definitions of each −
The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
The String variable SQL represents the stored procedure, with parameter placeholders.
Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding.
When you use OUT and INOUT parameters, you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data type the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type.
Just as you close other Statement object, for the same reason you should also close the CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
cstmt.close();
}
studyWe have studied more details in the Callable - Example Code.
The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties.
The general SQL escape syntax format is as follows −
{keyword 'parameters'}
Here are the following escape sequences, which you would find very useful while performing the JDBC programming −
They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database's format. For Example −
{d 'yyyy-mm-dd'}
Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009.
Here is a simple example showing how to INSERT date in a table −
//Create a Statement object
stmt = conn.createStatement();
//Insert data ==> ID, First Name, Last Name, DOB
String sql="INSERT INTO STUDENTS VALUES" +
"(100,'Zara','Ali', {d '2001-12-16'})";
stmt.executeUpdate(sql);
Similarly, you can use one of the following two syntaxes, either t or ts −
{t 'hh:mm:ss'}
Where hh = hour; mm = minute; ss = second. Using this syntax {t '13:30:29'} is 1:30:29 PM.
{ts 'yyyy-mm-dd hh:mm:ss'}
This is combined syntax of the above two syntax for 'd' and 't' to represent timestamp.
This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters. For example −
String sql = "SELECT symbol FROM MathSymbols
WHERE symbol LIKE '\%' {escape '\'}";
stmt.execute(sql);
If you use the backslash character (\) as the escape character, you also have to use two backslash characters in your Java String literal, because the backslash is also a Java escape character.
This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to get the length of a string −
{fn length('Hello World')}
This returns 11, the length of the character string 'Hello World'.
This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN parameter, use the following syntax −
{call my_procedure(?)};
For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax −
{? = call my_procedure(?)};
This keyword is used to signify outer joins. The syntax is as follows −
{oj outer-join}
Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition. For example −
String sql = "SELECT Employees
FROM {oj ThisTable RIGHT
OUTER JOIN ThatTable on id = '100'}";
stmt.execute(sql);
A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can
hold large values, such as CLOB and BLOB data types.
There are following methods, which can be used to stream data −
setAsciiStream() − This method is used to supply large ASCII values.
setAsciiStream() − This method is used to supply large ASCII values.
setCharacterStream() − This method is used to supply large UNICODE values.
setCharacterStream() − This method is used to supply large UNICODE values.
setBinaryStream() − This method is used to supply large binary values.
setBinaryStream() − This method is used to supply large binary values.
The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream.
This example would create a database table XML_Data and then XML content would be written into this table.
Copy and paste the following example in FirstApplication.java, compile and run as follows −
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT Data FROM XML_Data WHERE id=100";
static final String INSERT_QUERY="INSERT INTO XML_Data VALUES (?,?)";
static final String CREATE_TABLE_QUERY = "CREATE TABLE XML_Data (id INTEGER, Data LONG)";
static final String DROP_TABLE_QUERY = "DROP TABLE XML_Data";
static final String XML_DATA = "<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>";
public static void createXMLTable(Statement stmt)
throws SQLException{
System.out.println("Creating XML_Data table..." );
//Drop table first if it exists.
try{
stmt.executeUpdate(DROP_TABLE_QUERY);
}catch(SQLException se){
}
stmt.executeUpdate(CREATE_TABLE_QUERY);
}
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY);
) {
createXMLTable(stmt);
ByteArrayInputStream bis = new ByteArrayInputStream(XML_DATA.getBytes());
pstmt.setInt(1,100);
pstmt.setAsciiStream(2,bis,XML_DATA.getBytes().length);
pstmt.execute();
//Close input stream
bis.close();
ResultSet rs = stmt.executeQuery(QUERY);
// Get the first row
if (rs.next ()){
//Retrieve data from input stream
InputStream xmlInputStream = rs.getAsciiStream (1);
int c;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while (( c = xmlInputStream.read ()) != -1)
bos.write(c);
//Print results
System.out.println(bos.toString());
}
// Clean-up environment
rs.close();
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac FirstApplication.java
C:\>
When you run FirstApplication, it produces the following result −
C:\>java FirstApplication
Creating XML_Data table...
<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>
C:\>
This tutorial provides an example on how to create a Database using JDBC application. Before executing the following example, make sure you have the following in place −
You should have admin privilege to create a database in the given schema. To execute the following example, you need to replace the username and password with your actual user name and password.
You should have admin privilege to create a database in the given schema. To execute the following example, you need to replace the username and password with your actual user name and password.
Your MySQL or whatever database is up and running.
Your MySQL or whatever database is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database server.
To create a new database, you need not give any database name while preparing database URL as mentioned in the below example.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database server.
To create a new database, you need not give any database name while preparing database URL as mentioned in the below example.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
Clean up the environment . try with resources automatically closes the resources.
Clean up the environment . try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database created successfully...
C:\>
This chapter provides an example on how to select a Database using JDBC application. Before executing the following example, make sure you have the following in place −
To execute the following example you need to replace the username and password with your actual user name and password.
To execute the following example you need to replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using, is up and running.
Your MySQL or whatever database you are using, is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database.
Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database.
Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
System.out.println("Connecting to a selected database...");
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) {
System.out.println("Connected database successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
C:\>
This chapter provides an example on how to drop an existing Database using JDBC application. Before executing the following example, make sure you have the following in place −
To execute the following example you need to replace the username and password with your actual user name and password.
To execute the following example you need to replace the username and password with your actual user name and password.
Your MySQL is up and running.
Your MySQL is up and running.
NOTE: This is a serious operation and you have to make a firm decision before proceeding to delete a database because everything you have in your database would be lost.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Deleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Deleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "DROP DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database dropped successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database dropped successfully...
C:\>
This chapter provides an example on how to create a table using JDBC application. Before executing the following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL is up and running.
Your MySQL is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to create a table in a seleted database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to create a table in a seleted database.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in TestApplication.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac TestApplication.java
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Created table in given database...
C:\>
This chapter provides an example on how to delete a table using JDBC application. Before executing the following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using, is up and running.
Your MySQL or whatever database you are using, is up and running.
NOTE Reformatting JDBC Tutorial This is a serious operation and you have to make a firm decision before proceeding to delete a table, because everything you have in your table would be lost.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a queryReformatting JDBC Tutorial Requires using an object of type Statement for building and submitting an SQL statement to drop a table in a seleted database.
Execute a queryReformatting JDBC Tutorial Requires using an object of type Statement for building and submitting an SQL statement to drop a table in a seleted database.
Clean up the environment Reformatting JDBC Tutorial try with resources automatically closes the resources.
Clean up the environment Reformatting JDBC Tutorial try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "DROP TABLE REGISTRATION";
stmt.executeUpdate(sql);
System.out.println("Table deleted in given database...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Table deleted in given database...
C:\>
This chapter provides an example on how to insert records in a table using JDBC application. Before executing following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using is up and running.
Your MySQL or whatever database you are using is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table.
Clean up the environment try with resources automatically closes the resources.
Clean up the environment try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
// Execute a query
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Inserting records into the table...
Inserted records into the table...
C:\>
This chapter provides an example on how to select/ fetch records from a table using JDBC application. Before executing the following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using is up and running.
Your MySQL or whatever database you are using is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to select (i.e. fetch ) records from a table.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to select (i.e. fetch ) records from a table.
Extract Data − Once SQL query is executed, you can fetch records from the table.
Extract Data − Once SQL query is executed, you can fetch records from the table.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);
) {
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
This chapter provides an example on how to update records in a table using JDBC application. Before executing the following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using is up and running.
Your MySQL or whatever database you are using is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 101, Age: 30, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
This chapter provides an example on how to delete records from a table using JDBC application. Before executing following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using is up and running.
Your MySQL or whatever database you are using is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of the WHERE clause to delete conditional records.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of the WHERE clause to delete conditional records.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "DELETE FROM Registration " +
"WHERE id = 101";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
This chapter provides an example on how to select records from a table using JDBC application. This would add additional conditions using WHERE clause while selecting records from the table. Before executing the following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using, is up and running.
Your MySQL or whatever database you are using, is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table, which meet the given condition. This Query makes use of the WHERE clause to select records.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table, which meet the given condition. This Query makes use of the WHERE clause to select records.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in TestApplication.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();) {
System.out.println("Fetching records without condition...");
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
// Select all records having ID equal or greater than 101
System.out.println("Fetching records with condition...");
String sql = "SELECT id, first, last, age FROM Registration" +
" WHERE id >= 101 ";
rs = stmt.executeQuery(sql);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac TestApplication.java
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Fetching records without condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Fetching records with condition...
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
This chapter provides an example on how to select records from a table using JDBC application. This would add additional conditions using LIKE clause while selecting records from the table. Before executing the following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using, is up and running.
Your MySQL or whatever database you are using, is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table which meet given condition. This Query makes use of LIKE clause to select records to select all the students whose first name starts with "za".
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table which meet given condition. This Query makes use of LIKE clause to select records to select all the students whose first name starts with "za".
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();) {
System.out.println("Fetching records without condition...");
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
// Select all records having ID equal or greater than 101
System.out.println("Fetching records with condition...");
String sql = "SELECT id, first, last, age FROM Registration" +
" WHERE first LIKE '%za%'";
rs = stmt.executeQuery(sql);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Fetching records without condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Fetching records with condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
C:\>
This chapter provides an example on how to sort records from a table using JDBC application. This would use asc and desc keywords to sort records in ascending or descending order. Before executing the following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL or whatever database you are using, is up and running.
Your MySQL or whatever database you are using, is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to sort records from a table. These Queries make use of asc and desc clauses to sort data in ascending and descening orders.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to sort records from a table. These Queries make use of asc and desc clauses to sort data in ascending and descening orders.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();) {
System.out.println("Fetching records in ascending order...");
ResultSet rs = stmt.executeQuery(QUERY + " ORDER BY first ASC");
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
System.out.println("Fetching records in descending order...");
rs = stmt.executeQuery(QUERY + " ORDER BY first DESC");
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Fetching records in ascending order...
ID: 103, Age: 28, First: Sumit, Last: Mittal
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 100, Age: 30, First: Zara, Last: Ali
Fetching records in descending order...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
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": 2342,
"s": 2162,
"text": "JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases."
},
{
"code": null,
"e": 2461,
"s": 2342,
"text": "The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage."
},
{
"code": null,
"e": 2496,
"s": 2461,
"text": "Making a connection to a database."
},
{
"code": null,
"e": 2531,
"s": 2496,
"text": "Making a connection to a database."
},
{
"code": null,
"e": 2565,
"s": 2531,
"text": "Creating SQL or MySQL statements."
},
{
"code": null,
"e": 2599,
"s": 2565,
"text": "Creating SQL or MySQL statements."
},
{
"code": null,
"e": 2647,
"s": 2599,
"text": "Executing SQL or MySQL queries in the database."
},
{
"code": null,
"e": 2695,
"s": 2647,
"text": "Executing SQL or MySQL queries in the database."
},
{
"code": null,
"e": 2738,
"s": 2695,
"text": "Viewing & Modifying the resulting records."
},
{
"code": null,
"e": 2781,
"s": 2738,
"text": "Viewing & Modifying the resulting records."
},
{
"code": null,
"e": 2990,
"s": 2781,
"text": "Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as −"
},
{
"code": null,
"e": 3008,
"s": 2990,
"text": "Java Applications"
},
{
"code": null,
"e": 3026,
"s": 3008,
"text": "Java Applications"
},
{
"code": null,
"e": 3039,
"s": 3026,
"text": "Java Applets"
},
{
"code": null,
"e": 3052,
"s": 3039,
"text": "Java Applets"
},
{
"code": null,
"e": 3066,
"s": 3052,
"text": "Java Servlets"
},
{
"code": null,
"e": 3080,
"s": 3066,
"text": "Java Servlets"
},
{
"code": null,
"e": 3104,
"s": 3080,
"text": "Java ServerPages (JSPs)"
},
{
"code": null,
"e": 3128,
"s": 3104,
"text": "Java ServerPages (JSPs)"
},
{
"code": null,
"e": 3157,
"s": 3128,
"text": "Enterprise JavaBeans (EJBs)."
},
{
"code": null,
"e": 3186,
"s": 3157,
"text": "Enterprise JavaBeans (EJBs)."
},
{
"code": null,
"e": 3312,
"s": 3186,
"text": "All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data."
},
{
"code": null,
"e": 3418,
"s": 3312,
"text": "JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code."
},
{
"code": null,
"e": 3511,
"s": 3418,
"text": "Before moving further, you need to have a good understanding of the following two subjects −"
},
{
"code": null,
"e": 3533,
"s": 3511,
"text": "Core JAVA Programming"
},
{
"code": null,
"e": 3555,
"s": 3533,
"text": "Core JAVA Programming"
},
{
"code": null,
"e": 3577,
"s": 3555,
"text": "SQL or MySQL Database"
},
{
"code": null,
"e": 3599,
"s": 3577,
"text": "SQL or MySQL Database"
},
{
"code": null,
"e": 3747,
"s": 3599,
"text": "The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers −"
},
{
"code": null,
"e": 3816,
"s": 3747,
"text": "JDBC API − This provides the application-to-JDBC Manager connection."
},
{
"code": null,
"e": 3885,
"s": 3816,
"text": "JDBC API − This provides the application-to-JDBC Manager connection."
},
{
"code": null,
"e": 3956,
"s": 3885,
"text": "JDBC Driver API − This supports the JDBC Manager-to-Driver Connection."
},
{
"code": null,
"e": 4027,
"s": 3956,
"text": "JDBC Driver API − This supports the JDBC Manager-to-Driver Connection."
},
{
"code": null,
"e": 4156,
"s": 4027,
"text": "The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases."
},
{
"code": null,
"e": 4367,
"s": 4156,
"text": "The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases."
},
{
"code": null,
"e": 4514,
"s": 4367,
"text": "Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application −"
},
{
"code": null,
"e": 4575,
"s": 4514,
"text": "The JDBC API provides the following interfaces and classes −"
},
{
"code": null,
"e": 4873,
"s": 4575,
"text": "DriverManager − This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection."
},
{
"code": null,
"e": 5171,
"s": 4873,
"text": "DriverManager − This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection."
},
{
"code": null,
"e": 5459,
"s": 5171,
"text": "Driver − This interface handles the communications with the database server. You will interact directly with Driver\nobjects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects."
},
{
"code": null,
"e": 5747,
"s": 5459,
"text": "Driver − This interface handles the communications with the database server. You will interact directly with Driver\nobjects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects."
},
{
"code": null,
"e": 5948,
"s": 5747,
"text": "Connection − This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only."
},
{
"code": null,
"e": 6149,
"s": 5948,
"text": "Connection − This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only."
},
{
"code": null,
"e": 6337,
"s": 6149,
"text": "Statement − You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures."
},
{
"code": null,
"e": 6525,
"s": 6337,
"text": "Statement − You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures."
},
{
"code": null,
"e": 6705,
"s": 6525,
"text": "ResultSet − These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data."
},
{
"code": null,
"e": 6885,
"s": 6705,
"text": "ResultSet − These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data."
},
{
"code": null,
"e": 6968,
"s": 6885,
"text": "SQLException − This class handles any errors that occur in a database application."
},
{
"code": null,
"e": 7051,
"s": 6968,
"text": "SQLException − This class handles any errors that occur in a database application."
},
{
"code": null,
"e": 7254,
"s": 7051,
"text": "The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at the time of writing this tutorial. It offers the main classes for interacting with your data sources."
},
{
"code": null,
"e": 7330,
"s": 7254,
"text": "The new features in these packages include changes in the following areas −"
},
{
"code": null,
"e": 7365,
"s": 7330,
"text": "Automatic database driver loading."
},
{
"code": null,
"e": 7400,
"s": 7365,
"text": "Automatic database driver loading."
},
{
"code": null,
"e": 7433,
"s": 7400,
"text": "Exception handling improvements."
},
{
"code": null,
"e": 7466,
"s": 7433,
"text": "Exception handling improvements."
},
{
"code": null,
"e": 7500,
"s": 7466,
"text": "Enhanced BLOB/CLOB functionality."
},
{
"code": null,
"e": 7534,
"s": 7500,
"text": "Enhanced BLOB/CLOB functionality."
},
{
"code": null,
"e": 7583,
"s": 7534,
"text": "Connection and statement interface enhancements."
},
{
"code": null,
"e": 7632,
"s": 7583,
"text": "Connection and statement interface enhancements."
},
{
"code": null,
"e": 7664,
"s": 7632,
"text": "National character set support."
},
{
"code": null,
"e": 7696,
"s": 7664,
"text": "National character set support."
},
{
"code": null,
"e": 7714,
"s": 7696,
"text": "SQL ROWID access."
},
{
"code": null,
"e": 7732,
"s": 7714,
"text": "SQL ROWID access."
},
{
"code": null,
"e": 7764,
"s": 7732,
"text": "SQL 2003 XML data type support."
},
{
"code": null,
"e": 7796,
"s": 7764,
"text": "SQL 2003 XML data type support."
},
{
"code": null,
"e": 7809,
"s": 7796,
"text": "Annotations."
},
{
"code": null,
"e": 7822,
"s": 7809,
"text": "Annotations."
},
{
"code": null,
"e": 8017,
"s": 7822,
"text": "Structured Query Language (SQL) is a standardized language that allows you to perform operations on a database, such as creating entries, reading content, updating content, and deleting entries."
},
{
"code": null,
"e": 8161,
"s": 8017,
"text": "SQL is supported by almost any database you will likely use, and it allows you to write database code independently of the underlying database."
},
{
"code": null,
"e": 8409,
"s": 8161,
"text": "This chapter gives an overview of SQL, which is a prerequisite to understand JDBC concepts. After going through this chapter, you will be able to Create, Create, Read, Update, and Delete (often referred to as CRUD operations) data from a database."
},
{
"code": null,
"e": 8479,
"s": 8409,
"text": "For a detailed understanding on SQL, you can read our MySQL Tutorial."
},
{
"code": null,
"e": 8562,
"s": 8479,
"text": "The CREATE DATABASE statement is used for creating a new database. The syntax is −"
},
{
"code": null,
"e": 8599,
"s": 8562,
"text": "SQL> CREATE DATABASE DATABASE_NAME;\n"
},
{
"code": null,
"e": 8658,
"s": 8599,
"text": "The following SQL statement creates a Database named EMP −"
},
{
"code": null,
"e": 8684,
"s": 8658,
"text": "SQL> CREATE DATABASE EMP;"
},
{
"code": null,
"e": 8771,
"s": 8684,
"text": "The DROP DATABASE statement is used for deleting an existing database. The syntax is −"
},
{
"code": null,
"e": 8806,
"s": 8771,
"text": "SQL> DROP DATABASE DATABASE_NAME;\n"
},
{
"code": null,
"e": 8987,
"s": 8806,
"text": "Note − To create or drop a database you should have administrator privilege on your database server. Be careful, deleting a database would loss all the data stored in the database."
},
{
"code": null,
"e": 9064,
"s": 8987,
"text": "The CREATE TABLE statement is used for creating a new table. The syntax is −"
},
{
"code": null,
"e": 9204,
"s": 9064,
"text": "SQL> CREATE TABLE table_name\n(\n column_name column_data_type,\n column_name column_data_type,\n column_name column_data_type\n ...\n);\n"
},
{
"code": null,
"e": 9284,
"s": 9204,
"text": "The following SQL statement creates a table named Employees with four columns −"
},
{
"code": null,
"e": 9425,
"s": 9284,
"text": "SQL> CREATE TABLE Employees\n(\n id INT NOT NULL,\n age INT NOT NULL,\n first VARCHAR(255),\n last VARCHAR(255),\n PRIMARY KEY ( id )\n);"
},
{
"code": null,
"e": 9506,
"s": 9425,
"text": "The DROP TABLE statement is used for deleting an existing table. The syntax is −"
},
{
"code": null,
"e": 9535,
"s": 9506,
"text": "SQL> DROP TABLE table_name;\n"
},
{
"code": null,
"e": 9597,
"s": 9535,
"text": "The following SQL statement deletes a table named Employees −"
},
{
"code": null,
"e": 9624,
"s": 9597,
"text": "SQL> DROP TABLE Employees;"
},
{
"code": null,
"e": 9775,
"s": 9624,
"text": "The syntax for INSERT, looks similar to the following, where column1, column2, and so on represents the new data to appear in the\nrespective columns −"
},
{
"code": null,
"e": 9836,
"s": 9775,
"text": "SQL> INSERT INTO table_name VALUES (column1, column2, ...);\n"
},
{
"code": null,
"e": 9933,
"s": 9836,
"text": "The following SQL INSERT statement inserts a new row in the Employees database created earlier −"
},
{
"code": null,
"e": 9993,
"s": 9933,
"text": "SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');"
},
{
"code": null,
"e": 10083,
"s": 9993,
"text": "The SELECT statement is used to retrieve data from a database. The syntax for SELECT is −"
},
{
"code": null,
"e": 10170,
"s": 10083,
"text": "SQL> SELECT column_name, column_name, ...\n FROM table_name\n WHERE conditions;\n"
},
{
"code": null,
"e": 10295,
"s": 10170,
"text": "The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators."
},
{
"code": null,
"e": 10414,
"s": 10295,
"text": "The following SQL statement selects the age, first and last columns from the Employees table, where id column is 100 −"
},
{
"code": null,
"e": 10486,
"s": 10414,
"text": "SQL> SELECT first, last, age \n FROM Employees \n WHERE id = 100;"
},
{
"code": null,
"e": 10614,
"s": 10486,
"text": "The following SQL statement selects the age, first and last columns from the Employees table where first column contains Zara −"
},
{
"code": null,
"e": 10697,
"s": 10614,
"text": "SQL> SELECT first, last, age \n FROM Employees \n WHERE first LIKE '%Zara%';"
},
{
"code": null,
"e": 10769,
"s": 10697,
"text": "The UPDATE statement is used to update data. The syntax for UPDATE is −"
},
{
"code": null,
"e": 10871,
"s": 10769,
"text": "SQL> UPDATE table_name\n SET column_name = value, column_name = value, ...\n WHERE conditions;\n"
},
{
"code": null,
"e": 10996,
"s": 10871,
"text": "The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators."
},
{
"code": null,
"e": 11088,
"s": 10996,
"text": "The following SQL UPDATE statement changes the age column of the employee whose id is 100 −"
},
{
"code": null,
"e": 11135,
"s": 11088,
"text": "SQL> UPDATE Employees SET age=20 WHERE id=100;"
},
{
"code": null,
"e": 11219,
"s": 11135,
"text": "The DELETE statement is used to delete data from tables. The syntax for DELETE is −"
},
{
"code": null,
"e": 11266,
"s": 11219,
"text": "SQL> DELETE FROM table_name WHERE conditions;\n"
},
{
"code": null,
"e": 11391,
"s": 11266,
"text": "The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators."
},
{
"code": null,
"e": 11479,
"s": 11391,
"text": "The following SQL DELETE statement deletes the record of the employee whose id is 100 −"
},
{
"code": null,
"e": 11520,
"s": 11479,
"text": "SQL> DELETE FROM Employees WHERE id=100;"
},
{
"code": null,
"e": 11680,
"s": 11520,
"text": "To start developing with JDBC, you should setup your JDBC environment by following the steps shown below. We assume that you are working on a Windows platform."
},
{
"code": null,
"e": 11813,
"s": 11680,
"text": "Java SE is available for download for free. To download click here, please download a version compatible with your operating system."
},
{
"code": null,
"e": 12041,
"s": 11813,
"text": "Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories."
},
{
"code": null,
"e": 12115,
"s": 12041,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 12169,
"s": 12115,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 12223,
"s": 12169,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 12293,
"s": 12223,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 12363,
"s": 12293,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 12558,
"s": 12363,
"text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way"
},
{
"code": null,
"e": 12753,
"s": 12558,
"text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way"
},
{
"code": null,
"e": 12804,
"s": 12753,
"text": "C:\\Windows\\System32;c:\\Program Files\\java\\jdk\\bin\n"
},
{
"code": null,
"e": 12878,
"s": 12804,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 12950,
"s": 12878,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −"
},
{
"code": null,
"e": 13022,
"s": 12950,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −"
},
{
"code": null,
"e": 13071,
"s": 13022,
"text": "SET PATH = %PATH%;C:\\Program Files\\java\\jdk\\bin\n"
},
{
"code": null,
"e": 13234,
"s": 13071,
"text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this."
},
{
"code": null,
"e": 13345,
"s": 13234,
"text": "For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −"
},
{
"code": null,
"e": 13380,
"s": 13345,
"text": "export PATH = /path/to/java:$PATH'"
},
{
"code": null,
"e": 13484,
"s": 13380,
"text": "You automatically get both JDBC packages java.sql and javax.sql, when you install J2SE Development Kit."
},
{
"code": null,
"e": 13608,
"s": 13484,
"text": "The most important thing you will need, of course is an actual running database with a table that you can query and modify."
},
{
"code": null,
"e": 13711,
"s": 13608,
"text": "Install a database that is most suitable for you. You can have plenty of choices and most common are −"
},
{
"code": null,
"e": 14431,
"s": 13711,
"text": "MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation.\nIn addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier.\nFinally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8.\nAccordingly, set CLASSPATH variable to C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8\\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation."
},
{
"code": null,
"e": 14578,
"s": 14431,
"text": "MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation."
},
{
"code": null,
"e": 14735,
"s": 14578,
"text": "In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier."
},
{
"code": null,
"e": 14969,
"s": 14735,
"text": "Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8."
},
{
"code": null,
"e": 15151,
"s": 14969,
"text": "Accordingly, set CLASSPATH variable to C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8\\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation."
},
{
"code": null,
"e": 15276,
"s": 15151,
"text": "When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice."
},
{
"code": null,
"e": 15418,
"s": 15276,
"text": "Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application."
},
{
"code": null,
"e": 15541,
"s": 15418,
"text": "There are various database operations like database creation and deletion, which would need administrator ID and password."
},
{
"code": null,
"e": 15643,
"s": 15541,
"text": "For rest of the JDBC tutorial, we would use MySQL Database with guest as ID and guest123 as password."
},
{
"code": null,
"e": 15798,
"s": 15643,
"text": "If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you."
},
{
"code": null,
"e": 15863,
"s": 15798,
"text": "To create the TUTORIALSPOINT database, use the following steps −"
},
{
"code": null,
"e": 15939,
"s": 15863,
"text": "Open a Command Prompt and change to the installation directory as follows −"
},
{
"code": null,
"e": 16003,
"s": 15939,
"text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>"
},
{
"code": null,
"e": 16181,
"s": 16003,
"text": "Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server."
},
{
"code": null,
"e": 16273,
"s": 16181,
"text": "Start the database server by executing the following command, if it is already not running."
},
{
"code": null,
"e": 16335,
"s": 16273,
"text": "C:\\Program Files\\MySQL\\bin>mysqld\nC:\\Program Files\\MySQL\\bin>"
},
{
"code": null,
"e": 16407,
"s": 16335,
"text": "Create the TUTORIALSPOINT database by executing the following command −"
},
{
"code": null,
"e": 16533,
"s": 16407,
"text": "C:\\Program Files\\MySQL\\bin> mysqladmin create TUTORIALSPOINT -u guest -p\nEnter password: ********\nC:\\Program Files\\MySQL\\bin>"
},
{
"code": null,
"e": 16617,
"s": 16533,
"text": "To create the Employees table in TUTORIALSPOINT database, use the following steps −"
},
{
"code": null,
"e": 16693,
"s": 16617,
"text": "Open a Command Prompt and change to the installation directory as follows −"
},
{
"code": null,
"e": 16757,
"s": 16693,
"text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>"
},
{
"code": null,
"e": 16792,
"s": 16757,
"text": "Login to the database as follows −"
},
{
"code": null,
"e": 16869,
"s": 16792,
"text": "C:\\Program Files\\MySQL\\bin>mysql -u guest -p\nEnter password: ********\nmysql>"
},
{
"code": null,
"e": 16909,
"s": 16869,
"text": "Create the table Employees as follows −"
},
{
"code": null,
"e": 17132,
"s": 16909,
"text": "mysql> use TUTORIALSPOINT;\nmysql> create table Employees\n -> (\n -> id int not null,\n -> age int not null,\n -> first varchar (255),\n -> last varchar (255)\n -> );\nQuery OK, 0 rows affected (0.08 sec)\nmysql>"
},
{
"code": null,
"e": 17194,
"s": 17132,
"text": "Finally you create few records in Employee table as follows −"
},
{
"code": null,
"e": 17606,
"s": 17194,
"text": "mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql>"
},
{
"code": null,
"e": 17680,
"s": 17606,
"text": "For a complete understanding on MySQL database, study the MySQL Tutorial."
},
{
"code": null,
"e": 17793,
"s": 17680,
"text": "Now you are ready to start experimenting with JDBC. Next chapter gives you a sample example on JDBC Programming."
},
{
"code": null,
"e": 17970,
"s": 17793,
"text": "This chapter provides an example of how to create a simple JDBC application. This will show you how to open a database connection, execute a SQL query, and display the results."
},
{
"code": null,
"e": 18080,
"s": 17970,
"text": "All the steps mentioned in this template example, would be explained in subsequent chapters of this tutorial."
},
{
"code": null,
"e": 18152,
"s": 18080,
"text": "There are following six steps involved in building a JDBC application −"
},
{
"code": null,
"e": 18324,
"s": 18152,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 18496,
"s": 18324,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 18661,
"s": 18496,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database."
},
{
"code": null,
"e": 18826,
"s": 18661,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database."
},
{
"code": null,
"e": 18949,
"s": 18826,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 19072,
"s": 18949,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 19209,
"s": 19072,
"text": "Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to\nretrieve the data from the result set."
},
{
"code": null,
"e": 19346,
"s": 19209,
"text": "Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to\nretrieve the data from the result set."
},
{
"code": null,
"e": 19473,
"s": 19346,
"text": "Clean up the environment − Requires explicitly closing all database resources versus relying on the JVM's garbage collection.\n"
},
{
"code": null,
"e": 19599,
"s": 19473,
"text": "Clean up the environment − Requires explicitly closing all database resources versus relying on the JVM's garbage collection."
},
{
"code": null,
"e": 19708,
"s": 19599,
"text": "This sample example can serve as a template when you need to create your own JDBC application in the future."
},
{
"code": null,
"e": 19816,
"s": 19708,
"text": "This sample code has been written based on the environment and database setup done in the previous chapter."
},
{
"code": null,
"e": 19904,
"s": 19816,
"text": "Copy and paste the following example in FirstExample.java, compile and run as follows −"
},
{
"code": null,
"e": 20884,
"s": 19904,
"text": "import java.sql.*;\n\npublic class FirstExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Employees\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(QUERY);) {\n // Extract data from result set\n while (rs.next()) {\n // Retrieve by column name\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 20934,
"s": 20884,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 20967,
"s": 20934,
"text": "C:\\>javac FirstExample.java\nC:\\>"
},
{
"code": null,
"e": 21029,
"s": 20967,
"text": "When you run FirstExample, it produces the following result −"
},
{
"code": null,
"e": 21278,
"s": 21029,
"text": "C:\\>java FirstExample\nConnecting to database...\nCreating statement...\nID: 100, Age: 18, First: Zara, Last: Ali\nID: 101, Age: 25, First: Mahnaz, Last: Fatma\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 21384,
"s": 21278,
"text": "JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server."
},
{
"code": null,
"e": 21550,
"s": 21384,
"text": "For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java."
},
{
"code": null,
"e": 21799,
"s": 21550,
"text": "The Java.sql package that ships with JDK, contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driver interface in their database driver."
},
{
"code": null,
"e": 22040,
"s": 21799,
"text": "JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is explained below −"
},
{
"code": null,
"e": 22249,
"s": 22040,
"text": "In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target database."
},
{
"code": null,
"e": 22462,
"s": 22249,
"text": "When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available."
},
{
"code": null,
"e": 22549,
"s": 22462,
"text": "The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver."
},
{
"code": null,
"e": 22844,
"s": 22549,
"text": "In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine."
},
{
"code": null,
"e": 23073,
"s": 22844,
"text": "If we change the Database, we have to change the native API, as it is specific to a database and they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead. "
},
{
"code": null,
"e": 23146,
"s": 23073,
"text": "The Oracle Call Interface (OCI) driver is an example of a Type 2 driver."
},
{
"code": null,
"e": 23476,
"s": 23146,
"text": "In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server."
},
{
"code": null,
"e": 23640,
"s": 23476,
"text": "This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases."
},
{
"code": null,
"e": 23880,
"s": 23640,
"text": "You can think of the application server as a JDBC \"proxy,\" meaning that it makes calls for the client application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type."
},
{
"code": null,
"e": 24019,
"s": 23880,
"text": "Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the nuances will prove helpful."
},
{
"code": null,
"e": 24252,
"s": 24019,
"text": "In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database through socket connection. This is the highest performance driver\navailable for the database and is usually provided by the vendor itself."
},
{
"code": null,
"e": 24417,
"s": 24252,
"text": "This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically."
},
{
"code": null,
"e": 24574,
"s": 24417,
"text": "MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers."
},
{
"code": null,
"e": 24681,
"s": 24574,
"text": "If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4."
},
{
"code": null,
"e": 24797,
"s": 24681,
"text": "If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver."
},
{
"code": null,
"e": 24910,
"s": 24797,
"text": "Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database."
},
{
"code": null,
"e": 25038,
"s": 24910,
"text": "The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only."
},
{
"code": null,
"e": 25143,
"s": 25038,
"text": "After you've installed the appropriate driver, it is time to establish a database connection using JDBC."
},
{
"code": null,
"e": 25252,
"s": 25143,
"text": "The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps −"
},
{
"code": null,
"e": 25364,
"s": 25252,
"text": "Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code."
},
{
"code": null,
"e": 25476,
"s": 25364,
"text": "Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code."
},
{
"code": null,
"e": 25616,
"s": 25476,
"text": "Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests."
},
{
"code": null,
"e": 25756,
"s": 25616,
"text": "Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests."
},
{
"code": null,
"e": 25888,
"s": 25756,
"text": "Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect."
},
{
"code": null,
"e": 26020,
"s": 25888,
"text": "Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to connect."
},
{
"code": null,
"e": 26163,
"s": 26020,
"text": "Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection."
},
{
"code": null,
"e": 26306,
"s": 26163,
"text": "Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection."
},
{
"code": null,
"e": 26462,
"s": 26306,
"text": "The Import statements tell the Java compiler where to find the classes you reference in your code and are placed at the very beginning of your source code."
},
{
"code": null,
"e": 26619,
"s": 26462,
"text": "To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL tables, add the following imports to your source code −"
},
{
"code": null,
"e": 26732,
"s": 26619,
"text": "import java.sql.* ; // for standard JDBC programs\nimport java.math.* ; // for BigDecimal and BigInteger support"
},
{
"code": null,
"e": 26968,
"s": 26732,
"text": "You must register the driver in your program before you use it. Registering the driver is the process by which the Oracle driver's class file is loaded into the memory,\nso it can be utilized as an implementation of the JDBC interfaces."
},
{
"code": null,
"e": 27074,
"s": 26968,
"text": "You need to do this registration only once in your program. You can register a driver in one of two ways."
},
{
"code": null,
"e": 27359,
"s": 27074,
"text": "The most common approach to register a driver is to use Java's Class.forName() method, to dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable."
},
{
"code": null,
"e": 27435,
"s": 27359,
"text": "The following example uses Class.forName( ) to register the Oracle driver −"
},
{
"code": null,
"e": 27614,
"s": 27435,
"text": "try {\n Class.forName(\"oracle.jdbc.driver.OracleDriver\");\n}\ncatch(ClassNotFoundException ex) {\n System.out.println(\"Error: unable to load driver class!\");\n System.exit(1);\n}"
},
{
"code": null,
"e": 27748,
"s": 27614,
"text": "You can use getInstance() method to work around noncompliant JVMs, but then you'll have to code for two extra Exceptions as follows −"
},
{
"code": null,
"e": 28175,
"s": 27748,
"text": "try {\n Class.forName(\"oracle.jdbc.driver.OracleDriver\").newInstance();\n}\ncatch(ClassNotFoundException ex) {\n System.out.println(\"Error: unable to load driver class!\");\n System.exit(1);\ncatch(IllegalAccessException ex) {\n System.out.println(\"Error: access problem while loading!\");\n System.exit(2);\ncatch(InstantiationException ex) {\n System.out.println(\"Error: unable to instantiate driver!\");\n System.exit(3);\n}"
},
{
"code": null,
"e": 28289,
"s": 28175,
"text": "The second approach you can use to register a driver, is to use the static DriverManager.registerDriver() method."
},
{
"code": null,
"e": 28413,
"s": 28289,
"text": "You should use the registerDriver() method if you are using a non-JDK compliant JVM, such as the one provided by Microsoft."
},
{
"code": null,
"e": 28489,
"s": 28413,
"text": "The following example uses registerDriver() to register the Oracle driver −"
},
{
"code": null,
"e": 28720,
"s": 28489,
"text": "try {\n Driver myDriver = new oracle.jdbc.driver.OracleDriver();\n DriverManager.registerDriver( myDriver );\n}\ncatch(ClassNotFoundException ex) {\n System.out.println(\"Error: unable to load driver class!\");\n System.exit(1);\n}"
},
{
"code": null,
"e": 28924,
"s": 28720,
"text": "After you've loaded the driver, you can establish a connection using the DriverManager.getConnection() method. For easy reference, let me list the three\noverloaded DriverManager.getConnection() methods −"
},
{
"code": null,
"e": 28950,
"s": 28924,
"text": "getConnection(String url)"
},
{
"code": null,
"e": 28976,
"s": 28950,
"text": "getConnection(String url)"
},
{
"code": null,
"e": 29019,
"s": 28976,
"text": "getConnection(String url, Properties prop)"
},
{
"code": null,
"e": 29062,
"s": 29019,
"text": "getConnection(String url, Properties prop)"
},
{
"code": null,
"e": 29118,
"s": 29062,
"text": "getConnection(String url, String user, String password)"
},
{
"code": null,
"e": 29174,
"s": 29118,
"text": "getConnection(String url, String user, String password)"
},
{
"code": null,
"e": 29273,
"s": 29174,
"text": "Here each form requires a database URL. A database URL is an address that points to your database."
},
{
"code": null,
"e": 29380,
"s": 29273,
"text": "Formulating a database URL is where most of the problems associated with establishing a connection occurs."
},
{
"code": null,
"e": 29455,
"s": 29380,
"text": "Following table lists down the popular JDBC driver names and database URL."
},
{
"code": null,
"e": 29579,
"s": 29455,
"text": "All the highlighted part in URL format is static and you need to change only the remaining part as per your database setup."
},
{
"code": null,
"e": 29682,
"s": 29579,
"text": "We have listed down three forms of DriverManager.getConnection() method to create a connection object."
},
{
"code": null,
"e": 29795,
"s": 29682,
"text": "The most commonly used form of getConnection() requires you to pass a database URL, a username, and a password −"
},
{
"code": null,
"e": 29923,
"s": 29795,
"text": "Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for the database portion of the URL."
},
{
"code": null,
"e": 30130,
"s": 29923,
"text": "If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle listener is configured to listen on port 1521, and your database name is EMP, then complete database URL would be −"
},
{
"code": null,
"e": 30164,
"s": 30130,
"text": "jdbc:oracle:thin:@amrood:1521:EMP"
},
{
"code": null,
"e": 30287,
"s": 30164,
"text": "Now you have to call getConnection() method with appropriate username and password to get a Connection object as follows −"
},
{
"code": null,
"e": 30452,
"s": 30287,
"text": "String URL = \"jdbc:oracle:thin:@amrood:1521:EMP\";\nString USER = \"username\";\nString PASS = \"password\"\nConnection conn = DriverManager.getConnection(URL, USER, PASS);"
},
{
"code": null,
"e": 30542,
"s": 30452,
"text": "A second form of the DriverManager.getConnection( ) method requires only a database URL −"
},
{
"code": null,
"e": 30584,
"s": 30542,
"text": "DriverManager.getConnection(String url);\n"
},
{
"code": null,
"e": 30696,
"s": 30584,
"text": "However, in this case, the database URL includes the username and password and has the following general form −"
},
{
"code": null,
"e": 30742,
"s": 30696,
"text": "jdbc:oracle:driver:username/password@database"
},
{
"code": null,
"e": 30795,
"s": 30742,
"text": "So, the above connection can be created as follows −"
},
{
"code": null,
"e": 30914,
"s": 30795,
"text": "String URL = \"jdbc:oracle:thin:username/password@amrood:1521:EMP\";\nConnection conn = DriverManager.getConnection(URL);"
},
{
"code": null,
"e": 31022,
"s": 30914,
"text": "A third form of the DriverManager.getConnection( ) method requires a database URL and a Properties object −"
},
{
"code": null,
"e": 31080,
"s": 31022,
"text": "DriverManager.getConnection(String url, Properties info);"
},
{
"code": null,
"e": 31232,
"s": 31080,
"text": "A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to the driver during a call to the getConnection() method."
},
{
"code": null,
"e": 31316,
"s": 31232,
"text": "To make the same connection made by the previous examples, use the following code −"
},
{
"code": null,
"e": 31551,
"s": 31316,
"text": "import java.util.*;\n\nString URL = \"jdbc:oracle:thin:@amrood:1521:EMP\";\nProperties info = new Properties( );\ninfo.put( \"user\", \"username\" );\ninfo.put( \"password\", \"password\" );\n\nConnection conn = DriverManager.getConnection(URL, info);"
},
{
"code": null,
"e": 31793,
"s": 31551,
"text": "At the end of your JDBC program, it is required explicitly to close all the connections to the database to end each database session. However, if\nyou forget, Java's garbage collector will close the connection when it cleans up stale objects."
},
{
"code": null,
"e": 32017,
"s": 31793,
"text": "Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object."
},
{
"code": null,
"e": 32181,
"s": 32017,
"text": "To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless of an exception occurs or not."
},
{
"code": null,
"e": 32263,
"s": 32181,
"text": "To close the above opened connection, you should call close() method as follows −"
},
{
"code": null,
"e": 32278,
"s": 32263,
"text": "conn.close();\n"
},
{
"code": null,
"e": 32387,
"s": 32278,
"text": "Explicitly closing a connection conserves DBMS resources, which will make your database administrator happy."
},
{
"code": null,
"e": 32472,
"s": 32387,
"text": "For a better understanding, we suggest you to study our JDBC - Sample Code tutorial."
},
{
"code": null,
"e": 32727,
"s": 32472,
"text": "Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database."
},
{
"code": null,
"e": 32843,
"s": 32727,
"text": "They also define methods that help bridge data type differences between Java and SQL data types used in a database."
},
{
"code": null,
"e": 32945,
"s": 32843,
"text": "The following table provides a summary of each interface's purpose to decide on the interface to use."
},
{
"code": null,
"e": 33121,
"s": 32945,
"text": "Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement( ) method, as in the following example −"
},
{
"code": null,
"e": 33253,
"s": 33121,
"text": "Statement stmt = null;\ntry {\n stmt = conn.createStatement( );\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}"
},
{
"code": null,
"e": 33380,
"s": 33253,
"text": "Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three execute methods."
},
{
"code": null,
"e": 33600,
"s": 33380,
"text": "boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL."
},
{
"code": null,
"e": 33820,
"s": 33600,
"text": "boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL."
},
{
"code": null,
"e": 34079,
"s": 33820,
"text": "int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement."
},
{
"code": null,
"e": 34338,
"s": 34079,
"text": "int executeUpdate (String SQL) − Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement."
},
{
"code": null,
"e": 34495,
"s": 34338,
"text": "ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement."
},
{
"code": null,
"e": 34652,
"s": 34495,
"text": "ResultSet executeQuery (String SQL) − Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement."
},
{
"code": null,
"e": 34783,
"s": 34652,
"text": "Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object."
},
{
"code": null,
"e": 35013,
"s": 34783,
"text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the Statement object as well. However, you should always explicitly close the Statement object to ensure proper cleanup."
},
{
"code": null,
"e": 35153,
"s": 35013,
"text": "Statement stmt = null;\ntry {\n stmt = conn.createStatement( );\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n stmt.close();\n}"
},
{
"code": null,
"e": 35239,
"s": 35153,
"text": "For a better understanding, we suggest you to study the Statement - Example tutorial."
},
{
"code": null,
"e": 35401,
"s": 35239,
"text": "The PreparedStatement interface extends the Statement interface, which gives you added functionality with a couple of advantages over a generic Statement object."
},
{
"code": null,
"e": 35478,
"s": 35401,
"text": "This statement gives you the flexibility of supplying arguments dynamically."
},
{
"code": null,
"e": 35684,
"s": 35478,
"text": "PreparedStatement pstmt = null;\ntry {\n String SQL = \"Update Employees SET age = ? WHERE id = ?\";\n pstmt = conn.prepareStatement(SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}"
},
{
"code": null,
"e": 35859,
"s": 35684,
"text": "All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must supply values for every parameter before executing the SQL statement."
},
{
"code": null,
"e": 36075,
"s": 35859,
"text": "The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException."
},
{
"code": null,
"e": 36281,
"s": 36075,
"text": "Each parameter marker is referred by its ordinal position. The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java array indices, which starts at 0."
},
{
"code": null,
"e": 36544,
"s": 36281,
"text": "All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use SQL statements that can input the parameters."
},
{
"code": null,
"e": 36654,
"s": 36544,
"text": "Just as you close a Statement object, for the same reason you should also close the PreparedStatement object."
},
{
"code": null,
"e": 36900,
"s": 36654,
"text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup."
},
{
"code": null,
"e": 37115,
"s": 36900,
"text": "PreparedStatement pstmt = null;\ntry {\n String SQL = \"Update Employees SET age = ? WHERE id = ?\";\n pstmt = conn.prepareStatement(SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n pstmt.close();\n}"
},
{
"code": null,
"e": 37180,
"s": 37115,
"text": "For a better understanding, let us study Prepare - Example Code."
},
{
"code": null,
"e": 37377,
"s": 37180,
"text": "Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure."
},
{
"code": null,
"e": 37446,
"s": 37377,
"text": "Suppose, you need to execute the following Oracle stored procedure −"
},
{
"code": null,
"e": 37616,
"s": 37446,
"text": "CREATE OR REPLACE PROCEDURE getEmpName \n (EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND;"
},
{
"code": null,
"e": 37805,
"s": 37616,
"text": "NOTE − Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database −"
},
{
"code": null,
"e": 38047,
"s": 37805,
"text": "DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$\nCREATE PROCEDURE `EMP`.`getEmpName` \n (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND $$\n\nDELIMITER ;"
},
{
"code": null,
"e": 38209,
"s": 38047,
"text": "Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three."
},
{
"code": null,
"e": 38244,
"s": 38209,
"text": "Here are the definitions of each −"
},
{
"code": null,
"e": 38411,
"s": 38244,
"text": "The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure −"
},
{
"code": null,
"e": 38596,
"s": 38411,
"text": "CallableStatement cstmt = null;\ntry {\n String SQL = \"{call getEmpName (?, ?)}\";\n cstmt = conn.prepareCall (SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}"
},
{
"code": null,
"e": 38683,
"s": 38596,
"text": "The String variable SQL, represents the stored procedure, with parameter placeholders."
},
{
"code": null,
"e": 38881,
"s": 38683,
"text": "Using the CallableStatement objects is much like using the PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException."
},
{
"code": null,
"e": 39072,
"s": 38881,
"text": "If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding."
},
{
"code": null,
"e": 39316,
"s": 39072,
"text": "When you use OUT and INOUT parameters you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type, to the data type that the stored procedure is expected to return."
},
{
"code": null,
"e": 39508,
"s": 39316,
"text": "Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type."
},
{
"code": null,
"e": 39622,
"s": 39508,
"text": "Just as you close other Statement object, for the same reason you should also close the CallableStatement object."
},
{
"code": null,
"e": 39868,
"s": 39622,
"text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup."
},
{
"code": null,
"e": 40062,
"s": 39868,
"text": "CallableStatement cstmt = null;\ntry {\n String SQL = \"{call getEmpName (?, ?)}\";\n cstmt = conn.prepareCall (SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n cstmt.close();\n}"
},
{
"code": null,
"e": 40140,
"s": 40062,
"text": "For a better understanding, I would suggest to study Callable - Example Code."
},
{
"code": null,
"e": 40413,
"s": 40140,
"text": "The SQL statements that read data from a database query, return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The java.sql.ResultSet interface represents the result set of a database query."
},
{
"code": null,
"e": 40591,
"s": 40413,
"text": "A ResultSet object maintains a cursor that points to the current row in the result set. The term \"result set\" refers to the row and column data contained in a ResultSet object."
},
{
"code": null,
"e": 40673,
"s": 40591,
"text": "The methods of the ResultSet interface can be broken down into three categories −"
},
{
"code": null,
"e": 40728,
"s": 40673,
"text": "Navigational methods − Used to move the cursor around."
},
{
"code": null,
"e": 40783,
"s": 40728,
"text": "Navigational methods − Used to move the cursor around."
},
{
"code": null,
"e": 40882,
"s": 40783,
"text": "Get methods − Used to view the data in the columns of the current row being pointed by the cursor."
},
{
"code": null,
"e": 40981,
"s": 40882,
"text": "Get methods − Used to view the data in the columns of the current row being pointed by the cursor."
},
{
"code": null,
"e": 41125,
"s": 40981,
"text": "Update methods − Used to update the data in the columns of the current row. The updates can then be updated in the underlying database as well."
},
{
"code": null,
"e": 41269,
"s": 41125,
"text": "Update methods − Used to update the data in the columns of the current row. The updates can then be updated in the underlying database as well."
},
{
"code": null,
"e": 41439,
"s": 41269,
"text": "The cursor is movable based on the properties of the ResultSet. These properties are designated when the corresponding Statement that generates the ResultSet is created."
},
{
"code": null,
"e": 41532,
"s": 41439,
"text": "JDBC provides the following connection methods to create statements with desired ResultSet −"
},
{
"code": null,
"e": 41580,
"s": 41532,
"text": "createStatement(int RSType, int RSConcurrency);"
},
{
"code": null,
"e": 41628,
"s": 41580,
"text": "createStatement(int RSType, int RSConcurrency);"
},
{
"code": null,
"e": 41689,
"s": 41628,
"text": "prepareStatement(String SQL, int RSType, int RSConcurrency);"
},
{
"code": null,
"e": 41750,
"s": 41689,
"text": "prepareStatement(String SQL, int RSType, int RSConcurrency);"
},
{
"code": null,
"e": 41806,
"s": 41750,
"text": "prepareCall(String sql, int RSType, int RSConcurrency);"
},
{
"code": null,
"e": 41862,
"s": 41806,
"text": "prepareCall(String sql, int RSType, int RSConcurrency);"
},
{
"code": null,
"e": 42043,
"s": 41862,
"text": "The first argument indicates the type of a ResultSet object and the second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable."
},
{
"code": null,
"e": 42180,
"s": 42043,
"text": "The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get one that is TYPE_FORWARD_ONLY."
},
{
"code": null,
"e": 42325,
"s": 42180,
"text": "The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY."
},
{
"code": null,
"e": 42476,
"s": 42325,
"text": "All our examples written so far can be written as follows, which initializes a Statement object to create a forward-only, read only ResultSet object −"
},
{
"code": null,
"e": 42690,
"s": 42476,
"text": "try {\n Statement stmt = conn.createStatement(\n ResultSet.TYPE_FORWARD_ONLY,\n ResultSet.CONCUR_READ_ONLY);\n}\ncatch(Exception ex) {\n ....\n}\nfinally {\n ....\n}"
},
{
"code": null,
"e": 42787,
"s": 42690,
"text": "There are several methods in the ResultSet interface that involve moving the cursor, including −"
},
{
"code": null,
"e": 42831,
"s": 42787,
"text": "Moves the cursor just before the first row."
},
{
"code": null,
"e": 42873,
"s": 42831,
"text": "Moves the cursor just after the last row."
},
{
"code": null,
"e": 42908,
"s": 42873,
"text": "Moves the cursor to the first row."
},
{
"code": null,
"e": 42942,
"s": 42908,
"text": "Moves the cursor to the last row."
},
{
"code": null,
"e": 42981,
"s": 42942,
"text": "Moves the cursor to the specified row."
},
{
"code": null,
"e": 43081,
"s": 42981,
"text": "Moves the cursor the given number of rows forward or backward, from where it is currently\npointing."
},
{
"code": null,
"e": 43188,
"s": 43081,
"text": "Moves the cursor to the previous row. This method returns false if the previous row is off the\nresult set."
},
{
"code": null,
"e": 43293,
"s": 43188,
"text": "Moves the cursor to the next row. This method returns false if there are no more rows in the\nresult set."
},
{
"code": null,
"e": 43348,
"s": 43293,
"text": "Returns the row number that the cursor is pointing to."
},
{
"code": null,
"e": 43500,
"s": 43348,
"text": " Moves the cursor to a special row in the result set that can be used to insert a new row\ninto the database. The current cursor location is remembered."
},
{
"code": null,
"e": 43624,
"s": 43500,
"text": " Moves the cursor back to the current row if the cursor is currently at the insert row;\notherwise, this method does nothing"
},
{
"code": null,
"e": 43690,
"s": 43624,
"text": "For a better understanding, let us study Navigate - Example Code."
},
{
"code": null,
"e": 43782,
"s": 43690,
"text": "The ResultSet interface contains dozens of methods for getting the data of the current row."
},
{
"code": null,
"e": 43880,
"s": 43782,
"text": "There is a get method for each of the possible data types, and each get method has two versions −"
},
{
"code": null,
"e": 43913,
"s": 43880,
"text": "One that takes in a column name."
},
{
"code": null,
"e": 43946,
"s": 43913,
"text": "One that takes in a column name."
},
{
"code": null,
"e": 43980,
"s": 43946,
"text": "One that takes in a column index."
},
{
"code": null,
"e": 44014,
"s": 43980,
"text": "One that takes in a column index."
},
{
"code": null,
"e": 44147,
"s": 44014,
"text": "For example, if the column you are interested in viewing contains an int, you need to use one of the getInt() methods of ResultSet −"
},
{
"code": null,
"e": 44214,
"s": 44147,
"text": "Returns the int in the current row in the column named columnName."
},
{
"code": null,
"e": 44395,
"s": 44214,
"text": " Returns the int in the current row in the specified column index. The column index\nstarts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on."
},
{
"code": null,
"e": 44585,
"s": 44395,
"text": "Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL."
},
{
"code": null,
"e": 44798,
"s": 44585,
"text": "There are also methods for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more information about using these SQL data types."
},
{
"code": null,
"e": 44863,
"s": 44798,
"text": "For a better understanding, let us study Viewing - Example Code."
},
{
"code": null,
"e": 44966,
"s": 44863,
"text": "The ResultSet interface contains a collection of update methods for updating the data of a result set."
},
{
"code": null,
"e": 45041,
"s": 44966,
"text": "As with the get methods, there are two update methods for each data type −"
},
{
"code": null,
"e": 45074,
"s": 45041,
"text": "One that takes in a column name."
},
{
"code": null,
"e": 45107,
"s": 45074,
"text": "One that takes in a column name."
},
{
"code": null,
"e": 45141,
"s": 45107,
"text": "One that takes in a column index."
},
{
"code": null,
"e": 45175,
"s": 45141,
"text": "One that takes in a column index."
},
{
"code": null,
"e": 45310,
"s": 45175,
"text": "For example, to update a String column of the current row of a result set, you would use one of the following updateString() methods −"
},
{
"code": null,
"e": 45372,
"s": 45310,
"text": "Changes the String in the specified column to the value of s."
},
{
"code": null,
"e": 45474,
"s": 45372,
"text": "Similar to the previous method, except that the column is\nspecified by its name instead of its index."
},
{
"code": null,
"e": 45615,
"s": 45474,
"text": "There are update methods for the eight primitive data types, as well as String, Object, URL, and the SQL data types in the java.sql package."
},
{
"code": null,
"e": 45848,
"s": 45615,
"text": "Updating a row in the result set changes the columns of the current row in the ResultSet object, but not in the underlying database. To update your changes to the row in the database, you need to invoke one of the following methods."
},
{
"code": null,
"e": 45923,
"s": 45848,
"text": "Updates the current row by updating the corresponding row in the database."
},
{
"code": null,
"e": 45965,
"s": 45923,
"text": "Deletes the current row from the database"
},
{
"code": null,
"e": 46049,
"s": 45965,
"text": "Refreshes the data in the result set to reflect any recent changes in the database."
},
{
"code": null,
"e": 46094,
"s": 46049,
"text": "Cancels any updates made on the current row."
},
{
"code": null,
"e": 46206,
"s": 46094,
"text": "Inserts a row into the database. This method can only be invoked when the cursor is pointing to the insert row."
},
{
"code": null,
"e": 46277,
"s": 46206,
"text": "For a better understanding, let us study the Updating - Example Code ."
},
{
"code": null,
"e": 46559,
"s": 46277,
"text": "The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL INTEGER. Default mappings were created to provide consistency between drivers."
},
{
"code": null,
"e": 46782,
"s": 46559,
"text": "The following table summarizes the default JDBC data type that the Java data type is converted to, when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method."
},
{
"code": null,
"e": 47025,
"s": 46782,
"text": "JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable you to directly manipulate the respective data on the server."
},
{
"code": null,
"e": 47238,
"s": 47025,
"text": "The setXXX() and updateXXX() methods enable you to convert specific Java types to specific JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java type to a JDBC data type."
},
{
"code": null,
"e": 47408,
"s": 47238,
"text": "ResultSet object provides corresponding getXXX() method for each data type to retrieve column value. Each method can be used with column name or by its ordinal position."
},
{
"code": null,
"e": 47576,
"s": 47408,
"text": "The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and java.sql.Timestamp classes map to the SQL TIME and SQL TIMESTAMP data types, respectively."
},
{
"code": null,
"e": 47717,
"s": 47576,
"text": "Following example shows how the Date and Time classes format the standard Java date and time values to match the SQL data type requirements."
},
{
"code": null,
"e": 48690,
"s": 47717,
"text": "import java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.*;\n\npublic class SqlDateTime {\n public static void main(String[] args) {\n //Get standard date and time\n java.util.Date javaDate = new java.util.Date();\n long javaTime = javaDate.getTime();\n System.out.println(\"The Java Date is:\" + \n javaDate.toString());\n\n //Get and display SQL DATE\n java.sql.Date sqlDate = new java.sql.Date(javaTime);\n System.out.println(\"The SQL DATE is: \" + \n sqlDate.toString());\n\n //Get and display SQL TIME\n java.sql.Time sqlTime = new java.sql.Time(javaTime);\n System.out.println(\"The SQL TIME is: \" + \n sqlTime.toString());\n //Get and display SQL TIMESTAMP\n java.sql.Timestamp sqlTimestamp =\n new java.sql.Timestamp(javaTime);\n System.out.println(\"The SQL TIMESTAMP is: \" + \n sqlTimestamp.toString());\n }//end main\n}//end SqlDateTime"
},
{
"code": null,
"e": 48740,
"s": 48690,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 48772,
"s": 48740,
"text": "C:\\>javac SqlDateTime.java\nC:\\>"
},
{
"code": null,
"e": 48833,
"s": 48772,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 49012,
"s": 48833,
"text": "C:\\>java SqlDateTime\nThe Java Date is:Tue Aug 18 13:46:02 GMT+04:00 2009\nThe SQL DATE is: 2009-08-18\nThe SQL TIME is: 13:46:02\nThe SQL TIMESTAMP is: 2009-08-18 13:46:02.828\nC:\\>\n"
},
{
"code": null,
"e": 49161,
"s": 49012,
"text": "SQL's use of NULL values and Java's use of null are different concepts. So, to handle SQL NULL values in Java, there are three tactics you can use −"
},
{
"code": null,
"e": 49225,
"s": 49161,
"text": "Avoid using getXXX( ) methods that return primitive data types."
},
{
"code": null,
"e": 49289,
"s": 49225,
"text": "Avoid using getXXX( ) methods that return primitive data types."
},
{
"code": null,
"e": 49507,
"s": 49289,
"text": "Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value\nreturned by the getXXX( ) method should be set to null."
},
{
"code": null,
"e": 49725,
"s": 49507,
"text": "Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value\nreturned by the getXXX( ) method should be set to null."
},
{
"code": null,
"e": 49968,
"s": 49725,
"text": "Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( )\nmethod should be set to an acceptable value that you've chosen to represent a NULL."
},
{
"code": null,
"e": 50211,
"s": 49968,
"text": "Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( )\nmethod should be set to an acceptable value that you've chosen to represent a NULL."
},
{
"code": null,
"e": 50256,
"s": 50211,
"text": "Here is one example to handle a NULL value −"
},
{
"code": null,
"e": 50455,
"s": 50256,
"text": "Statement stmt = conn.createStatement( );\nString sql = \"SELECT id, first, last, age FROM Employees\";\nResultSet rs = stmt.executeQuery(sql);\n\nint id = rs.getInt(1);\nif( rs.wasNull( ) ) {\n id = 0;\n}"
},
{
"code": null,
"e": 50602,
"s": 50455,
"text": "If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion."
},
{
"code": null,
"e": 50752,
"s": 50602,
"text": "That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions −"
},
{
"code": null,
"e": 50777,
"s": 50752,
"text": "To increase performance."
},
{
"code": null,
"e": 50802,
"s": 50777,
"text": "To increase performance."
},
{
"code": null,
"e": 50851,
"s": 50802,
"text": "To maintain the integrity of business processes."
},
{
"code": null,
"e": 50900,
"s": 50851,
"text": "To maintain the integrity of business processes."
},
{
"code": null,
"e": 50933,
"s": 50900,
"text": "To use distributed transactions."
},
{
"code": null,
"e": 50966,
"s": 50933,
"text": "To use distributed transactions."
},
{
"code": null,
"e": 51192,
"s": 50966,
"text": "Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails."
},
{
"code": null,
"e": 51481,
"s": 51192,
"text": "To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again."
},
{
"code": null,
"e": 51583,
"s": 51481,
"text": "For example, if you have a Connection object named conn, code the following to turn off auto-commit −"
},
{
"code": null,
"e": 51610,
"s": 51583,
"text": "conn.setAutoCommit(false);"
},
{
"code": null,
"e": 51741,
"s": 51610,
"text": "Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −"
},
{
"code": null,
"e": 51757,
"s": 51741,
"text": "conn.commit( );"
},
{
"code": null,
"e": 51868,
"s": 51757,
"text": "Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −"
},
{
"code": null,
"e": 51886,
"s": 51868,
"text": "conn.rollback( );"
},
{
"code": null,
"e": 51962,
"s": 51886,
"text": "The following example illustrates the use of a commit and rollback object −"
},
{
"code": null,
"e": 52510,
"s": 51962,
"text": "try{\n //Assume a valid connection object conn\n conn.setAutoCommit(false);\n Statement stmt = conn.createStatement();\n \n String SQL = \"INSERT INTO Employees \" +\n \"VALUES (106, 20, 'Rita', 'Tez')\";\n stmt.executeUpdate(SQL); \n //Submit a malformed SQL statement that breaks\n String SQL = \"INSERTED IN Employees \" +\n \"VALUES (107, 22, 'Sita', 'Singh')\";\n stmt.executeUpdate(SQL);\n // If there is no error.\n conn.commit();\n}catch(SQLException se){\n // If there is any error.\n conn.rollback();\n}"
},
{
"code": null,
"e": 52610,
"s": 52510,
"text": "In this case, none of the above INSERT statement would success and everything would be rolled back."
},
{
"code": null,
"e": 52678,
"s": 52610,
"text": "For a better understanding, let us study the Commit - Example Code."
},
{
"code": null,
"e": 52851,
"s": 52678,
"text": "The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern DBMS, support savepoints within their environments such as Oracle's PL/SQL."
},
{
"code": null,
"e": 53080,
"s": 52851,
"text": "When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint."
},
{
"code": null,
"e": 53156,
"s": 53080,
"text": "The Connection object has two new methods that help you manage savepoints −"
},
{
"code": null,
"e": 53254,
"s": 53156,
"text": "setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object."
},
{
"code": null,
"e": 53352,
"s": 53254,
"text": "setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object."
},
{
"code": null,
"e": 53551,
"s": 53352,
"text": "releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method."
},
{
"code": null,
"e": 53750,
"s": 53551,
"text": "releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method."
},
{
"code": null,
"e": 53853,
"s": 53750,
"text": "There is one rollback (String savepointName) method, which rolls back work to the specified savepoint."
},
{
"code": null,
"e": 53919,
"s": 53853,
"text": "The following example illustrates the use of a Savepoint object −"
},
{
"code": null,
"e": 54574,
"s": 53919,
"text": "try{\n //Assume a valid connection object conn\n conn.setAutoCommit(false);\n Statement stmt = conn.createStatement();\n \n //set a Savepoint\n Savepoint savepoint1 = conn.setSavepoint(\"Savepoint1\");\n String SQL = \"INSERT INTO Employees \" +\n \"VALUES (106, 20, 'Rita', 'Tez')\";\n stmt.executeUpdate(SQL); \n //Submit a malformed SQL statement that breaks\n String SQL = \"INSERTED IN Employees \" +\n \"VALUES (107, 22, 'Sita', 'Tez')\";\n stmt.executeUpdate(SQL);\n // If there is no error, commit the changes.\n conn.commit();\n\n}catch(SQLException se){\n // If there is any error.\n conn.rollback(savepoint1);\n}"
},
{
"code": null,
"e": 54674,
"s": 54574,
"text": "In this case, none of the above INSERT statement would success and everything would be rolled back."
},
{
"code": null,
"e": 54746,
"s": 54674,
"text": "For a better understanding, let us study the Savepoints - Example Code."
},
{
"code": null,
"e": 54865,
"s": 54746,
"text": "Exception handling allows you to handle exceptional conditions such as program-defined errors in a controlled fashion."
},
{
"code": null,
"e": 55128,
"s": 54865,
"text": "When an exception condition occurs, an exception is thrown. The term thrown means that current program execution stops, and the control is redirected to the nearest\napplicable catch clause. If no applicable catch clause exists, then the program's execution ends."
},
{
"code": null,
"e": 55282,
"s": 55128,
"text": "JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most common exception you'll deal with is java.sql.SQLException."
},
{
"code": null,
"e": 55443,
"s": 55282,
"text": "An SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause."
},
{
"code": null,
"e": 55570,
"s": 55443,
"text": "The passed SQLException object has the following methods available for retrieving additional information about the exception −"
},
{
"code": null,
"e": 55746,
"s": 55570,
"text": "By utilizing the information available from the Exception object, you can catch an exception and continue your program appropriately. Here is the general form of a try block −"
},
{
"code": null,
"e": 56094,
"s": 55746,
"text": "try {\n // Your risky code goes between these curly braces!!!\n}\ncatch(Exception ex) {\n // Your exception handling code goes between these \n // curly braces, similar to the exception clause \n // in a PL/SQL block.\n}\nfinally {\n // Your must-always-be-executed code goes between these \n // curly braces. Like closing database connection.\n}"
},
{
"code": null,
"e": 56185,
"s": 56094,
"text": "Study the following example code to understand the usage of try....catch...finally blocks."
},
{
"code": null,
"e": 57379,
"s": 56185,
"text": "import java.sql.CallableStatement;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"{call getEmpName (?, ?)}\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n CallableStatement stmt = conn.prepareCall(QUERY);\n ) {\t\t \n // Bind values into the parameters.\n stmt.setInt(1, 1); // This would set ID\n // Because second parameter is OUT so register it\n stmt.registerOutParameter(2, java.sql.Types.VARCHAR);\n //Use execute method to run stored procedure.\n System.out.println(\"Executing stored procedure...\" );\n stmt.execute();\n //Retrieve employee name with getXXX method\n String empName = stmt.getString(2);\n System.out.println(\"Emp Name with ID: 1 is \" + empName);\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 57430,
"s": 57379,
"text": "Now, let us compile the above example as follows −"
},
{
"code": null,
"e": 57462,
"s": 57430,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 57634,
"s": 57462,
"text": "When you run JDBCExample, it produces the following result if there is no problem, otherwise the corresponding error would be caught and error message would be displayed −"
},
{
"code": null,
"e": 57718,
"s": 57634,
"text": "C:\\>java JDBCExample\nExecuting stored procedure...\nEmp Name with ID: 1 is Zara\nC:\\>"
},
{
"code": null,
"e": 57823,
"s": 57718,
"text": "Try the above example by passing wrong database name or wrong username or password and check the result."
},
{
"code": null,
"e": 57943,
"s": 57823,
"text": "Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database."
},
{
"code": null,
"e": 58085,
"s": 57943,
"text": "When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance."
},
{
"code": null,
"e": 58343,
"s": 58085,
"text": "JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature."
},
{
"code": null,
"e": 58601,
"s": 58343,
"text": "JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature."
},
{
"code": null,
"e": 58819,
"s": 58601,
"text": "The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together."
},
{
"code": null,
"e": 59037,
"s": 58819,
"text": "The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together."
},
{
"code": null,
"e": 59181,
"s": 59037,
"text": "The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement."
},
{
"code": null,
"e": 59325,
"s": 59181,
"text": "The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement."
},
{
"code": null,
"e": 59576,
"s": 59325,
"text": "Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove."
},
{
"code": null,
"e": 59827,
"s": 59576,
"text": "Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove."
},
{
"code": null,
"e": 59911,
"s": 59827,
"text": "Here is a typical sequence of steps to use Batch Processing with Statement Object −"
},
{
"code": null,
"e": 59977,
"s": 59911,
"text": "Create a Statement object using either createStatement() methods."
},
{
"code": null,
"e": 60043,
"s": 59977,
"text": "Create a Statement object using either createStatement() methods."
},
{
"code": null,
"e": 60091,
"s": 60043,
"text": "Set auto-commit to false using setAutoCommit()."
},
{
"code": null,
"e": 60139,
"s": 60091,
"text": "Set auto-commit to false using setAutoCommit()."
},
{
"code": null,
"e": 60242,
"s": 60139,
"text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object."
},
{
"code": null,
"e": 60345,
"s": 60242,
"text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object."
},
{
"code": null,
"e": 60433,
"s": 60345,
"text": "Execute all the SQL statements using executeBatch() method on created statement object."
},
{
"code": null,
"e": 60521,
"s": 60433,
"text": "Execute all the SQL statements using executeBatch() method on created statement object."
},
{
"code": null,
"e": 60576,
"s": 60521,
"text": "Finally, commit all the changes using commit() method."
},
{
"code": null,
"e": 60631,
"s": 60576,
"text": "Finally, commit all the changes using commit() method."
},
{
"code": null,
"e": 60721,
"s": 60631,
"text": "The following code snippet provides an example of a batch update using Statement object −"
},
{
"code": null,
"e": 61561,
"s": 60721,
"text": "// Create statement object\nStatement stmt = conn.createStatement();\n\n// Set auto-commit to false\nconn.setAutoCommit(false);\n\n// Create SQL statement\nString SQL = \"INSERT INTO Employees (id, first, last, age) \" +\n \"VALUES(200,'Zia', 'Ali', 30)\";\n// Add above SQL statement in the batch.\nstmt.addBatch(SQL);\n\n// Create one more SQL statement\nString SQL = \"INSERT INTO Employees (id, first, last, age) \" +\n \"VALUES(201,'Raj', 'Kumar', 35)\";\n// Add above SQL statement in the batch.\nstmt.addBatch(SQL);\n\n// Create one more SQL statement\nString SQL = \"UPDATE Employees SET age = 35 \" +\n \"WHERE id = 100\";\n// Add above SQL statement in the batch.\nstmt.addBatch(SQL);\n\n// Create an int[] to hold returned values\nint[] count = stmt.executeBatch();\n\n//Explicitly commit statements to apply changes\nconn.commit();"
},
{
"code": null,
"e": 61631,
"s": 61561,
"text": "For a better understanding, let us study the Batching - Example Code."
},
{
"code": null,
"e": 61722,
"s": 61631,
"text": "Here is a typical sequence of steps to use Batch Processing with PrepareStatement Object −"
},
{
"code": null,
"e": 62132,
"s": 61722,
"text": "\nCreate SQL statements with placeholders.\nCreate PrepareStatement object using either prepareStatement() methods.\nSet auto-commit to false using setAutoCommit().\nAdd as many as SQL statements you like into batch using addBatch() method on created statement object.\nExecute all the SQL statements using executeBatch() method on created statement object.\nFinally, commit all the changes using commit() method.\n"
},
{
"code": null,
"e": 62173,
"s": 62132,
"text": "Create SQL statements with placeholders."
},
{
"code": null,
"e": 62214,
"s": 62173,
"text": "Create SQL statements with placeholders."
},
{
"code": null,
"e": 62287,
"s": 62214,
"text": "Create PrepareStatement object using either prepareStatement() methods."
},
{
"code": null,
"e": 62360,
"s": 62287,
"text": "Create PrepareStatement object using either prepareStatement() methods."
},
{
"code": null,
"e": 62408,
"s": 62360,
"text": "Set auto-commit to false using setAutoCommit()."
},
{
"code": null,
"e": 62456,
"s": 62408,
"text": "Set auto-commit to false using setAutoCommit()."
},
{
"code": null,
"e": 62559,
"s": 62456,
"text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object."
},
{
"code": null,
"e": 62662,
"s": 62559,
"text": "Add as many as SQL statements you like into batch using addBatch() method on created statement object."
},
{
"code": null,
"e": 62750,
"s": 62662,
"text": "Execute all the SQL statements using executeBatch() method on created statement object."
},
{
"code": null,
"e": 62838,
"s": 62750,
"text": "Execute all the SQL statements using executeBatch() method on created statement object."
},
{
"code": null,
"e": 62893,
"s": 62838,
"text": "Finally, commit all the changes using commit() method."
},
{
"code": null,
"e": 62948,
"s": 62893,
"text": "Finally, commit all the changes using commit() method."
},
{
"code": null,
"e": 63045,
"s": 62948,
"text": "The following code snippet provides an example of a batch update using PrepareStatement object −"
},
{
"code": null,
"e": 63823,
"s": 63045,
"text": "// Create SQL statement\nString SQL = \"INSERT INTO Employees (id, first, last, age) \" +\n \"VALUES(?, ?, ?, ?)\";\n\n// Create PrepareStatement object\nPreparedStatemen pstmt = conn.prepareStatement(SQL);\n\n//Set auto-commit to false\nconn.setAutoCommit(false);\n\n// Set the variables\npstmt.setInt( 1, 400 );\npstmt.setString( 2, \"Pappu\" );\npstmt.setString( 3, \"Singh\" );\npstmt.setInt( 4, 33 );\n// Add it to the batch\npstmt.addBatch();\n\n// Set the variables\npstmt.setInt( 1, 401 );\npstmt.setString( 2, \"Pawan\" );\npstmt.setString( 3, \"Singh\" );\npstmt.setInt( 4, 31 );\n// Add it to the batch\npstmt.addBatch();\n\n//add more batches\n.\n.\n.\n.\n//Create an int[] to hold returned values\nint[] count = stmt.executeBatch();\n\n//Explicitly commit statements to apply changes\nconn.commit();"
},
{
"code": null,
"e": 63893,
"s": 63823,
"text": "For a better understanding, let us study the Batching - Example Code."
},
{
"code": null,
"e": 64109,
"s": 63893,
"text": "We have learnt how to use Stored Procedures in JDBC while discussing the JDBC - Statements chapter. This chapter is similar to that section, but it would give you additional information about JDBC SQL escape syntax."
},
{
"code": null,
"e": 64306,
"s": 64109,
"text": "Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure."
},
{
"code": null,
"e": 64375,
"s": 64306,
"text": "Suppose, you need to execute the following Oracle stored procedure −"
},
{
"code": null,
"e": 64545,
"s": 64375,
"text": "CREATE OR REPLACE PROCEDURE getEmpName \n (EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND;"
},
{
"code": null,
"e": 64733,
"s": 64545,
"text": "NOTE − Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database."
},
{
"code": null,
"e": 64975,
"s": 64733,
"text": "DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$\nCREATE PROCEDURE `EMP`.`getEmpName` \n (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND $$\n\nDELIMITER ;"
},
{
"code": null,
"e": 65138,
"s": 64975,
"text": "Three types of parameters exist − IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three."
},
{
"code": null,
"e": 65173,
"s": 65138,
"text": "Here are the definitions of each −"
},
{
"code": null,
"e": 65340,
"s": 65173,
"text": "The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure −"
},
{
"code": null,
"e": 65525,
"s": 65340,
"text": "CallableStatement cstmt = null;\ntry {\n String SQL = \"{call getEmpName (?, ?)}\";\n cstmt = conn.prepareCall (SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}"
},
{
"code": null,
"e": 65611,
"s": 65525,
"text": "The String variable SQL represents the stored procedure, with parameter placeholders."
},
{
"code": null,
"e": 65801,
"s": 65611,
"text": "Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException."
},
{
"code": null,
"e": 65992,
"s": 65801,
"text": "If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding."
},
{
"code": null,
"e": 66231,
"s": 65992,
"text": "When you use OUT and INOUT parameters, you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data type the stored procedure is expected to return."
},
{
"code": null,
"e": 66423,
"s": 66231,
"text": "Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type."
},
{
"code": null,
"e": 66537,
"s": 66423,
"text": "Just as you close other Statement object, for the same reason you should also close the CallableStatement object."
},
{
"code": null,
"e": 66783,
"s": 66537,
"text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup."
},
{
"code": null,
"e": 66977,
"s": 66783,
"text": "CallableStatement cstmt = null;\ntry {\n String SQL = \"{call getEmpName (?, ?)}\";\n cstmt = conn.prepareCall (SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n cstmt.close();\n}"
},
{
"code": null,
"e": 67043,
"s": 66977,
"text": "studyWe have studied more details in the Callable - Example Code."
},
{
"code": null,
"e": 67187,
"s": 67043,
"text": "The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties."
},
{
"code": null,
"e": 67240,
"s": 67187,
"text": "The general SQL escape syntax format is as follows −"
},
{
"code": null,
"e": 67264,
"s": 67240,
"text": "{keyword 'parameters'}\n"
},
{
"code": null,
"e": 67378,
"s": 67264,
"text": "Here are the following escape sequences, which you would find very useful while performing the JDBC programming −"
},
{
"code": null,
"e": 67608,
"s": 67378,
"text": "They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database's format. For Example −"
},
{
"code": null,
"e": 67625,
"s": 67608,
"text": "{d 'yyyy-mm-dd'}"
},
{
"code": null,
"e": 67720,
"s": 67625,
"text": "Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009."
},
{
"code": null,
"e": 67785,
"s": 67720,
"text": "Here is a simple example showing how to INSERT date in a table −"
},
{
"code": null,
"e": 68015,
"s": 67785,
"text": "//Create a Statement object\nstmt = conn.createStatement();\n//Insert data ==> ID, First Name, Last Name, DOB\nString sql=\"INSERT INTO STUDENTS VALUES\" +\n \"(100,'Zara','Ali', {d '2001-12-16'})\";\n\nstmt.executeUpdate(sql);"
},
{
"code": null,
"e": 68090,
"s": 68015,
"text": "Similarly, you can use one of the following two syntaxes, either t or ts −"
},
{
"code": null,
"e": 68106,
"s": 68090,
"text": "{t 'hh:mm:ss'}\n"
},
{
"code": null,
"e": 68197,
"s": 68106,
"text": "Where hh = hour; mm = minute; ss = second. Using this syntax {t '13:30:29'} is 1:30:29 PM."
},
{
"code": null,
"e": 68225,
"s": 68197,
"text": "{ts 'yyyy-mm-dd hh:mm:ss'}\n"
},
{
"code": null,
"e": 68313,
"s": 68225,
"text": "This is combined syntax of the above two syntax for 'd' and 't' to represent timestamp."
},
{
"code": null,
"e": 68471,
"s": 68313,
"text": "This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters. For example −"
},
{
"code": null,
"e": 68587,
"s": 68471,
"text": "String sql = \"SELECT symbol FROM MathSymbols\n WHERE symbol LIKE '\\%' {escape '\\'}\";\nstmt.execute(sql);"
},
{
"code": null,
"e": 68781,
"s": 68587,
"text": "If you use the backslash character (\\) as the escape character, you also have to use two backslash characters in your Java String literal, because the backslash is also a Java escape character."
},
{
"code": null,
"e": 68915,
"s": 68781,
"text": "This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to get the length of a string −"
},
{
"code": null,
"e": 68942,
"s": 68915,
"text": "{fn length('Hello World')}"
},
{
"code": null,
"e": 69009,
"s": 68942,
"text": "This returns 11, the length of the character string 'Hello World'."
},
{
"code": null,
"e": 69151,
"s": 69009,
"text": "This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN parameter, use the following syntax −"
},
{
"code": null,
"e": 69175,
"s": 69151,
"text": "{call my_procedure(?)};"
},
{
"code": null,
"e": 69283,
"s": 69175,
"text": "For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax −"
},
{
"code": null,
"e": 69312,
"s": 69283,
"text": "{? = call my_procedure(?)};\n"
},
{
"code": null,
"e": 69384,
"s": 69312,
"text": "This keyword is used to signify outer joins. The syntax is as follows −"
},
{
"code": null,
"e": 69401,
"s": 69384,
"text": "{oj outer-join}\n"
},
{
"code": null,
"e": 69510,
"s": 69401,
"text": "Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition. For example −"
},
{
"code": null,
"e": 69652,
"s": 69510,
"text": "String sql = \"SELECT Employees \n FROM {oj ThisTable RIGHT\n OUTER JOIN ThatTable on id = '100'}\";\nstmt.execute(sql);"
},
{
"code": null,
"e": 69876,
"s": 69652,
"text": "A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can\nhold large values, such as CLOB and BLOB data types."
},
{
"code": null,
"e": 69942,
"s": 69876,
"text": "There are following methods, which can be used to stream data −"
},
{
"code": null,
"e": 70011,
"s": 69942,
"text": "setAsciiStream() − This method is used to supply large ASCII values."
},
{
"code": null,
"e": 70080,
"s": 70011,
"text": "setAsciiStream() − This method is used to supply large ASCII values."
},
{
"code": null,
"e": 70155,
"s": 70080,
"text": "setCharacterStream() − This method is used to supply large UNICODE values."
},
{
"code": null,
"e": 70230,
"s": 70155,
"text": "setCharacterStream() − This method is used to supply large UNICODE values."
},
{
"code": null,
"e": 70301,
"s": 70230,
"text": "setBinaryStream() − This method is used to supply large binary values."
},
{
"code": null,
"e": 70372,
"s": 70301,
"text": "setBinaryStream() − This method is used to supply large binary values."
},
{
"code": null,
"e": 70574,
"s": 70372,
"text": "The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream."
},
{
"code": null,
"e": 70681,
"s": 70574,
"text": "This example would create a database table XML_Data and then XML content would be written into this table."
},
{
"code": null,
"e": 70773,
"s": 70681,
"text": "Copy and paste the following example in FirstApplication.java, compile and run as follows −"
},
{
"code": null,
"e": 73345,
"s": 70773,
"text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT Data FROM XML_Data WHERE id=100\";\n static final String INSERT_QUERY=\"INSERT INTO XML_Data VALUES (?,?)\";\n static final String CREATE_TABLE_QUERY = \"CREATE TABLE XML_Data (id INTEGER, Data LONG)\";\n static final String DROP_TABLE_QUERY = \"DROP TABLE XML_Data\";\n static final String XML_DATA = \"<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>\";\n \n public static void createXMLTable(Statement stmt) \n throws SQLException{\n System.out.println(\"Creating XML_Data table...\" );\n //Drop table first if it exists.\n try{\n stmt.executeUpdate(DROP_TABLE_QUERY);\n }catch(SQLException se){\n }\n stmt.executeUpdate(CREATE_TABLE_QUERY);\n }\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n PreparedStatement pstmt = conn.prepareStatement(INSERT_QUERY);\n ) {\t\t \n createXMLTable(stmt);\n\n ByteArrayInputStream bis = new ByteArrayInputStream(XML_DATA.getBytes());\n\n pstmt.setInt(1,100);\n pstmt.setAsciiStream(2,bis,XML_DATA.getBytes().length);\n pstmt.execute();\n\n //Close input stream\n bis.close();\n\n ResultSet rs = stmt.executeQuery(QUERY);\n // Get the first row\n if (rs.next ()){\n //Retrieve data from input stream\n InputStream xmlInputStream = rs.getAsciiStream (1);\n int c;\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n while (( c = xmlInputStream.read ()) != -1)\n bos.write(c);\n //Print results\n System.out.println(bos.toString());\n }\n // Clean-up environment\n rs.close();\n\n } catch (SQLException | IOException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 73395,
"s": 73345,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 73432,
"s": 73395,
"text": "C:\\>javac FirstApplication.java\nC:\\>"
},
{
"code": null,
"e": 73498,
"s": 73432,
"text": "When you run FirstApplication, it produces the following result −"
},
{
"code": null,
"e": 73669,
"s": 73498,
"text": "C:\\>java FirstApplication\nCreating XML_Data table...\n<Employee><id>100</id><first>Zara</first><last>Ali</last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>\nC:\\>\n"
},
{
"code": null,
"e": 73839,
"s": 73669,
"text": "This tutorial provides an example on how to create a Database using JDBC application. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 74034,
"s": 73839,
"text": "You should have admin privilege to create a database in the given schema. To execute the following example, you need to replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 74229,
"s": 74034,
"text": "You should have admin privilege to create a database in the given schema. To execute the following example, you need to replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 74280,
"s": 74229,
"text": "Your MySQL or whatever database is up and running."
},
{
"code": null,
"e": 74331,
"s": 74280,
"text": "Your MySQL or whatever database is up and running."
},
{
"code": null,
"e": 74414,
"s": 74331,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 74586,
"s": 74414,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 74758,
"s": 74586,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 75056,
"s": 74758,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database server.\nTo create a new database, you need not give any database name while preparing database URL as mentioned in the below example."
},
{
"code": null,
"e": 75228,
"s": 75056,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database server."
},
{
"code": null,
"e": 75354,
"s": 75228,
"text": "To create a new database, you need not give any database name while preparing database URL as mentioned in the below example."
},
{
"code": null,
"e": 75477,
"s": 75354,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 75600,
"s": 75477,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 75683,
"s": 75600,
"text": "Clean up the environment . try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 75765,
"s": 75683,
"text": "Clean up the environment . try with resources automatically closes the resources."
},
{
"code": null,
"e": 75852,
"s": 75765,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 76587,
"s": 75852,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"CREATE DATABASE STUDENTS\";\n stmt.executeUpdate(sql);\n System.out.println(\"Database created successfully...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 76637,
"s": 76587,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 76669,
"s": 76637,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 76730,
"s": 76669,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 76790,
"s": 76730,
"text": "C:\\>java JDBCExample\nDatabase created successfully...\nC:\\>\n"
},
{
"code": null,
"e": 76959,
"s": 76790,
"text": "This chapter provides an example on how to select a Database using JDBC application. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 77079,
"s": 76959,
"text": "To execute the following example you need to replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 77199,
"s": 77079,
"text": "To execute the following example you need to replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 77265,
"s": 77199,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 77331,
"s": 77265,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 77414,
"s": 77331,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 77590,
"s": 77414,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 77766,
"s": 77590,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 78064,
"s": 77766,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database.\nSelection of database is made while you prepare database URL. Following example would make connection with STUDENTS database."
},
{
"code": null,
"e": 78236,
"s": 78064,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database."
},
{
"code": null,
"e": 78362,
"s": 78236,
"text": "Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database."
},
{
"code": null,
"e": 78445,
"s": 78362,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 78527,
"s": 78445,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 78614,
"s": 78527,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 79286,
"s": 78614,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n System.out.println(\"Connecting to a selected database...\");\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) {\t\t \n System.out.println(\"Connected database successfully...\"); \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 79336,
"s": 79286,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 79368,
"s": 79336,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 79429,
"s": 79368,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 79528,
"s": 79429,
"text": "C:\\>java JDBCExample\nConnecting to a selected database...\nConnected database successfully...\nC:\\>\n"
},
{
"code": null,
"e": 79705,
"s": 79528,
"text": "This chapter provides an example on how to drop an existing Database using JDBC application. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 79825,
"s": 79705,
"text": "To execute the following example you need to replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 79945,
"s": 79825,
"text": "To execute the following example you need to replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 79975,
"s": 79945,
"text": "Your MySQL is up and running."
},
{
"code": null,
"e": 80005,
"s": 79975,
"text": "Your MySQL is up and running."
},
{
"code": null,
"e": 80175,
"s": 80005,
"text": "NOTE: This is a serious operation and you have to make a firm decision before proceeding to delete a database because everything you have in your database would be lost."
},
{
"code": null,
"e": 80258,
"s": 80175,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 80430,
"s": 80258,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 80602,
"s": 80430,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 80901,
"s": 80602,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.\nDeleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database."
},
{
"code": null,
"e": 81071,
"s": 80901,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 81200,
"s": 81071,
"text": "Deleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database."
},
{
"code": null,
"e": 81330,
"s": 81200,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database."
},
{
"code": null,
"e": 81460,
"s": 81330,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database."
},
{
"code": null,
"e": 81543,
"s": 81460,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 81625,
"s": 81543,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 81712,
"s": 81625,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 82445,
"s": 81712,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"DROP DATABASE STUDENTS\";\n stmt.executeUpdate(sql);\n System.out.println(\"Database dropped successfully...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 82495,
"s": 82445,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 82527,
"s": 82495,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 82588,
"s": 82527,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 82648,
"s": 82588,
"text": "C:\\>java JDBCExample\nDatabase dropped successfully...\nC:\\>\n"
},
{
"code": null,
"e": 82814,
"s": 82648,
"text": "This chapter provides an example on how to create a table using JDBC application. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 82930,
"s": 82814,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 83046,
"s": 82930,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 83076,
"s": 83046,
"text": "Your MySQL is up and running."
},
{
"code": null,
"e": 83106,
"s": 83076,
"text": "Your MySQL is up and running."
},
{
"code": null,
"e": 83189,
"s": 83106,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 83361,
"s": 83189,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 83533,
"s": 83361,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 83703,
"s": 83533,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 83873,
"s": 83703,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 84020,
"s": 83873,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to create a table in a seleted database."
},
{
"code": null,
"e": 84167,
"s": 84020,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to create a table in a seleted database."
},
{
"code": null,
"e": 84250,
"s": 84167,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 84332,
"s": 84250,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 84423,
"s": 84332,
"text": "Copy and paste the following example in TestApplication.java, compile and run as follows −"
},
{
"code": null,
"e": 85403,
"s": 84423,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"CREATE TABLE REGISTRATION \" +\n \"(id INTEGER not NULL, \" +\n \" first VARCHAR(255), \" + \n \" last VARCHAR(255), \" + \n \" age INTEGER, \" + \n \" PRIMARY KEY ( id ))\"; \n\n stmt.executeUpdate(sql);\n System.out.println(\"Created table in given database...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 85453,
"s": 85403,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 85489,
"s": 85453,
"text": "C:\\>javac TestApplication.java\nC:\\>"
},
{
"code": null,
"e": 85554,
"s": 85489,
"text": "When you run TestApplication, it produces the following result −"
},
{
"code": null,
"e": 85620,
"s": 85554,
"text": "C:\\>java TestApplication\nCreated table in given database...\nC:\\>\n"
},
{
"code": null,
"e": 85786,
"s": 85620,
"text": "This chapter provides an example on how to delete a table using JDBC application. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 85902,
"s": 85786,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 86018,
"s": 85902,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 86084,
"s": 86018,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 86150,
"s": 86084,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 86341,
"s": 86150,
"text": "NOTE Reformatting JDBC Tutorial This is a serious operation and you have to make a firm decision before proceeding to delete a table, because everything you have in your table would be lost."
},
{
"code": null,
"e": 86424,
"s": 86341,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 86596,
"s": 86424,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 86768,
"s": 86596,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 86938,
"s": 86768,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 87108,
"s": 86938,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 87277,
"s": 87108,
"text": "Execute a queryReformatting JDBC Tutorial Requires using an object of type Statement for building and submitting an SQL statement to drop a table in a seleted database."
},
{
"code": null,
"e": 87446,
"s": 87277,
"text": "Execute a queryReformatting JDBC Tutorial Requires using an object of type Statement for building and submitting an SQL statement to drop a table in a seleted database."
},
{
"code": null,
"e": 87554,
"s": 87446,
"text": "Clean up the environment Reformatting JDBC Tutorial try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 87661,
"s": 87554,
"text": "Clean up the environment Reformatting JDBC Tutorial try with resources automatically closes the resources."
},
{
"code": null,
"e": 87748,
"s": 87661,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 88498,
"s": 87748,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"DROP TABLE REGISTRATION\";\n stmt.executeUpdate(sql);\n System.out.println(\"Table deleted in given database...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 88548,
"s": 88498,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 88580,
"s": 88548,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 88641,
"s": 88580,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 88703,
"s": 88641,
"text": "C:\\>java JDBCExample\nTable deleted in given database...\nC:\\>\n"
},
{
"code": null,
"e": 88876,
"s": 88703,
"text": "This chapter provides an example on how to insert records in a table using JDBC application. Before executing following example, make sure you have the following in place −"
},
{
"code": null,
"e": 88992,
"s": 88876,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 89108,
"s": 88992,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 89173,
"s": 89108,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 89238,
"s": 89173,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 89321,
"s": 89238,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 89493,
"s": 89321,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 89665,
"s": 89493,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 89790,
"s": 89665,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 89915,
"s": 89790,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 90085,
"s": 89915,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 90255,
"s": 90085,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 90393,
"s": 90255,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table."
},
{
"code": null,
"e": 90531,
"s": 90393,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table."
},
{
"code": null,
"e": 90612,
"s": 90531,
"text": "Clean up the environment try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 90692,
"s": 90612,
"text": "Clean up the environment try with resources automatically closes the resources."
},
{
"code": null,
"e": 90779,
"s": 90692,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 92003,
"s": 90779,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n // Execute a query\n System.out.println(\"Inserting records into the table...\"); \n String sql = \"INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)\";\n stmt.executeUpdate(sql);\n System.out.println(\"Inserted records into the table...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 92053,
"s": 92003,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 92085,
"s": 92053,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 92146,
"s": 92085,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 92244,
"s": 92146,
"text": "C:\\>java JDBCExample\nInserting records into the table...\nInserted records into the table...\nC:\\>\n"
},
{
"code": null,
"e": 92430,
"s": 92244,
"text": "This chapter provides an example on how to select/ fetch records from a table using JDBC application. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 92546,
"s": 92430,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 92662,
"s": 92546,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 92727,
"s": 92662,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 92792,
"s": 92727,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 92875,
"s": 92792,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 93047,
"s": 92875,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 93219,
"s": 93047,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 93389,
"s": 93219,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 93559,
"s": 93389,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 93711,
"s": 93559,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to select (i.e. fetch ) records from a table."
},
{
"code": null,
"e": 93863,
"s": 93711,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to select (i.e. fetch ) records from a table."
},
{
"code": null,
"e": 93945,
"s": 93863,
"text": "Extract Data − Once SQL query is executed, you can fetch records from the table."
},
{
"code": null,
"e": 94027,
"s": 93945,
"text": "Extract Data − Once SQL query is executed, you can fetch records from the table."
},
{
"code": null,
"e": 94111,
"s": 94027,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 94194,
"s": 94111,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 94281,
"s": 94194,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 95349,
"s": 94281,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ResultSet rs = stmt.executeQuery(QUERY);\n ) {\t\t \n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 95399,
"s": 95349,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 95431,
"s": 95399,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 95492,
"s": 95431,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 95692,
"s": 95492,
"text": "C:\\>java JDBCExample\nID: 100, Age: 18, First: Zara, Last: Ali\nID: 101, Age: 25, First: Mahnaz, Last: Fatma\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 95869,
"s": 95692,
"text": "This chapter provides an example on how to update records in a table using JDBC application. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 95985,
"s": 95869,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 96101,
"s": 95985,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 96166,
"s": 96101,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 96231,
"s": 96166,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 96314,
"s": 96231,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 96486,
"s": 96314,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 96658,
"s": 96486,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 96828,
"s": 96658,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 96998,
"s": 96828,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 97209,
"s": 96998,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records."
},
{
"code": null,
"e": 97420,
"s": 97209,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records."
},
{
"code": null,
"e": 97503,
"s": 97420,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 97585,
"s": 97503,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 97672,
"s": 97585,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 98893,
"s": 97672,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"UPDATE Registration \" +\n \"SET age = 30 WHERE id in (100, 101)\";\n stmt.executeUpdate(sql);\n ResultSet rs = stmt.executeQuery(QUERY);\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 98943,
"s": 98893,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 98975,
"s": 98943,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 99036,
"s": 98975,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 99236,
"s": 99036,
"text": "C:\\>java JDBCExample\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 101, Age: 30, First: Mahnaz, Last: Fatma\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 99411,
"s": 99236,
"text": "This chapter provides an example on how to delete records from a table using JDBC application. Before executing following example, make sure you have the following in place −"
},
{
"code": null,
"e": 99527,
"s": 99411,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 99643,
"s": 99527,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 99708,
"s": 99643,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 99773,
"s": 99708,
"text": "Your MySQL or whatever database you are using is up and running."
},
{
"code": null,
"e": 99856,
"s": 99773,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 100028,
"s": 99856,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 100200,
"s": 100028,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 100325,
"s": 100200,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 100450,
"s": 100325,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 100620,
"s": 100450,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 100790,
"s": 100620,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 101000,
"s": 100790,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of the WHERE clause to delete conditional records."
},
{
"code": null,
"e": 101210,
"s": 101000,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete records from a table. This Query makes use of the WHERE clause to delete conditional records."
},
{
"code": null,
"e": 101293,
"s": 101210,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 101375,
"s": 101293,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 101462,
"s": 101375,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 102667,
"s": 101462,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"DELETE FROM Registration \" +\n \"WHERE id = 101\";\n stmt.executeUpdate(sql);\n ResultSet rs = stmt.executeQuery(QUERY);\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 102717,
"s": 102667,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 102749,
"s": 102717,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 102810,
"s": 102749,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 102965,
"s": 102810,
"text": "C:\\>java JDBCExample\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 103240,
"s": 102965,
"text": "This chapter provides an example on how to select records from a table using JDBC application. This would add additional conditions using WHERE clause while selecting records from the table. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 103356,
"s": 103240,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 103472,
"s": 103356,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 103538,
"s": 103472,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 103604,
"s": 103538,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 103687,
"s": 103604,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 103863,
"s": 103687,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 104039,
"s": 103863,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 104164,
"s": 104039,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 104289,
"s": 104164,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 104459,
"s": 104289,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 104629,
"s": 104459,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 104858,
"s": 104629,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table, which meet the given condition. This Query makes use of the WHERE clause to select records."
},
{
"code": null,
"e": 105087,
"s": 104858,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table, which meet the given condition. This Query makes use of the WHERE clause to select records."
},
{
"code": null,
"e": 105170,
"s": 105087,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 105252,
"s": 105170,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 105343,
"s": 105252,
"text": "Copy and paste the following example in TestApplication.java, compile and run as follows −"
},
{
"code": null,
"e": 107095,
"s": 105343,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();) {\t\t \n System.out.println(\"Fetching records without condition...\");\n ResultSet rs = stmt.executeQuery(QUERY);\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n\n // Select all records having ID equal or greater than 101\n System.out.println(\"Fetching records with condition...\");\n String sql = \"SELECT id, first, last, age FROM Registration\" +\n \" WHERE id >= 101 \";\n rs = stmt.executeQuery(sql);\n\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 107145,
"s": 107095,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 107181,
"s": 107145,
"text": "C:\\>javac TestApplication.java\nC:\\>"
},
{
"code": null,
"e": 107246,
"s": 107181,
"text": "When you run TestApplication, it produces the following result −"
},
{
"code": null,
"e": 107565,
"s": 107246,
"text": "C:\\>java TestApplication\nFetching records without condition...\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nFetching records with condition...\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 107839,
"s": 107565,
"text": "This chapter provides an example on how to select records from a table using JDBC application. This would add additional conditions using LIKE clause while selecting records from the table. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 107955,
"s": 107839,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 108071,
"s": 107955,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 108137,
"s": 108071,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 108203,
"s": 108137,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 108286,
"s": 108203,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 108458,
"s": 108286,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 108630,
"s": 108458,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 108800,
"s": 108630,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 108970,
"s": 108800,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 109250,
"s": 108970,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table which meet given condition. This Query makes use of LIKE clause to select records to select all the students whose first name starts with \"za\"."
},
{
"code": null,
"e": 109530,
"s": 109250,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to fetch records from a table which meet given condition. This Query makes use of LIKE clause to select records to select all the students whose first name starts with \"za\"."
},
{
"code": null,
"e": 109613,
"s": 109530,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 109695,
"s": 109613,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 109782,
"s": 109695,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 111537,
"s": 109782,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();) {\t\t \n System.out.println(\"Fetching records without condition...\");\n ResultSet rs = stmt.executeQuery(QUERY);\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n\n // Select all records having ID equal or greater than 101\n System.out.println(\"Fetching records with condition...\");\n String sql = \"SELECT id, first, last, age FROM Registration\" +\n \" WHERE first LIKE '%za%'\";\n rs = stmt.executeQuery(sql);\n\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 111587,
"s": 111537,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 111619,
"s": 111587,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 111680,
"s": 111619,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 111991,
"s": 111680,
"text": "C:\\>java JDBCExample\nFetching records without condition...\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nFetching records with condition...\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 102, Age: 30, First: Zaid, Last: Khan\nC:\\>\n"
},
{
"code": null,
"e": 112255,
"s": 111991,
"text": "This chapter provides an example on how to sort records from a table using JDBC application. This would use asc and desc keywords to sort records in ascending or descending order. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 112371,
"s": 112255,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 112487,
"s": 112371,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 112553,
"s": 112487,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 112619,
"s": 112553,
"text": "Your MySQL or whatever database you are using, is up and running."
},
{
"code": null,
"e": 112702,
"s": 112619,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 112874,
"s": 112702,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 113046,
"s": 112874,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 113216,
"s": 113046,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 113386,
"s": 113216,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 113617,
"s": 113386,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to sort records from a table. These Queries make use of asc and desc clauses to sort data in ascending and descening orders."
},
{
"code": null,
"e": 113848,
"s": 113617,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to sort records from a table. These Queries make use of asc and desc clauses to sort data in ascending and descening orders."
},
{
"code": null,
"e": 113931,
"s": 113848,
"text": "Clean up the environment − try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 114013,
"s": 113931,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 114100,
"s": 114013,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 115732,
"s": 114100,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();) {\t\t \n System.out.println(\"Fetching records in ascending order...\");\n ResultSet rs = stmt.executeQuery(QUERY + \" ORDER BY first ASC\");\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n\n System.out.println(\"Fetching records in descending order...\");\n rs = stmt.executeQuery(QUERY + \" ORDER BY first DESC\");\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 115782,
"s": 115732,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 115814,
"s": 115782,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 115875,
"s": 115814,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 116237,
"s": 115875,
"text": "C:\\>java JDBCExample\nFetching records in ascending order...\nID: 103, Age: 28, First: Sumit, Last: Mittal\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 100, Age: 30, First: Zara, Last: Ali\nFetching records in descending order...\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 116270,
"s": 116237,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 116286,
"s": 116270,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 116319,
"s": 116286,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 116335,
"s": 116319,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 116370,
"s": 116335,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 116384,
"s": 116370,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 116418,
"s": 116384,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 116432,
"s": 116418,
"text": " Tushar Kale"
},
{
"code": null,
"e": 116469,
"s": 116432,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 116484,
"s": 116469,
"text": " Monica Mittal"
},
{
"code": null,
"e": 116517,
"s": 116484,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 116536,
"s": 116517,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 116543,
"s": 116536,
"text": " Print"
},
{
"code": null,
"e": 116554,
"s": 116543,
"text": " Add Notes"
}
] |
How to create Ordered dictionaries in Python?
|
An OrderedDict is a dictionary subclass that remembers the order in which its contents are added, It is defined in collections module of Python library. OrderDict remembers the order of addition of key-value pairs in a dictionary
>>> from collections import OrderedDict
>>> od=OrderedDict(d.items())
>>> od
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
>>> t=od.popitem()
>>> t
('orange', 2)
|
[
{
"code": null,
"e": 1292,
"s": 1062,
"text": "An OrderedDict is a dictionary subclass that remembers the order in which its contents are added, It is defined in collections module of Python library. OrderDict remembers the order of addition of key-value pairs in a dictionary"
},
{
"code": null,
"e": 1479,
"s": 1292,
"text": ">>> from collections import OrderedDict\n>>> od=OrderedDict(d.items())\n>>> od\nOrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])\n>>> t=od.popitem()\n>>> t\n('orange', 2)"
}
] |
How to select rows of a data frame that are not in other data frame in R?
|
Instead of finding the common rows, sometimes we need to find the uncommon rows between two data frames. It is mostly used when we expect that a large number of rows are uncommon instead of few ones. We can do this by using the negation operator which is represented by exclamation sign with subset function.
Consider the below data frames −
Live Demo
> x1<-sample(1:10,20,replace=TRUE)
> y1<-sample(1:10,20,replace=TRUE)
> df1<-data.frame(x1,y1)
> df1
x1 y1
1 10 6
2 5 9
3 10 10
4 4 10
5 1 6
6 1 4
7 9 3
8 5 10
9 10 3
10 8 2
11 6 10
12 6 3
13 9 3
14 3 6
15 6 9
16 9 1
17 7 9
18 3 8
19 2 5
20 4 9
Live Demo
> x2<-sample(1:10,20,replace=TRUE)
> y2<-sample(1:10,20,replace=TRUE)
> df2<-data.frame(x2,y2)
> df2
x2 y2
1 6 10
2 3 6
3 9 6
4 9 10
5 10 10
6 3 2
7 3 3
8 2 9
9 7 5
10 1 1
11 10 10
12 1 6
13 3 4
14 4 2
15 6 3
16 1 7
17 2 2
18 4 6
19 4 1
20 1 8
Now suppose we want to take a subset of df2 variable y2 that are not in y1 of df1, then it can be done as follows −
> subset(df2,!(y2%in%df1$y1))
x2 y2
16 1 7
<0 rows> (or 0-length row.names)
Similarly, taking a subset of df2 variable y2 that are not in x1 of df1, then it can be done as follows −
> subset(df2,!(y2%in%df1$x1))
[1] x2 y2
<0 rows> (or 0-length row.names)
Let’s have a look at one more example −
Live Demo
> x1<-rep(1:10,2)
> df1<-data.frame(x1)
> df1
x1
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 1
12 2
13 3
14 4
15 5
16 6
17 7
18 8
19 9
20 10
Live Demo
> x2<-rep(1:5,4)
> df2<-data.frame(x2)
> df2
x2
1 1
2 2
3 3
4 4
5 5
6 1
7 2
8 3
9 4
10 5
11 1
12 2
13 3
14 4
15 5
16 1
17 2
18 3
19 4
20 5
> subset(df1,!(x1%in%df2$x2))
x1
6 6
7 7
8 8
9 9
10 10
16 6
17 7
18 8
19 9
20 10
|
[
{
"code": null,
"e": 1371,
"s": 1062,
"text": "Instead of finding the common rows, sometimes we need to find the uncommon rows between two data frames. It is mostly used when we expect that a large number of rows are uncommon instead of few ones. We can do this by using the negation operator which is represented by exclamation sign with subset function."
},
{
"code": null,
"e": 1404,
"s": 1371,
"text": "Consider the below data frames −"
},
{
"code": null,
"e": 1415,
"s": 1404,
"text": " Live Demo"
},
{
"code": null,
"e": 1516,
"s": 1415,
"text": "> x1<-sample(1:10,20,replace=TRUE)\n> y1<-sample(1:10,20,replace=TRUE)\n> df1<-data.frame(x1,y1)\n> df1"
},
{
"code": null,
"e": 1661,
"s": 1516,
"text": " x1 y1\n1 10 6\n2 5 9\n3 10 10\n4 4 10\n5 1 6\n6 1 4\n7 9 3\n8 5 10\n9 10 3\n10 8 2\n11 6 10\n12 6 3\n13 9 3\n14 3 6\n15 6 9\n16 9 1\n17 7 9\n18 3 8\n19 2 5\n20 4 9"
},
{
"code": null,
"e": 1672,
"s": 1661,
"text": " Live Demo"
},
{
"code": null,
"e": 1773,
"s": 1672,
"text": "> x2<-sample(1:10,20,replace=TRUE)\n> y2<-sample(1:10,20,replace=TRUE)\n> df2<-data.frame(x2,y2)\n> df2"
},
{
"code": null,
"e": 1917,
"s": 1773,
"text": " x2 y2\n1 6 10\n2 3 6\n3 9 6\n4 9 10\n5 10 10\n6 3 2\n7 3 3\n8 2 9\n9 7 5\n10 1 1\n11 10 10\n12 1 6\n13 3 4\n14 4 2\n15 6 3\n16 1 7\n17 2 2\n18 4 6\n19 4 1\n20 1 8"
},
{
"code": null,
"e": 2033,
"s": 1917,
"text": "Now suppose we want to take a subset of df2 variable y2 that are not in y1 of df1, then it can be done as follows −"
},
{
"code": null,
"e": 2109,
"s": 2033,
"text": "> subset(df2,!(y2%in%df1$y1))\nx2 y2\n16 1 7\n<0 rows> (or 0-length row.names)"
},
{
"code": null,
"e": 2215,
"s": 2109,
"text": "Similarly, taking a subset of df2 variable y2 that are not in x1 of df1, then it can be done as follows −"
},
{
"code": null,
"e": 2288,
"s": 2215,
"text": "> subset(df2,!(y2%in%df1$x1))\n[1] x2 y2\n<0 rows> (or 0-length row.names)"
},
{
"code": null,
"e": 2328,
"s": 2288,
"text": "Let’s have a look at one more example −"
},
{
"code": null,
"e": 2339,
"s": 2328,
"text": " Live Demo"
},
{
"code": null,
"e": 2385,
"s": 2339,
"text": "> x1<-rep(1:10,2)\n> df1<-data.frame(x1)\n> df1"
},
{
"code": null,
"e": 2482,
"s": 2385,
"text": " x1\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7\n8 8\n9 9\n10 10\n11 1\n12 2\n13 3\n14 4\n15 5\n16 6\n17 7\n18 8\n19 9\n20 10"
},
{
"code": null,
"e": 2493,
"s": 2482,
"text": " Live Demo"
},
{
"code": null,
"e": 2538,
"s": 2493,
"text": "> x2<-rep(1:5,4)\n> df2<-data.frame(x2)\n> df2"
},
{
"code": null,
"e": 2633,
"s": 2538,
"text": " x2\n1 1\n2 2\n3 3\n4 4\n5 5\n6 1\n7 2\n8 3\n9 4\n10 5\n11 1\n12 2\n13 3\n14 4\n15 5\n16 1\n17 2\n18 3\n19 4\n20 5"
},
{
"code": null,
"e": 2663,
"s": 2633,
"text": "> subset(df1,!(x1%in%df2$x2))"
},
{
"code": null,
"e": 2715,
"s": 2663,
"text": " x1\n6 6\n7 7\n8 8\n9 9\n10 10\n16 6\n17 7\n18 8\n19 9\n20 10"
}
] |
ftp - Unix, Linux Command
|
ftp - Internet file transfer program
ftp [-pinegvd] [host]
pftp [-inegvd] [host]
Example-1:
To see help of all available commands in ftp
$ ftp
ftp> help
output:
$ ftpftp> helpCommands may be abbreviated. Commands are:! dir mdelete qc site$ disconnect mdir sendport sizeaccount exit mget put statusappend form mkdir pwd structascii get mls quit systembell glob mode quote suniquebinary hash modtime recv tenexbye help mput reget tickcase idle newer rstatus tracecd image nmap rhelp typecdup ipany nlist rename userchmod ipv4 ntrans reset umaskclose ipv6 open restart verbosecr lcd prompt rmdir ?delete ls passive runiquedebug macdef proxy send
Example-2:
To Changing FTP Mode to binary or ascii
ftp> ascii
output:
200 Type set to A.
Example-3:
To Download a file using ftp:
ftp> get README
output:200 PORT command successful. 150 ASCII data connection for README (128.138.242.10,3134) (2881 bytes). 226 ASCII Transfer complete. local: README remote: README 2939 bytes received in 0.066 seconds (43 Kbytes/s)
Example-4:
Example-5:
To Changing the remote and local directory:
ftp> pwd
257 "/myftpserver" is current directory.
ftp> cd dir1
250 CWD command successful. "/myftpserver/dir1" is current directory.
ftp> pwd
257 "/myftpserver/dir1" is current directory.
Example-6:
Listing the contents of remote directory from FTP
ftp> ls
output:
200 PORT command successful.150 ASCII data connection for /bin/ls (128.138.242.10,3133) (0 bytes).ElementsofAVS.ps.Z
. . .execsumm_tr.ps.ZviShortRef.ps.Z226 ASCII Transfer complete.418 bytes received in 0.043 seconds (9.5 Kbytes/s)
Example-7:
ftp> mput Makefile
output:
200 PORT command successful.150 Opening ASCII mode data connection for Makefile.226 Transfer complete.local: Makefile remote: Makefile1020 bytes sent in 0.0062 seconds (1.6e+02 Kbytes/s)
Example-8:
To Close a FTP connection:
ftp> close
output:
221 Goodbye.
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": 10614,
"s": 10577,
"text": "ftp - Internet file transfer program"
},
{
"code": null,
"e": 10659,
"s": 10614,
"text": "ftp [-pinegvd] [host]\n\npftp [-inegvd] [host]"
},
{
"code": null,
"e": 10670,
"s": 10659,
"text": "Example-1:"
},
{
"code": null,
"e": 10715,
"s": 10670,
"text": "To see help of all available commands in ftp"
},
{
"code": null,
"e": 10721,
"s": 10715,
"text": "$ ftp"
},
{
"code": null,
"e": 10731,
"s": 10721,
"text": "ftp> help"
},
{
"code": null,
"e": 10739,
"s": 10731,
"text": "output:"
},
{
"code": null,
"e": 11876,
"s": 10739,
"text": "$ ftpftp> helpCommands may be abbreviated. Commands are:! dir mdelete qc site$ disconnect mdir sendport sizeaccount exit mget put statusappend form mkdir pwd structascii get mls quit systembell glob mode quote suniquebinary hash modtime recv tenexbye help mput reget tickcase idle newer rstatus tracecd image nmap rhelp typecdup ipany nlist rename userchmod ipv4 ntrans reset umaskclose ipv6 open restart verbosecr lcd prompt rmdir ?delete ls passive runiquedebug macdef proxy send"
},
{
"code": null,
"e": 11887,
"s": 11876,
"text": "Example-2:"
},
{
"code": null,
"e": 11927,
"s": 11887,
"text": "To Changing FTP Mode to binary or ascii"
},
{
"code": null,
"e": 11938,
"s": 11927,
"text": "ftp> ascii"
},
{
"code": null,
"e": 11946,
"s": 11938,
"text": "output:"
},
{
"code": null,
"e": 11966,
"s": 11946,
"text": "200 Type set to A.\n"
},
{
"code": null,
"e": 11977,
"s": 11966,
"text": "Example-3:"
},
{
"code": null,
"e": 12007,
"s": 11977,
"text": "To Download a file using ftp:"
},
{
"code": null,
"e": 12025,
"s": 12007,
"text": "ftp> get README "
},
{
"code": null,
"e": 12247,
"s": 12025,
"text": "output:200 PORT command successful. 150 ASCII data connection for README (128.138.242.10,3134) (2881 bytes). 226 ASCII Transfer complete. local: README remote: README 2939 bytes received in 0.066 seconds (43 Kbytes/s)"
},
{
"code": null,
"e": 12258,
"s": 12247,
"text": "Example-4:"
},
{
"code": null,
"e": 12269,
"s": 12258,
"text": "Example-5:"
},
{
"code": null,
"e": 12313,
"s": 12269,
"text": "To Changing the remote and local directory:"
},
{
"code": null,
"e": 12322,
"s": 12313,
"text": "ftp> pwd"
},
{
"code": null,
"e": 12363,
"s": 12322,
"text": "257 \"/myftpserver\" is current directory."
},
{
"code": null,
"e": 12376,
"s": 12363,
"text": "ftp> cd dir1"
},
{
"code": null,
"e": 12446,
"s": 12376,
"text": "250 CWD command successful. \"/myftpserver/dir1\" is current directory."
},
{
"code": null,
"e": 12455,
"s": 12446,
"text": "ftp> pwd"
},
{
"code": null,
"e": 12501,
"s": 12455,
"text": "257 \"/myftpserver/dir1\" is current directory."
},
{
"code": null,
"e": 12512,
"s": 12501,
"text": "Example-6:"
},
{
"code": null,
"e": 12562,
"s": 12512,
"text": "Listing the contents of remote directory from FTP"
},
{
"code": null,
"e": 12570,
"s": 12562,
"text": "ftp> ls"
},
{
"code": null,
"e": 12578,
"s": 12570,
"text": "output:"
},
{
"code": null,
"e": 12695,
"s": 12578,
"text": "200 PORT command successful.150 ASCII data connection for /bin/ls (128.138.242.10,3133) (0 bytes).ElementsofAVS.ps.Z"
},
{
"code": null,
"e": 12810,
"s": 12695,
"text": ". . .execsumm_tr.ps.ZviShortRef.ps.Z226 ASCII Transfer complete.418 bytes received in 0.043 seconds (9.5 Kbytes/s)"
},
{
"code": null,
"e": 12821,
"s": 12810,
"text": "Example-7:"
},
{
"code": null,
"e": 12840,
"s": 12821,
"text": "ftp> mput Makefile"
},
{
"code": null,
"e": 12848,
"s": 12840,
"text": "output:"
},
{
"code": null,
"e": 13035,
"s": 12848,
"text": "200 PORT command successful.150 Opening ASCII mode data connection for Makefile.226 Transfer complete.local: Makefile remote: Makefile1020 bytes sent in 0.0062 seconds (1.6e+02 Kbytes/s)"
},
{
"code": null,
"e": 13046,
"s": 13035,
"text": "Example-8:"
},
{
"code": null,
"e": 13073,
"s": 13046,
"text": "To Close a FTP connection:"
},
{
"code": null,
"e": 13084,
"s": 13073,
"text": "ftp> close"
},
{
"code": null,
"e": 13092,
"s": 13084,
"text": "output:"
},
{
"code": null,
"e": 13105,
"s": 13092,
"text": "221 Goodbye."
},
{
"code": null,
"e": 13140,
"s": 13105,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 13168,
"s": 13140,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 13202,
"s": 13168,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13219,
"s": 13202,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 13252,
"s": 13219,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13263,
"s": 13252,
"text": " Pradeep D"
},
{
"code": null,
"e": 13298,
"s": 13263,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13314,
"s": 13298,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 13347,
"s": 13314,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13359,
"s": 13347,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 13391,
"s": 13359,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13399,
"s": 13391,
"text": " Uplatz"
},
{
"code": null,
"e": 13406,
"s": 13399,
"text": " Print"
},
{
"code": null,
"e": 13417,
"s": 13406,
"text": " Add Notes"
}
] |
What is the height of the status bar in Android?
|
This example demonstrates how to height of the status bar in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getStatusBarHeight();
}
private int getStatusBarHeight() {
int height;
Resources myResources = getResources();
int idStatusBarHeight = myResources.getIdentifier( "status_bar_height", "dimen", "android");
if (idStatusBarHeight > 0) {
height = getResources().getDimensionPixelSize(idStatusBarHeight);
Toast.makeText(this, "Status Bar Height = " + height, Toast.LENGTH_LONG).show();
} else {
height = 0;
Toast.makeText(this, "Resources NOT found", Toast.LENGTH_LONG).show();
}
return height;
}
}
Step 4 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "This example demonstrates how to height of the status bar in Android."
},
{
"code": null,
"e": 1261,
"s": 1132,
"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": 1326,
"s": 1261,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2088,
"s": 1326,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</androidx.constraintlayout.widget.ConstraintLayout>"
},
{
"code": null,
"e": 2145,
"s": 2088,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3134,
"s": 2145,
"text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.content.res.Resources;\nimport android.os.Bundle;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n getStatusBarHeight();\n }\n private int getStatusBarHeight() {\n int height;\n Resources myResources = getResources();\n int idStatusBarHeight = myResources.getIdentifier( \"status_bar_height\", \"dimen\", \"android\");\n if (idStatusBarHeight > 0) {\n height = getResources().getDimensionPixelSize(idStatusBarHeight);\n Toast.makeText(this, \"Status Bar Height = \" + height, Toast.LENGTH_LONG).show();\n } else {\n height = 0;\n Toast.makeText(this, \"Resources NOT found\", Toast.LENGTH_LONG).show();\n }\n return height;\n }\n}"
},
{
"code": null,
"e": 3199,
"s": 3134,
"text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml"
},
{
"code": null,
"e": 3869,
"s": 3199,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.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": 4220,
"s": 3869,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4261,
"s": 4220,
"text": "Click here to download the project code."
}
] |
MomentJS - Now
|
This will display the current date.
var now = moment();
To get the current date, we have to use the following code −
now._d
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1996,
"s": 1960,
"text": "This will display the current date."
},
{
"code": null,
"e": 2016,
"s": 1996,
"text": "var now = moment();"
},
{
"code": null,
"e": 2077,
"s": 2016,
"text": "To get the current date, we have to use the following code −"
},
{
"code": null,
"e": 2084,
"s": 2077,
"text": "now._d"
},
{
"code": null,
"e": 2091,
"s": 2084,
"text": " Print"
},
{
"code": null,
"e": 2102,
"s": 2091,
"text": " Add Notes"
}
] |
Program to find the minimum cost to arrange the numbers in ascending or descending order in Python
|
Suppose we have a list of numbers called nums, we have to find the minimum cost to sort the
list in any order (Ascending or Descending). Here the cost is the sum of differences between any
element's old and new value.
So, if the input is like [2, 5, 4], then the output will be 2.
To solve this, we will follow these steps −
temp:= copy the array nums
sort the list temp
c1:= 0, c2:= 0
n:= size of nums
for i in range 0 to n, doif nums[i] is not same as temp[i], thenc1 := c1 + |nums[i]-temp[i]|if nums[i] is not same as temp[n-1-i], thenc2 := c2 + |nums[i]-temp[n-i-1]|
if nums[i] is not same as temp[i], thenc1 := c1 + |nums[i]-temp[i]|
c1 := c1 + |nums[i]-temp[i]|
if nums[i] is not same as temp[n-1-i], thenc2 := c2 + |nums[i]-temp[n-i-1]|
c2 := c2 + |nums[i]-temp[n-i-1]|
return minimum of c1 and c2
Let us see the following implementation to get better understanding −
class Solution:
def solve(self, nums):
temp=nums.copy()
temp.sort()
c1=0
c2=0
n=len(nums)
for i in range(n):
if nums[i]!=temp[i]:
c1+=abs(nums[i]-temp[i])
if nums[i]!=temp[n-1-i]:
c2+=abs(nums[i]-temp[n-i-1])
return min(c1,c2)
ob = Solution()
print(ob.solve([2, 5, 4]))
[2, 5, 4]
2
|
[
{
"code": null,
"e": 1280,
"s": 1062,
"text": "Suppose we have a list of numbers called nums, we have to find the minimum cost to sort the\nlist in any order (Ascending or Descending). Here the cost is the sum of differences between any\nelement's old and new value."
},
{
"code": null,
"e": 1343,
"s": 1280,
"text": "So, if the input is like [2, 5, 4], then the output will be 2."
},
{
"code": null,
"e": 1387,
"s": 1343,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1414,
"s": 1387,
"text": "temp:= copy the array nums"
},
{
"code": null,
"e": 1433,
"s": 1414,
"text": "sort the list temp"
},
{
"code": null,
"e": 1448,
"s": 1433,
"text": "c1:= 0, c2:= 0"
},
{
"code": null,
"e": 1465,
"s": 1448,
"text": "n:= size of nums"
},
{
"code": null,
"e": 1633,
"s": 1465,
"text": "for i in range 0 to n, doif nums[i] is not same as temp[i], thenc1 := c1 + |nums[i]-temp[i]|if nums[i] is not same as temp[n-1-i], thenc2 := c2 + |nums[i]-temp[n-i-1]|"
},
{
"code": null,
"e": 1701,
"s": 1633,
"text": "if nums[i] is not same as temp[i], thenc1 := c1 + |nums[i]-temp[i]|"
},
{
"code": null,
"e": 1730,
"s": 1701,
"text": "c1 := c1 + |nums[i]-temp[i]|"
},
{
"code": null,
"e": 1806,
"s": 1730,
"text": "if nums[i] is not same as temp[n-1-i], thenc2 := c2 + |nums[i]-temp[n-i-1]|"
},
{
"code": null,
"e": 1839,
"s": 1806,
"text": "c2 := c2 + |nums[i]-temp[n-i-1]|"
},
{
"code": null,
"e": 1867,
"s": 1839,
"text": "return minimum of c1 and c2"
},
{
"code": null,
"e": 1937,
"s": 1867,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2294,
"s": 1937,
"text": "class Solution:\n def solve(self, nums):\n temp=nums.copy()\n temp.sort()\n c1=0\n c2=0\n n=len(nums)\n for i in range(n):\n if nums[i]!=temp[i]:\n c1+=abs(nums[i]-temp[i])\n if nums[i]!=temp[n-1-i]:\n c2+=abs(nums[i]-temp[n-i-1])\n return min(c1,c2)\nob = Solution()\nprint(ob.solve([2, 5, 4]))"
},
{
"code": null,
"e": 2304,
"s": 2294,
"text": "[2, 5, 4]"
},
{
"code": null,
"e": 2306,
"s": 2304,
"text": "2"
}
] |
Java Exception Handling | Practice | GeeksforGeeks
|
Given two integers (positive , negative or even 0) say a and b. Find the minimum value of a$b where $ is any arithmetic operation like multiply(*), Divide(/), Addition(+),Substraction(-). Use Exception Handling in this problem.
Input:
The first line will contain an integer T (number of test cases). Each test case will contain two integers a and b.
Output:
Print the minimum value of a$b.
Constraints:
1 < = T < = 100
-103<=a,b<=103
Example:
Input:
2
5 -5
4 0
Output:
-25
0
EXPLANATION:
In test case 1: 5*(-5) = -25
In test case 2: 4*0 = 0
0
shakirmalik707861 week ago
// Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b. private int a,b; public TestClass(int a, int b) { this.a = a; this.b = b; } public void findMin() { try{ int []arr = new int[4]; arr[0] = a + b; arr[1] = a - b; arr[2] = a * b; arr[3] = a / b; int min = Math.min( Math.min(arr[0], arr[1]), Math.min(arr[2], arr[3])); System.out.println(min); } catch (Exception e) { System.out.println(0); } }
0
anas0shah03 weeks ago
class TestClass{ // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the private nt a; private int b; // Minimum value of a$b. TestClass(int a, int b){ this.a = a; this.b= b; } void findMin(){ try{ int sum=a+b; int diff=a-b; int mul=a*b; int div=a/b; int x = Math.min(Math.min(sum,diff),Math.min(mul,div)); System.out.println(x); }catch(Exception e) { System.out.println(0); } } }
0
debasishtewary51 month ago
private int a;private int b;
public TestClass(int a, int b) { // TODO Auto-generated constructor stub this.a=a; this.b=b;} public void findMin(){ int min=Math.min((a+b),(a-b)); int min1=Math.min((a*b),min); try{ int c= a/b; System.out.println(Math.min(c,min1)); } catch(Exception e){ System.out.println(min1); } }
+1
exponential6 months ago
private int a,b; public TestClass(int a,int b) { this.a=a; this.b=b; } public void findMin() { if(b==0) { System.out.println(a*b); } try{ int sum=a+b; int diff=a-b; int mul=a*b; int div=a/b; int x = Math.min(Math.min(sum,diff),Math.min(mul,div)); System.out.println(x); }catch(Exception e) { } }
0
Karandeep Singh8 months ago
Karandeep Singh
class TestClass{ // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b. int a; int b; TestClass(int p, int q) //constructor { a = p; b = q; } public void findMin() { int arr[] = new int[4]; arr[0] = a*b; arr[1] = a-b; arr[2] = a+b; try { arr[3]= a/b; } catch(Exception e) { System.out.print(""); } int min = arr[0]; for(int i=0; i<4;i++){ if(min>arr[i]) min = arr[i]; } System.out.println(min); }}
0
Amir Ansari1 year ago
Amir Ansari
Correct AnswerExecution Time:0.21
class TestClass{ // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b. private int a; private int b;
TestClass(int a, int b){ this.a = a; this.b = b; } public void findMin(){
int [] numArr = new int[4]; numArr[0] = a*b; numArr[1] = a-b; numArr[2] = a+b;
try{ numArr[3] = a/b; } catch(Exception e){ System.out.print(""); } int min = Integer.MAX_VALUE;
for(int i = 0; i < 4;i++){ min = Math.min(min,numArr[i]); } System.out.println(min);
}
}
0
Arunoday kumar2 years ago
Arunoday kumar
class TestClass{ int a; int b;
TestClass(int x,int y){ a = x; b = y; } public void findMin(){ int c[] = new int[4]; c[0] = (a*b);
c[1] = a+b; c[2] = a-b; try{ c[3] = a/b; } catch(Exception e){ System.out.print(""); }
int min = c[0]; for(int i= 0;i<4;i++){ if(min>c[i]) min = c[i]; }
System.out.println(min);
}// Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b.}
0
Sameer Anand2 years ago
Sameer Anand
int a; int b; TestClass(int p, int q) //constructor { a = p; b = q; } public void findMin() { int arr[] = new int[4]; arr[0] = a*b; arr[1] = a-b; arr[2] = a+b;
try { arr[3]= a/b; } catch(Exception e) { System.out.print("");
} int m = arr[0]; for (int i = 0; i < 4; i++) if(arr[i]<m) m="arr[i];" system.out.println(m);="" }="" }="">
0
Hitesh Yadav3 years ago
Hitesh Yadav
lass TestClass{ // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b.
int a,b,result=0,min=0; TestClass(int x, int y){ this.a=x; this.b=y; } void findMin(){ try{
result=a*b; min=result;
result=a/b; if(result<min) min="result;" result="a+b;" if(result<min)="" min="result;" result="a-b;" if(result<min)="" min="result;" }="" catch="" (arithmeticexception="" e="" ){}="" system.out.println(min);="" }="" }="">
0
Shubham Sharma3 years ago
Shubham Sharma
class TestClass{ int x,y; TestClass(int a,int b){ x=a; y=b; } public void findMin(){ int min; min=x+y; if((x*y)<min) {="" min="x*y;" }="" if((x-y)<min)="" {="" min="x-y;" }="" try{="" if((x="" y)<min){="" min="x/y;" }="" }="" catch(arithmeticexception="" e){="" system.out.print("");="" }="" system.out.println(min);="" }="" }="">
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": 454,
"s": 226,
"text": "Given two integers (positive , negative or even 0) say a and b. Find the minimum value of a$b where $ is any arithmetic operation like multiply(*), Divide(/), Addition(+),Substraction(-). Use Exception Handling in this problem."
},
{
"code": null,
"e": 577,
"s": 454,
"text": "Input: \nThe first line will contain an integer T (number of test cases). Each test case will contain two integers a and b."
},
{
"code": null,
"e": 618,
"s": 577,
"text": "Output: \nPrint the minimum value of a$b."
},
{
"code": null,
"e": 663,
"s": 618,
"text": "Constraints: \n1 < = T < = 100\n-103<=a,b<=103"
},
{
"code": null,
"e": 691,
"s": 663,
"text": "Example:\n Input:\n2\n5 -5\n4 0"
},
{
"code": null,
"e": 705,
"s": 691,
"text": "Output:\n-25\n0"
},
{
"code": null,
"e": 718,
"s": 705,
"text": "EXPLANATION:"
},
{
"code": null,
"e": 771,
"s": 718,
"text": "In test case 1: 5*(-5) = -25\nIn test case 2: 4*0 = 0"
},
{
"code": null,
"e": 773,
"s": 771,
"text": "0"
},
{
"code": null,
"e": 800,
"s": 773,
"text": "shakirmalik707861 week ago"
},
{
"code": null,
"e": 1459,
"s": 800,
"text": " // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b. private int a,b; public TestClass(int a, int b) { this.a = a; this.b = b; } public void findMin() { try{ int []arr = new int[4]; arr[0] = a + b; arr[1] = a - b; arr[2] = a * b; arr[3] = a / b; int min = Math.min( Math.min(arr[0], arr[1]), Math.min(arr[2], arr[3])); System.out.println(min); } catch (Exception e) { System.out.println(0); } } "
},
{
"code": null,
"e": 1461,
"s": 1459,
"text": "0"
},
{
"code": null,
"e": 1483,
"s": 1461,
"text": "anas0shah03 weeks ago"
},
{
"code": null,
"e": 2095,
"s": 1483,
"text": "class TestClass{ // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the private nt a; private int b; // Minimum value of a$b. TestClass(int a, int b){ this.a = a; this.b= b; } void findMin(){ try{ int sum=a+b; int diff=a-b; int mul=a*b; int div=a/b; int x = Math.min(Math.min(sum,diff),Math.min(mul,div)); System.out.println(x); }catch(Exception e) { System.out.println(0); } } }"
},
{
"code": null,
"e": 2097,
"s": 2095,
"text": "0"
},
{
"code": null,
"e": 2124,
"s": 2097,
"text": "debasishtewary51 month ago"
},
{
"code": null,
"e": 2154,
"s": 2124,
"text": " private int a;private int b;"
},
{
"code": null,
"e": 2513,
"s": 2154,
"text": "public TestClass(int a, int b) { // TODO Auto-generated constructor stub this.a=a; this.b=b;} public void findMin(){ int min=Math.min((a+b),(a-b)); int min1=Math.min((a*b),min); try{ int c= a/b; System.out.println(Math.min(c,min1)); } catch(Exception e){ System.out.println(min1); } }"
},
{
"code": null,
"e": 2516,
"s": 2513,
"text": "+1"
},
{
"code": null,
"e": 2540,
"s": 2516,
"text": "exponential6 months ago"
},
{
"code": null,
"e": 2991,
"s": 2540,
"text": "private int a,b; public TestClass(int a,int b) { this.a=a; this.b=b; } public void findMin() { if(b==0) { System.out.println(a*b); } try{ int sum=a+b; int diff=a-b; int mul=a*b; int div=a/b; int x = Math.min(Math.min(sum,diff),Math.min(mul,div)); System.out.println(x); }catch(Exception e) { } }"
},
{
"code": null,
"e": 2993,
"s": 2991,
"text": "0"
},
{
"code": null,
"e": 3021,
"s": 2993,
"text": "Karandeep Singh8 months ago"
},
{
"code": null,
"e": 3037,
"s": 3021,
"text": "Karandeep Singh"
},
{
"code": null,
"e": 3726,
"s": 3037,
"text": "class TestClass{ // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b. int a; int b; TestClass(int p, int q) //constructor { a = p; b = q; } public void findMin() { int arr[] = new int[4]; arr[0] = a*b; arr[1] = a-b; arr[2] = a+b; try { arr[3]= a/b; } catch(Exception e) { System.out.print(\"\"); } int min = arr[0]; for(int i=0; i<4;i++){ if(min>arr[i]) min = arr[i]; } System.out.println(min); }}"
},
{
"code": null,
"e": 3728,
"s": 3726,
"text": "0"
},
{
"code": null,
"e": 3750,
"s": 3728,
"text": "Amir Ansari1 year ago"
},
{
"code": null,
"e": 3762,
"s": 3750,
"text": "Amir Ansari"
},
{
"code": null,
"e": 3796,
"s": 3762,
"text": "Correct AnswerExecution Time:0.21"
},
{
"code": null,
"e": 4036,
"s": 3796,
"text": "class TestClass{ // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b. private int a; private int b;"
},
{
"code": null,
"e": 4139,
"s": 4036,
"text": " TestClass(int a, int b){ this.a = a; this.b = b; } public void findMin(){"
},
{
"code": null,
"e": 4251,
"s": 4139,
"text": " int [] numArr = new int[4]; numArr[0] = a*b; numArr[1] = a-b; numArr[2] = a+b;"
},
{
"code": null,
"e": 4406,
"s": 4251,
"text": " try{ numArr[3] = a/b; } catch(Exception e){ System.out.print(\"\"); } int min = Integer.MAX_VALUE;"
},
{
"code": null,
"e": 4533,
"s": 4406,
"text": " for(int i = 0; i < 4;i++){ min = Math.min(min,numArr[i]); } System.out.println(min);"
},
{
"code": null,
"e": 4540,
"s": 4533,
"text": " }"
},
{
"code": null,
"e": 4542,
"s": 4540,
"text": "}"
},
{
"code": null,
"e": 4544,
"s": 4542,
"text": "0"
},
{
"code": null,
"e": 4570,
"s": 4544,
"text": "Arunoday kumar2 years ago"
},
{
"code": null,
"e": 4585,
"s": 4570,
"text": "Arunoday kumar"
},
{
"code": null,
"e": 4622,
"s": 4585,
"text": "class TestClass{ int a; int b;"
},
{
"code": null,
"e": 4760,
"s": 4622,
"text": " TestClass(int x,int y){ a = x; b = y; } public void findMin(){ int c[] = new int[4]; c[0] = (a*b);"
},
{
"code": null,
"e": 4909,
"s": 4760,
"text": " c[1] = a+b; c[2] = a-b; try{ c[3] = a/b; } catch(Exception e){ System.out.print(\"\"); }"
},
{
"code": null,
"e": 5019,
"s": 4909,
"text": " int min = c[0]; for(int i= 0;i<4;i++){ if(min>c[i]) min = c[i]; }"
},
{
"code": null,
"e": 5052,
"s": 5019,
"text": " System.out.println(min);"
},
{
"code": null,
"e": 5242,
"s": 5052,
"text": " }// Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b.}"
},
{
"code": null,
"e": 5244,
"s": 5242,
"text": "0"
},
{
"code": null,
"e": 5268,
"s": 5244,
"text": "Sameer Anand2 years ago"
},
{
"code": null,
"e": 5281,
"s": 5268,
"text": "Sameer Anand"
},
{
"code": null,
"e": 5493,
"s": 5281,
"text": "int a; int b; TestClass(int p, int q) //constructor { a = p; b = q; } public void findMin() { int arr[] = new int[4]; arr[0] = a*b; arr[1] = a-b; arr[2] = a+b;"
},
{
"code": null,
"e": 5583,
"s": 5493,
"text": " try { arr[3]= a/b; } catch(Exception e) { System.out.print(\"\");"
},
{
"code": null,
"e": 5707,
"s": 5583,
"text": " } int m = arr[0]; for (int i = 0; i < 4; i++) if(arr[i]<m) m=\"arr[i];\" system.out.println(m);=\"\" }=\"\" }=\"\">"
},
{
"code": null,
"e": 5709,
"s": 5707,
"text": "0"
},
{
"code": null,
"e": 5733,
"s": 5709,
"text": "Hitesh Yadav3 years ago"
},
{
"code": null,
"e": 5746,
"s": 5733,
"text": "Hitesh Yadav"
},
{
"code": null,
"e": 5949,
"s": 5746,
"text": "lass TestClass{ // Add your code here. Define private variables, Constructors to initialize // variables with the given values and a method findMin() which prints the // Minimum value of a$b."
},
{
"code": null,
"e": 6071,
"s": 5949,
"text": " int a,b,result=0,min=0; TestClass(int x, int y){ this.a=x; this.b=y; } void findMin(){ try{"
},
{
"code": null,
"e": 6110,
"s": 6071,
"text": " result=a*b; min=result;"
},
{
"code": null,
"e": 6347,
"s": 6110,
"text": " result=a/b; if(result<min) min=\"result;\" result=\"a+b;\" if(result<min)=\"\" min=\"result;\" result=\"a-b;\" if(result<min)=\"\" min=\"result;\" }=\"\" catch=\"\" (arithmeticexception=\"\" e=\"\" ){}=\"\" system.out.println(min);=\"\" }=\"\" }=\"\">"
},
{
"code": null,
"e": 6349,
"s": 6347,
"text": "0"
},
{
"code": null,
"e": 6375,
"s": 6349,
"text": "Shubham Sharma3 years ago"
},
{
"code": null,
"e": 6390,
"s": 6375,
"text": "Shubham Sharma"
},
{
"code": null,
"e": 6768,
"s": 6390,
"text": "class TestClass{ int x,y; TestClass(int a,int b){ x=a; y=b; } public void findMin(){ int min; min=x+y; if((x*y)<min) {=\"\" min=\"x*y;\" }=\"\" if((x-y)<min)=\"\" {=\"\" min=\"x-y;\" }=\"\" try{=\"\" if((x=\"\" y)<min){=\"\" min=\"x/y;\" }=\"\" }=\"\" catch(arithmeticexception=\"\" e){=\"\" system.out.print(\"\");=\"\" }=\"\" system.out.println(min);=\"\" }=\"\" }=\"\">"
},
{
"code": null,
"e": 6914,
"s": 6768,
"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": 6950,
"s": 6914,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6960,
"s": 6950,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6970,
"s": 6960,
"text": "\nContest\n"
},
{
"code": null,
"e": 7033,
"s": 6970,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7181,
"s": 7033,
"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": 7389,
"s": 7181,
"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": 7495,
"s": 7389,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Flask form submission without Page Reload - GeeksforGeeks
|
17 Jun, 2021
There are many modules or frameworks which allows to build your webpage using python like bottle, django, flask etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you the versatility to program with.
Problem:
If we do post request then the whole page will reload. So this article revolves around how to send the form data to flask backend without reloading the page. For submitting form without reloading page we use jquery and ajax. So before using flask we have to install that
Ubuntu
pip3 install flask
Create new directory for your project. Inside that create new file and name it as app.py
app.py
Python3
from flask import Flask,render_template,request app = Flask(__name__) @app.route("/",methods=["POST","GET"])def home(): if request.method == "POST": todo = request.form.get("todo") print(todo) return render_template('home.html') if __name__ == '__main__': app.run(debug=True)
Then create new directory and name it as templates
Inside that create new file and name it as home.html
home.html
HTML
<!DOCTYPE html><html><head> <title>GFG</title></head><body> <form method="post" id="todo-form"> <input type="text" name="todo" id="todo"> <button type="submit">submit</button> </form> <!--Jquery Cdn --> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).on('submit','#todo-form',function(e) { console.log('hello'); e.preventDefault(); $.ajax({ type:'POST', url:'/', data:{ todo:$("#todo").val() }, success:function() { alert('saved'); } }) }); </script> </body></html>
e.preventDefault() :- This function doesn’t reload the page
type: GET or POST request
url : url that we have specify in our flask app
data : Form data that we want to pass
Succes: function() :- This function run after successfully submitting the values and when there are no error occur while submitting the data.
OUTPUT :-
On the cmd or terminal it will print the value we have submitted using form.
ruhelaa48
Python Flask
Python Framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24317,
"s": 24289,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 24581,
"s": 24317,
"text": "There are many modules or frameworks which allows to build your webpage using python like bottle, django, flask etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you the versatility to program with."
},
{
"code": null,
"e": 24590,
"s": 24581,
"text": "Problem:"
},
{
"code": null,
"e": 24862,
"s": 24590,
"text": "If we do post request then the whole page will reload. So this article revolves around how to send the form data to flask backend without reloading the page. For submitting form without reloading page we use jquery and ajax. So before using flask we have to install that"
},
{
"code": null,
"e": 24869,
"s": 24862,
"text": "Ubuntu"
},
{
"code": null,
"e": 24888,
"s": 24869,
"text": "pip3 install flask"
},
{
"code": null,
"e": 24977,
"s": 24888,
"text": "Create new directory for your project. Inside that create new file and name it as app.py"
},
{
"code": null,
"e": 24984,
"s": 24977,
"text": "app.py"
},
{
"code": null,
"e": 24992,
"s": 24984,
"text": "Python3"
},
{
"code": "from flask import Flask,render_template,request app = Flask(__name__) @app.route(\"/\",methods=[\"POST\",\"GET\"])def home(): if request.method == \"POST\": todo = request.form.get(\"todo\") print(todo) return render_template('home.html') if __name__ == '__main__': app.run(debug=True) ",
"e": 25297,
"s": 24992,
"text": null
},
{
"code": null,
"e": 25348,
"s": 25297,
"text": "Then create new directory and name it as templates"
},
{
"code": null,
"e": 25401,
"s": 25348,
"text": "Inside that create new file and name it as home.html"
},
{
"code": null,
"e": 25411,
"s": 25401,
"text": "home.html"
},
{
"code": null,
"e": 25416,
"s": 25411,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>GFG</title></head><body> <form method=\"post\" id=\"todo-form\"> <input type=\"text\" name=\"todo\" id=\"todo\"> <button type=\"submit\">submit</button> </form> <!--Jquery Cdn --> <script src=\"https://code.jquery.com/jquery-3.5.1.js\" integrity=\"sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=\" crossorigin=\"anonymous\"></script> <script type=\"text/javascript\"> $(document).on('submit','#todo-form',function(e) { console.log('hello'); e.preventDefault(); $.ajax({ type:'POST', url:'/', data:{ todo:$(\"#todo\").val() }, success:function() { alert('saved'); } }) }); </script> </body></html>",
"e": 26192,
"s": 25416,
"text": null
},
{
"code": null,
"e": 26256,
"s": 26195,
"text": "e.preventDefault() :- This function doesn’t reload the page"
},
{
"code": null,
"e": 26282,
"s": 26256,
"text": "type: GET or POST request"
},
{
"code": null,
"e": 26330,
"s": 26282,
"text": "url : url that we have specify in our flask app"
},
{
"code": null,
"e": 26368,
"s": 26330,
"text": "data : Form data that we want to pass"
},
{
"code": null,
"e": 26510,
"s": 26368,
"text": "Succes: function() :- This function run after successfully submitting the values and when there are no error occur while submitting the data."
},
{
"code": null,
"e": 26522,
"s": 26512,
"text": "OUTPUT :-"
},
{
"code": null,
"e": 26605,
"s": 26528,
"text": "On the cmd or terminal it will print the value we have submitted using form."
},
{
"code": null,
"e": 26617,
"s": 26607,
"text": "ruhelaa48"
},
{
"code": null,
"e": 26630,
"s": 26617,
"text": "Python Flask"
},
{
"code": null,
"e": 26647,
"s": 26630,
"text": "Python Framework"
},
{
"code": null,
"e": 26654,
"s": 26647,
"text": "Python"
},
{
"code": null,
"e": 26752,
"s": 26654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26784,
"s": 26752,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26840,
"s": 26784,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26882,
"s": 26840,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26924,
"s": 26882,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26946,
"s": 26924,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26977,
"s": 26946,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27016,
"s": 26977,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27071,
"s": 27016,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27100,
"s": 27071,
"text": "Create a directory in Python"
}
] |
\scriptsize - Tex Command
|
\scriptsize - Used to turn on script size.
{ \scriptsize ... }
\scriptsize command is used to turn on script size.
\rm \scriptsize script \normalsize normal \large large
scriptnormallarge
\rm \scriptsize script \normalsize normal \large large
scriptnormallarge
\rm \scriptsize script \normalsize normal \large large
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8029,
"s": 7986,
"text": "\\scriptsize - Used to turn on script size."
},
{
"code": null,
"e": 8049,
"s": 8029,
"text": "{ \\scriptsize ... }"
},
{
"code": null,
"e": 8101,
"s": 8049,
"text": "\\scriptsize command is used to turn on script size."
},
{
"code": null,
"e": 8179,
"s": 8101,
"text": "\n\\rm \\scriptsize script \\normalsize normal \\large large\n\nscriptnormallarge\n\n\n"
},
{
"code": null,
"e": 8255,
"s": 8179,
"text": "\\rm \\scriptsize script \\normalsize normal \\large large\n\nscriptnormallarge\n\n"
},
{
"code": null,
"e": 8310,
"s": 8255,
"text": "\\rm \\scriptsize script \\normalsize normal \\large large"
},
{
"code": null,
"e": 8342,
"s": 8310,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8355,
"s": 8342,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8388,
"s": 8355,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8401,
"s": 8388,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8433,
"s": 8401,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8469,
"s": 8433,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8504,
"s": 8469,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8521,
"s": 8504,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8554,
"s": 8521,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8568,
"s": 8554,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8600,
"s": 8568,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8615,
"s": 8600,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8622,
"s": 8615,
"text": " Print"
},
{
"code": null,
"e": 8633,
"s": 8622,
"text": " Add Notes"
}
] |
Python - SFTP
|
SFTP is also known as the SSH File Transfer Protocol. It is a network protocol that provides file access, file transfer, and file management over any reliable data stream. The program is run over a secure channel, such as SSH, that the server has already authenticated the client, and that the identity of the client user is available to the protocol.
The pysftp module is a simple interface to SFTP. The module offers high level abstractions and task based routines to handle the SFTP needs. So we install the module into our python environment with the below command.
pip install pysftp
In the below example we login to a remote server using sftp and then get and put some file in that directory.
import pysftp
with pysftp.Connection('hostname', username='me', password='secret') as sftp:
with sftp.cd('/allcode'): # temporarily chdir to allcode
sftp.put('/pycode/filename') # upload file to allcode/pycode on remote
sftp.get('remote_file') # get a remote file
When we run the above code we are able to see the list of files present in the allcode directory and also put and get some file in that directory.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2678,
"s": 2326,
"text": "SFTP is also known as the SSH File Transfer Protocol. It is a network protocol that provides file access, file transfer, and file management over any reliable data stream. The program is run over a secure channel, such as SSH, that the server has already authenticated the client, and that the identity of the client user is available to the protocol."
},
{
"code": null,
"e": 2896,
"s": 2678,
"text": "The pysftp module is a simple interface to SFTP. The module offers high level abstractions and task based routines to handle the SFTP needs. So we install the module into our python environment with the below command."
},
{
"code": null,
"e": 2915,
"s": 2896,
"text": "pip install pysftp"
},
{
"code": null,
"e": 3025,
"s": 2915,
"text": "In the below example we login to a remote server using sftp and then get and put some file in that directory."
},
{
"code": null,
"e": 3333,
"s": 3025,
"text": "\nimport pysftp\n\nwith pysftp.Connection('hostname', username='me', password='secret') as sftp:\n\n with sftp.cd('/allcode'): # temporarily chdir to allcode\n sftp.put('/pycode/filename') \t# upload file to allcode/pycode on remote\n sftp.get('remote_file') # get a remote file\n"
},
{
"code": null,
"e": 3480,
"s": 3333,
"text": "When we run the above code we are able to see the list of files present in the allcode directory and also put and get some file in that directory."
},
{
"code": null,
"e": 3517,
"s": 3480,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3533,
"s": 3517,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3566,
"s": 3533,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3585,
"s": 3566,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3620,
"s": 3585,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3642,
"s": 3620,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3676,
"s": 3642,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3704,
"s": 3676,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3739,
"s": 3704,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3753,
"s": 3739,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3786,
"s": 3753,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3803,
"s": 3786,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3810,
"s": 3803,
"text": " Print"
},
{
"code": null,
"e": 3821,
"s": 3810,
"text": " Add Notes"
}
] |
Find the summation of the product of Array elements in range [L, R] - GeeksforGeeks
|
02 Mar, 2022
Given an array arr[] and two integers L and R. The task is to find the sum of the product of all the pairs (i, j) in the range [L, R], such that i ≤ j.
Input: arr[] = { 1, 3, 5, 8 }, L = 0, R = 2Output: 58Explanation: As 1*1 + 1*3 + 1*5 + 3*3 + 3*5 + 5*5 = 58
Input: arr[] = { 2, 1, 4, 5, 3, 2, 1 }, L = 1, R = 5Output: 140
Naive Approach: The brute force approach can be directly implemented by multiplying the indices using two nested loops and storing the sum in a variable.
Below is the implementation of the above approach:
C++
Java
Python
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the sum// of (arr[i]*arr[j]) for all i and j// between the index L and Rint sum_of_products(int arr[], int N, int L, int R){ int sum = 0; for (int i = L; i <= R; i++) { for (int j = i; j <= R; j++) { sum += arr[i] * arr[j]; } } return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 5, 8 }; int N = sizeof(arr) / sizeof(arr[0]); int L = 0; int R = 2; cout << sum_of_products(arr, N, L, R); return 0;}
// Java implementation of the above approachimport java.util.*;public class GFG { // Function to return the sum // of (arr[i]*arr[j]) for all i and j // between the index L and R static int sum_of_products(int[] arr, int N, int L, int R) { int sum = 0; for (int i = L; i <= R; i++) { for (int j = i; j <= R; j++) { sum += arr[i] * arr[j]; } } return sum; } // Driver code public static void main(String args[]) { int[] arr = { 1, 3, 5, 8 }; int N = arr.length; int L = 0; int R = 2; System.out.println(sum_of_products(arr, N, L, R)); }} // This code is contributed by Samim Hossain Mondal.
# C++ implementation of the above approach # Function to return the sum# of (arr[i]*arr[j]) for all i and j# between the index L and Rdef sum_of_products(arr, N, L, R): sum = 0 for i in range(L, R + 1): for j in range(i, R + 1): sum = sum + (arr[i] * arr[j]) return sum # Driver codearr = [ 1, 3, 5, 8 ]N = len(arr)L = 0R = 2print(sum_of_products(arr, N, L, R)) # This code is contributed by Samim Hossain Mondal.
// C# implementation of the above approachusing System;class GFG { // Function to return the sum // of (arr[i]*arr[j]) for all i and j // between the index L and R static int sum_of_products(int[] arr, int N, int L, int R) { int sum = 0; for (int i = L; i <= R; i++) { for (int j = i; j <= R; j++) { sum += arr[i] * arr[j]; } } return sum; } // Driver code public static void Main() { int[] arr = { 1, 3, 5, 8 }; int N = arr.Length; int L = 0; int R = 2; Console.WriteLine(sum_of_products(arr, N, L, R)); }} // This code is contributed by ukasp.
<script> // JavaScript code for the above approach // Function to return the sum // of (arr[i]*arr[j]) for all i and j // between the index L and R function sum_of_products(arr, N, L, R) { let sum = 0; for (let i = L; i <= R; i++) { for (let j = i; j <= R; j++) { sum += arr[i] * arr[j]; } } return sum; } // Driver code let arr = [1, 3, 5, 8]; let N = arr.length let L = 0; let R = 2; document.write(sum_of_products(arr, N, L, R)); // This code is contributed by Potta Lokesh </script>
58
Time complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: This problem can be efficiently solved by using the Prefix sum technique. In this method, store the prefix sum in pre-calculation and then iterate a single loop from L to R and multiply the corresponding prefix sum from that index to the last index.
Basically 1*1+1*3+1*5+3*3+3*5+5*5 can be written as 1*(1+3+5)+3*(3+5)+5*(5) = 1*(prefix_sum from 1 to 5)+3*(prefix_sum from 3 to 5)+5*(prefix sum from 5 to 5)
Below is the implementation of the above approach.
C++
Java
C#
Javascript
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of// (arr[i]*arr[j]) for all i and j// between the index L and Rint sum_of_products(int arr[], int n, int L, int R){ int sum = 0; // Pre-calculating Prefix sum int prefix_sum[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + arr[i]; } // Using prefix sum to find // summation of products for (int i = L; i <= R; i++) { // if-else for i==0 case // in prefix sum if (i != 0) sum += arr[i] * (prefix_sum[R] - prefix_sum[i - 1]); else sum += arr[i] * (prefix_sum[R]); } return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 5, 8 }; int N = sizeof(arr) / sizeof(arr[0]); int L = 0; int R = 2; cout << sum_of_products(arr, N, L, R); return 0;}
// Java code to implement above approachimport java.util.*;class GFG{ // Function to return the sum of // (arr[i]*arr[j]) for all i and j // between the index L and R static int sum_of_products(int arr[], int n, int L, int R) { int sum = 0; // Pre-calculating Prefix sum int []prefix_sum = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + arr[i]; } // Using prefix sum to find // summation of products for (int i = L; i <= R; i++) { // if-else for i==0 case // in prefix sum if (i != 0) sum += arr[i] * (prefix_sum[R] - prefix_sum[i - 1]); else sum += arr[i] * (prefix_sum[R]); } return sum; } // Driver code public static void main(String[] args) { int arr[] = { 1, 3, 5, 8 }; int N = arr.length; int L = 0; int R = 2; System.out.print(sum_of_products(arr, N, L, R)); }} // This code is contributed by shikhasingrajput
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the sum of // (arr[i]*arr[j]) for all i and j // between the index L and R static int sum_of_products(int[] arr, int n, int L, int R) { int sum = 0; // Pre-calculating Prefix sum int []prefix_sum = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + arr[i]; } // Using prefix sum to find // summation of products for (int i = L; i <= R; i++) { // if-else for i==0 case // in prefix sum if (i != 0) sum += arr[i] * (prefix_sum[R] - prefix_sum[i - 1]); else sum += arr[i] * (prefix_sum[R]); } return sum; } // Driver Code public static void Main() { int[] arr = { 1, 3, 5, 8 }; int N = arr.Length; int L = 0; int R = 2; Console.Write(sum_of_products(arr, N, L, R)); }} // This code is contributed by ukasp.
<script>// javascript code to implement above approach // Function to return the sum of // (arr[i]*arr[j]) for all i and j // between the index L and R function sum_of_products(arr , n , L , R) { var sum = 0; // Pre-calculating Prefix sum var prefix_sum = Array(n).fill(0); prefix_sum[0] = arr[0]; for (i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + arr[i]; } // Using prefix sum to find // summation of products for (i = L; i <= R; i++) { // if-else for i==0 case // in prefix sum if (i != 0) sum += arr[i] * (prefix_sum[R] - prefix_sum[i - 1]); else sum += arr[i] * (prefix_sum[R]); } return sum; } // Driver code var arr = [ 1, 3, 5, 8 ]; var N = arr.length; var L = 0; var R = 2; document.write(sum_of_products(arr, N, L, R)); // This code is contributed by umadevi9616</script>
58
Time complexity: O(N)Auxiliary Space: O(N)
lokeshpotta20
ukasp
samim2000
shikhasingrajput
sanjoy_62
umadevi9616
Algo-Geek 2021
array-range-queries
prefix-sum
Algo Geek
Arrays
Greedy
Mathematical
prefix-sum
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Split Array into subarrays of size K by filling elements
Program to find simple moving average | Set-2
Divide given number into two even parts
Check if the given string is valid English word or not
Minimize cost to sort given array by sorting unsorted subarrays
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
|
[
{
"code": null,
"e": 26029,
"s": 26001,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 26181,
"s": 26029,
"text": "Given an array arr[] and two integers L and R. The task is to find the sum of the product of all the pairs (i, j) in the range [L, R], such that i ≤ j."
},
{
"code": null,
"e": 26289,
"s": 26181,
"text": "Input: arr[] = { 1, 3, 5, 8 }, L = 0, R = 2Output: 58Explanation: As 1*1 + 1*3 + 1*5 + 3*3 + 3*5 + 5*5 = 58"
},
{
"code": null,
"e": 26353,
"s": 26289,
"text": "Input: arr[] = { 2, 1, 4, 5, 3, 2, 1 }, L = 1, R = 5Output: 140"
},
{
"code": null,
"e": 26507,
"s": 26353,
"text": "Naive Approach: The brute force approach can be directly implemented by multiplying the indices using two nested loops and storing the sum in a variable."
},
{
"code": null,
"e": 26558,
"s": 26507,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26562,
"s": 26558,
"text": "C++"
},
{
"code": null,
"e": 26567,
"s": 26562,
"text": "Java"
},
{
"code": null,
"e": 26574,
"s": 26567,
"text": "Python"
},
{
"code": null,
"e": 26577,
"s": 26574,
"text": "C#"
},
{
"code": null,
"e": 26588,
"s": 26577,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the sum// of (arr[i]*arr[j]) for all i and j// between the index L and Rint sum_of_products(int arr[], int N, int L, int R){ int sum = 0; for (int i = L; i <= R; i++) { for (int j = i; j <= R; j++) { sum += arr[i] * arr[j]; } } return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 5, 8 }; int N = sizeof(arr) / sizeof(arr[0]); int L = 0; int R = 2; cout << sum_of_products(arr, N, L, R); return 0;}",
"e": 27178,
"s": 26588,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*;public class GFG { // Function to return the sum // of (arr[i]*arr[j]) for all i and j // between the index L and R static int sum_of_products(int[] arr, int N, int L, int R) { int sum = 0; for (int i = L; i <= R; i++) { for (int j = i; j <= R; j++) { sum += arr[i] * arr[j]; } } return sum; } // Driver code public static void main(String args[]) { int[] arr = { 1, 3, 5, 8 }; int N = arr.length; int L = 0; int R = 2; System.out.println(sum_of_products(arr, N, L, R)); }} // This code is contributed by Samim Hossain Mondal.",
"e": 27853,
"s": 27178,
"text": null
},
{
"code": "# C++ implementation of the above approach # Function to return the sum# of (arr[i]*arr[j]) for all i and j# between the index L and Rdef sum_of_products(arr, N, L, R): sum = 0 for i in range(L, R + 1): for j in range(i, R + 1): sum = sum + (arr[i] * arr[j]) return sum # Driver codearr = [ 1, 3, 5, 8 ]N = len(arr)L = 0R = 2print(sum_of_products(arr, N, L, R)) # This code is contributed by Samim Hossain Mondal.",
"e": 28296,
"s": 27853,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;class GFG { // Function to return the sum // of (arr[i]*arr[j]) for all i and j // between the index L and R static int sum_of_products(int[] arr, int N, int L, int R) { int sum = 0; for (int i = L; i <= R; i++) { for (int j = i; j <= R; j++) { sum += arr[i] * arr[j]; } } return sum; } // Driver code public static void Main() { int[] arr = { 1, 3, 5, 8 }; int N = arr.Length; int L = 0; int R = 2; Console.WriteLine(sum_of_products(arr, N, L, R)); }} // This code is contributed by ukasp.",
"e": 28927,
"s": 28296,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to return the sum // of (arr[i]*arr[j]) for all i and j // between the index L and R function sum_of_products(arr, N, L, R) { let sum = 0; for (let i = L; i <= R; i++) { for (let j = i; j <= R; j++) { sum += arr[i] * arr[j]; } } return sum; } // Driver code let arr = [1, 3, 5, 8]; let N = arr.length let L = 0; let R = 2; document.write(sum_of_products(arr, N, L, R)); // This code is contributed by Potta Lokesh </script>",
"e": 29588,
"s": 28927,
"text": null
},
{
"code": null,
"e": 29594,
"s": 29591,
"text": "58"
},
{
"code": null,
"e": 29640,
"s": 29596,
"text": "Time complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29913,
"s": 29642,
"text": "Efficient Approach: This problem can be efficiently solved by using the Prefix sum technique. In this method, store the prefix sum in pre-calculation and then iterate a single loop from L to R and multiply the corresponding prefix sum from that index to the last index. "
},
{
"code": null,
"e": 30072,
"s": 29913,
"text": "Basically 1*1+1*3+1*5+3*3+3*5+5*5 can be written as 1*(1+3+5)+3*(3+5)+5*(5) = 1*(prefix_sum from 1 to 5)+3*(prefix_sum from 3 to 5)+5*(prefix sum from 5 to 5)"
},
{
"code": null,
"e": 30127,
"s": 30076,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 30133,
"s": 30129,
"text": "C++"
},
{
"code": null,
"e": 30138,
"s": 30133,
"text": "Java"
},
{
"code": null,
"e": 30141,
"s": 30138,
"text": "C#"
},
{
"code": null,
"e": 30152,
"s": 30141,
"text": "Javascript"
},
{
"code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of// (arr[i]*arr[j]) for all i and j// between the index L and Rint sum_of_products(int arr[], int n, int L, int R){ int sum = 0; // Pre-calculating Prefix sum int prefix_sum[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + arr[i]; } // Using prefix sum to find // summation of products for (int i = L; i <= R; i++) { // if-else for i==0 case // in prefix sum if (i != 0) sum += arr[i] * (prefix_sum[R] - prefix_sum[i - 1]); else sum += arr[i] * (prefix_sum[R]); } return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 5, 8 }; int N = sizeof(arr) / sizeof(arr[0]); int L = 0; int R = 2; cout << sum_of_products(arr, N, L, R); return 0;}",
"e": 31143,
"s": 30152,
"text": null
},
{
"code": "// Java code to implement above approachimport java.util.*;class GFG{ // Function to return the sum of // (arr[i]*arr[j]) for all i and j // between the index L and R static int sum_of_products(int arr[], int n, int L, int R) { int sum = 0; // Pre-calculating Prefix sum int []prefix_sum = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + arr[i]; } // Using prefix sum to find // summation of products for (int i = L; i <= R; i++) { // if-else for i==0 case // in prefix sum if (i != 0) sum += arr[i] * (prefix_sum[R] - prefix_sum[i - 1]); else sum += arr[i] * (prefix_sum[R]); } return sum; } // Driver code public static void main(String[] args) { int arr[] = { 1, 3, 5, 8 }; int N = arr.length; int L = 0; int R = 2; System.out.print(sum_of_products(arr, N, L, R)); }} // This code is contributed by shikhasingrajput",
"e": 32170,
"s": 31143,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the sum of // (arr[i]*arr[j]) for all i and j // between the index L and R static int sum_of_products(int[] arr, int n, int L, int R) { int sum = 0; // Pre-calculating Prefix sum int []prefix_sum = new int[n]; prefix_sum[0] = arr[0]; for (int i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + arr[i]; } // Using prefix sum to find // summation of products for (int i = L; i <= R; i++) { // if-else for i==0 case // in prefix sum if (i != 0) sum += arr[i] * (prefix_sum[R] - prefix_sum[i - 1]); else sum += arr[i] * (prefix_sum[R]); } return sum; } // Driver Code public static void Main() { int[] arr = { 1, 3, 5, 8 }; int N = arr.Length; int L = 0; int R = 2; Console.Write(sum_of_products(arr, N, L, R)); }} // This code is contributed by ukasp.",
"e": 33195,
"s": 32170,
"text": null
},
{
"code": "<script>// javascript code to implement above approach // Function to return the sum of // (arr[i]*arr[j]) for all i and j // between the index L and R function sum_of_products(arr , n , L , R) { var sum = 0; // Pre-calculating Prefix sum var prefix_sum = Array(n).fill(0); prefix_sum[0] = arr[0]; for (i = 1; i < n; i++) { prefix_sum[i] = prefix_sum[i - 1] + arr[i]; } // Using prefix sum to find // summation of products for (i = L; i <= R; i++) { // if-else for i==0 case // in prefix sum if (i != 0) sum += arr[i] * (prefix_sum[R] - prefix_sum[i - 1]); else sum += arr[i] * (prefix_sum[R]); } return sum; } // Driver code var arr = [ 1, 3, 5, 8 ]; var N = arr.length; var L = 0; var R = 2; document.write(sum_of_products(arr, N, L, R)); // This code is contributed by umadevi9616</script>",
"e": 34208,
"s": 33195,
"text": null
},
{
"code": null,
"e": 34214,
"s": 34211,
"text": "58"
},
{
"code": null,
"e": 34258,
"s": 34214,
"text": "Time complexity: O(N)Auxiliary Space: O(N) "
},
{
"code": null,
"e": 34272,
"s": 34258,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 34278,
"s": 34272,
"text": "ukasp"
},
{
"code": null,
"e": 34288,
"s": 34278,
"text": "samim2000"
},
{
"code": null,
"e": 34305,
"s": 34288,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 34315,
"s": 34305,
"text": "sanjoy_62"
},
{
"code": null,
"e": 34327,
"s": 34315,
"text": "umadevi9616"
},
{
"code": null,
"e": 34342,
"s": 34327,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 34362,
"s": 34342,
"text": "array-range-queries"
},
{
"code": null,
"e": 34373,
"s": 34362,
"text": "prefix-sum"
},
{
"code": null,
"e": 34383,
"s": 34373,
"text": "Algo Geek"
},
{
"code": null,
"e": 34390,
"s": 34383,
"text": "Arrays"
},
{
"code": null,
"e": 34397,
"s": 34390,
"text": "Greedy"
},
{
"code": null,
"e": 34410,
"s": 34397,
"text": "Mathematical"
},
{
"code": null,
"e": 34421,
"s": 34410,
"text": "prefix-sum"
},
{
"code": null,
"e": 34428,
"s": 34421,
"text": "Arrays"
},
{
"code": null,
"e": 34435,
"s": 34428,
"text": "Greedy"
},
{
"code": null,
"e": 34448,
"s": 34435,
"text": "Mathematical"
},
{
"code": null,
"e": 34546,
"s": 34448,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34555,
"s": 34546,
"text": "Comments"
},
{
"code": null,
"e": 34568,
"s": 34555,
"text": "Old Comments"
},
{
"code": null,
"e": 34625,
"s": 34568,
"text": "Split Array into subarrays of size K by filling elements"
},
{
"code": null,
"e": 34671,
"s": 34625,
"text": "Program to find simple moving average | Set-2"
},
{
"code": null,
"e": 34711,
"s": 34671,
"text": "Divide given number into two even parts"
},
{
"code": null,
"e": 34766,
"s": 34711,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 34830,
"s": 34766,
"text": "Minimize cost to sort given array by sorting unsorted subarrays"
},
{
"code": null,
"e": 34845,
"s": 34830,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34861,
"s": 34845,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34888,
"s": 34861,
"text": "Program for array rotation"
},
{
"code": null,
"e": 34936,
"s": 34888,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
KMeans Hyper-parameters Explained with Examples | by Sujeewa Kumaratunga PhD | Towards Data Science
|
These days anyone with a high school degree can implement a Machine Learning algorithm and that’s a good thing. It is always a good thing when things are accessible to most people. A lot of common libraries are available out there that simplifies the algorithm part. But with great power comes great responsibility. The time freed up writing libraries from scratch should be used to fine tune your model so you get decent results.
Today we’ll look at the tuning of the Scikit KMeans model. KMeans is a widely used algorithm to cluster data: you want to cluster your large number of customers in to similar groups based on their purchase behavior, you would use KMeans. You want to cluster all Canadians based on their demographics and interests, you would use KMeans. You want to cluster plants or wine based on their characteristics, you could use KMeans. All of these problems require unsupervised clustering, that is we do not know what the clusters will look like, a priori. There are other methods for unsupervised clustering, such as DBScan, Hierarchical clustering etc and they each have their merits, but in this post I will address KMeans since it is a computationally light clustering method that you can often run on your laptop, specially with MiniBatchKMeans.
Links to complete code are at the end.
We generate 3 clusters (0, 1, 2) with 2 features (xx and yy). The clusters are generated with the following 3 pairs of x,y values:
mu1 = 3.0sigma1 = 0.5mu2 = 20.0sigma2 = 5.5mu3a = 1.0sigma3a = 0.8mu3b = 5.0sigma3b = 0.4numpoints = 1000np.random.seed(1234)x1 = np.random.normal(mu1, sigma1, numpoints)y1 = np.random.normal(mu1, sigma1, numpoints)x2 = np.random.normal(mu2, sigma2, numpoints)y2 = np.random.normal(mu2, sigma2, numpoints)x3 = np.random.normal(mu3a, sigma3a, numpoints)y3 = np.random.normal(mu3b, sigma3b, numpoints)
The hyper-parameters are from Scikit’s KMeans:
class sklearn.cluster.KMeans(n_clusters=8, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=None, algorithm='auto')
This is setting a random seed. It is useful if we want to reproduce exact clusters over and over again. We can set it to any number we want. I set it to random_state=1234 below.
We need to provide the algorithm with the number of clusters that we want. Standard literature suggests we use the elbow method to determine how many clusters we need and it works well for Scikits’ cleaned theoretical datasets. In reality, this is only an initial guess. Well, in this example we know we have 3 clusters. So let’s try with n_clusters=3 :
km = KMeans(n_clusters=3, random_state=1234).fit(dftmp.loc[:, dftmp.columns != ‘group’])
We do get 3 clusters, but they are very different from our original clusters. Originally we had 2 clusters in the bottom left, but they are both grouped in to one cluster, the yellow circles. This is because KMeans randomly assigns initial cluster centroids and then tries to group as many points as possible based on the points’ distance to the centroid. Sure, it repeats this process until convergence, but nothing prevents it from being stuck in a local minimum. In fact KMeans is notoriously dependant on the centroid initialization. And here is our first clue that we can not go about blindly using KMeans. If we are asking for 3 clusters, then we need to have some idea where we expect the cluster centers to be in all of the features.
This is where you can set the initial cluster centroids. In our case we have 3 clusters, so we will need 3 centroid arrays. Since we have two features, each of our arrays will be of length 2. So in our case then, we have to have 3 pairs of cluster centers. We know our exact cluster centers since this is a simulation, so let’s try that.
centroids = np.asarray([[mu1,mu1],[mu2,mu2], [mu3a,mu3b]])km = KMeans(n_clusters=3, init=centroids, random_state=1234).fit(dftmp.loc[:, dftmp.columns != 'group'])
Ah! There we go. We have our original 3 clusters for most of the data points!
But wait! That is cheating! We will never know the exact centroids for our clusters. True. We can only speculate what our cluster centers will be approximately. So you don’t have to have the exact centers, but approximate values will help.
What else can we do to improve our clustering specially if we only have approximate cluster centers? Next we will look at another method we can get our original clusters.
I know! You think, but, but, but, we had 3 clusters originally and we set the number of clusters to be 3. What more can we do? How about we set the number of clusters to be twice the number that we expect. What? I know, bear with me, please.
km = KMeans(n_clusters=numclusters, random_state=1234).fit(dftmp.loc[:, dftmp.columns != 'group'])
Look at the bottom right that shows original cluster 0 and 2 — they are more or less well separated. So that is a good thing. But the original cluster 1 (top right) is now separated into 4 clusters. But we know that that is all one cluster from our simulation. So it is a matter of us just consolidating those clusters together after that. Something like cluster (purple, brown, dark green and light green) will become a single cluster.
So if we don’t have an idea of where our cluster centers are, which might be the case with many features, then we can use this trick — of overestimating our number of clusters. One might say this this is overfitting — which is true for the top right cluster, but it is the only way we can get the bottom left clusters to separate, in the absence of good centroids. Even if we had approximate centroids this method will enhance the cluster separation better.
You say: “But wait! I have read you have to normalize your data for KMeans“. Actually that is true. You do have to normalize your data so all the features are within the same range, whenever you do anything that involves Euclidean space, which KMeans does. I was able to get away with it in this case, because my x and y ranges for the original data look about the same : 0–30 (see first graphs in Sample Data section above). But let’s normalize our data to see if it makes a difference.
scl = StandardScaler()dftmparray = (dftmp.loc[:, dftmp.columns != 'group']).valuesdfnorm = scl.fit_transform(dftmparray)dfnorm = pd.DataFrame(dfnorm)km = KMeans(n_clusters=3, random_state=1234).fit(dfnorm)
We see we are still not successful in separating the original cluster 0 and 2 (in the bottom left of the original data), even if we normalize the data.
There are other hyperparameters like tol, max_iter that help with the computational time. These parameters become more important in a more complex problem than what is shown in this example, so I won’t attempt to show them by example.
But let’s look at what they mean:
n_init = By default is 10 and so the algorithm will initialize the centroids 10 times and will pick the most converging value as the best fit. Increase this value to scan the entire feature space. Note if we provide the centroids, then the algorithm will only run once; in fact it will warn us about this at run time. If we set initial centroids or if we set the number of clusters to be more than what we expect (with the intention of consolidating some clusters later on, as discussed above), then we can leave this at the default.
tol = If we set this to a higher value, then it implies that we are willing to tolerate a larger change in inertia, or change of loss, before we declare convergence (sort of like how fast are we converging). So if the change of inertia is less than the value specified by tol, then the algorithm will stop iterating and declare convergence even if it has completed fewer than max_iter rounds. Keep it at a low value to scan the entire feature space.
max_iter = There are n_init runs in general and each run iterates max_iter times, i.e., within a run, points will be assigned to different clusters and the loss calculated for max_iter times. If you keep max_iter at a higher value, then you are guaranteed that you have explored the entire feature space, but often this comes at the cost of diminishing returns.
The other variables decide computing efficiency — so if you have a very large dataset, it would be best that you keep them at the defaults.
It is usually not enough to just run an elbow method, determine the number of clusters and just run the standard KMeans with that. In general we have to explore the data and get subject experts’ opinion on how many clusters there must be and what their approximate centroids should be. Once we have those we can put them all together to tune KMeans:
By providing initial cluster centersBy asking for more clusters than is necessary so we can consolidate some of the clusters in the aftermath.We can also increase the contribution of some features by weighting them more than the others, in an attempt to replace the Euclidean distance by the Mahlanobis distance. For example in the above example if we thought xx is 10 times more important in the separation than yy, then we would multiply xx by 10 after the normalization step. Though this is not always advisable — there are other ways to deal with this like the PCA for example.
By providing initial cluster centers
By asking for more clusters than is necessary so we can consolidate some of the clusters in the aftermath.
We can also increase the contribution of some features by weighting them more than the others, in an attempt to replace the Euclidean distance by the Mahlanobis distance. For example in the above example if we thought xx is 10 times more important in the separation than yy, then we would multiply xx by 10 after the normalization step. Though this is not always advisable — there are other ways to deal with this like the PCA for example.
The complete python code to reproduce the above plots can be found here. The pdf version of the Jupyter notebook with the plots can be found here.
|
[
{
"code": null,
"e": 603,
"s": 172,
"text": "These days anyone with a high school degree can implement a Machine Learning algorithm and that’s a good thing. It is always a good thing when things are accessible to most people. A lot of common libraries are available out there that simplifies the algorithm part. But with great power comes great responsibility. The time freed up writing libraries from scratch should be used to fine tune your model so you get decent results."
},
{
"code": null,
"e": 1445,
"s": 603,
"text": "Today we’ll look at the tuning of the Scikit KMeans model. KMeans is a widely used algorithm to cluster data: you want to cluster your large number of customers in to similar groups based on their purchase behavior, you would use KMeans. You want to cluster all Canadians based on their demographics and interests, you would use KMeans. You want to cluster plants or wine based on their characteristics, you could use KMeans. All of these problems require unsupervised clustering, that is we do not know what the clusters will look like, a priori. There are other methods for unsupervised clustering, such as DBScan, Hierarchical clustering etc and they each have their merits, but in this post I will address KMeans since it is a computationally light clustering method that you can often run on your laptop, specially with MiniBatchKMeans."
},
{
"code": null,
"e": 1484,
"s": 1445,
"text": "Links to complete code are at the end."
},
{
"code": null,
"e": 1615,
"s": 1484,
"text": "We generate 3 clusters (0, 1, 2) with 2 features (xx and yy). The clusters are generated with the following 3 pairs of x,y values:"
},
{
"code": null,
"e": 2015,
"s": 1615,
"text": "mu1 = 3.0sigma1 = 0.5mu2 = 20.0sigma2 = 5.5mu3a = 1.0sigma3a = 0.8mu3b = 5.0sigma3b = 0.4numpoints = 1000np.random.seed(1234)x1 = np.random.normal(mu1, sigma1, numpoints)y1 = np.random.normal(mu1, sigma1, numpoints)x2 = np.random.normal(mu2, sigma2, numpoints)y2 = np.random.normal(mu2, sigma2, numpoints)x3 = np.random.normal(mu3a, sigma3a, numpoints)y3 = np.random.normal(mu3b, sigma3b, numpoints)"
},
{
"code": null,
"e": 2062,
"s": 2015,
"text": "The hyper-parameters are from Scikit’s KMeans:"
},
{
"code": null,
"e": 2263,
"s": 2062,
"text": "class sklearn.cluster.KMeans(n_clusters=8, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=None, algorithm='auto')"
},
{
"code": null,
"e": 2441,
"s": 2263,
"text": "This is setting a random seed. It is useful if we want to reproduce exact clusters over and over again. We can set it to any number we want. I set it to random_state=1234 below."
},
{
"code": null,
"e": 2795,
"s": 2441,
"text": "We need to provide the algorithm with the number of clusters that we want. Standard literature suggests we use the elbow method to determine how many clusters we need and it works well for Scikits’ cleaned theoretical datasets. In reality, this is only an initial guess. Well, in this example we know we have 3 clusters. So let’s try with n_clusters=3 :"
},
{
"code": null,
"e": 2884,
"s": 2795,
"text": "km = KMeans(n_clusters=3, random_state=1234).fit(dftmp.loc[:, dftmp.columns != ‘group’])"
},
{
"code": null,
"e": 3626,
"s": 2884,
"text": "We do get 3 clusters, but they are very different from our original clusters. Originally we had 2 clusters in the bottom left, but they are both grouped in to one cluster, the yellow circles. This is because KMeans randomly assigns initial cluster centroids and then tries to group as many points as possible based on the points’ distance to the centroid. Sure, it repeats this process until convergence, but nothing prevents it from being stuck in a local minimum. In fact KMeans is notoriously dependant on the centroid initialization. And here is our first clue that we can not go about blindly using KMeans. If we are asking for 3 clusters, then we need to have some idea where we expect the cluster centers to be in all of the features."
},
{
"code": null,
"e": 3964,
"s": 3626,
"text": "This is where you can set the initial cluster centroids. In our case we have 3 clusters, so we will need 3 centroid arrays. Since we have two features, each of our arrays will be of length 2. So in our case then, we have to have 3 pairs of cluster centers. We know our exact cluster centers since this is a simulation, so let’s try that."
},
{
"code": null,
"e": 4127,
"s": 3964,
"text": "centroids = np.asarray([[mu1,mu1],[mu2,mu2], [mu3a,mu3b]])km = KMeans(n_clusters=3, init=centroids, random_state=1234).fit(dftmp.loc[:, dftmp.columns != 'group'])"
},
{
"code": null,
"e": 4205,
"s": 4127,
"text": "Ah! There we go. We have our original 3 clusters for most of the data points!"
},
{
"code": null,
"e": 4445,
"s": 4205,
"text": "But wait! That is cheating! We will never know the exact centroids for our clusters. True. We can only speculate what our cluster centers will be approximately. So you don’t have to have the exact centers, but approximate values will help."
},
{
"code": null,
"e": 4616,
"s": 4445,
"text": "What else can we do to improve our clustering specially if we only have approximate cluster centers? Next we will look at another method we can get our original clusters."
},
{
"code": null,
"e": 4858,
"s": 4616,
"text": "I know! You think, but, but, but, we had 3 clusters originally and we set the number of clusters to be 3. What more can we do? How about we set the number of clusters to be twice the number that we expect. What? I know, bear with me, please."
},
{
"code": null,
"e": 4957,
"s": 4858,
"text": "km = KMeans(n_clusters=numclusters, random_state=1234).fit(dftmp.loc[:, dftmp.columns != 'group'])"
},
{
"code": null,
"e": 5394,
"s": 4957,
"text": "Look at the bottom right that shows original cluster 0 and 2 — they are more or less well separated. So that is a good thing. But the original cluster 1 (top right) is now separated into 4 clusters. But we know that that is all one cluster from our simulation. So it is a matter of us just consolidating those clusters together after that. Something like cluster (purple, brown, dark green and light green) will become a single cluster."
},
{
"code": null,
"e": 5852,
"s": 5394,
"text": "So if we don’t have an idea of where our cluster centers are, which might be the case with many features, then we can use this trick — of overestimating our number of clusters. One might say this this is overfitting — which is true for the top right cluster, but it is the only way we can get the bottom left clusters to separate, in the absence of good centroids. Even if we had approximate centroids this method will enhance the cluster separation better."
},
{
"code": null,
"e": 6340,
"s": 5852,
"text": "You say: “But wait! I have read you have to normalize your data for KMeans“. Actually that is true. You do have to normalize your data so all the features are within the same range, whenever you do anything that involves Euclidean space, which KMeans does. I was able to get away with it in this case, because my x and y ranges for the original data look about the same : 0–30 (see first graphs in Sample Data section above). But let’s normalize our data to see if it makes a difference."
},
{
"code": null,
"e": 6546,
"s": 6340,
"text": "scl = StandardScaler()dftmparray = (dftmp.loc[:, dftmp.columns != 'group']).valuesdfnorm = scl.fit_transform(dftmparray)dfnorm = pd.DataFrame(dfnorm)km = KMeans(n_clusters=3, random_state=1234).fit(dfnorm)"
},
{
"code": null,
"e": 6698,
"s": 6546,
"text": "We see we are still not successful in separating the original cluster 0 and 2 (in the bottom left of the original data), even if we normalize the data."
},
{
"code": null,
"e": 6933,
"s": 6698,
"text": "There are other hyperparameters like tol, max_iter that help with the computational time. These parameters become more important in a more complex problem than what is shown in this example, so I won’t attempt to show them by example."
},
{
"code": null,
"e": 6967,
"s": 6933,
"text": "But let’s look at what they mean:"
},
{
"code": null,
"e": 7501,
"s": 6967,
"text": "n_init = By default is 10 and so the algorithm will initialize the centroids 10 times and will pick the most converging value as the best fit. Increase this value to scan the entire feature space. Note if we provide the centroids, then the algorithm will only run once; in fact it will warn us about this at run time. If we set initial centroids or if we set the number of clusters to be more than what we expect (with the intention of consolidating some clusters later on, as discussed above), then we can leave this at the default."
},
{
"code": null,
"e": 7951,
"s": 7501,
"text": "tol = If we set this to a higher value, then it implies that we are willing to tolerate a larger change in inertia, or change of loss, before we declare convergence (sort of like how fast are we converging). So if the change of inertia is less than the value specified by tol, then the algorithm will stop iterating and declare convergence even if it has completed fewer than max_iter rounds. Keep it at a low value to scan the entire feature space."
},
{
"code": null,
"e": 8313,
"s": 7951,
"text": "max_iter = There are n_init runs in general and each run iterates max_iter times, i.e., within a run, points will be assigned to different clusters and the loss calculated for max_iter times. If you keep max_iter at a higher value, then you are guaranteed that you have explored the entire feature space, but often this comes at the cost of diminishing returns."
},
{
"code": null,
"e": 8453,
"s": 8313,
"text": "The other variables decide computing efficiency — so if you have a very large dataset, it would be best that you keep them at the defaults."
},
{
"code": null,
"e": 8803,
"s": 8453,
"text": "It is usually not enough to just run an elbow method, determine the number of clusters and just run the standard KMeans with that. In general we have to explore the data and get subject experts’ opinion on how many clusters there must be and what their approximate centroids should be. Once we have those we can put them all together to tune KMeans:"
},
{
"code": null,
"e": 9385,
"s": 8803,
"text": "By providing initial cluster centersBy asking for more clusters than is necessary so we can consolidate some of the clusters in the aftermath.We can also increase the contribution of some features by weighting them more than the others, in an attempt to replace the Euclidean distance by the Mahlanobis distance. For example in the above example if we thought xx is 10 times more important in the separation than yy, then we would multiply xx by 10 after the normalization step. Though this is not always advisable — there are other ways to deal with this like the PCA for example."
},
{
"code": null,
"e": 9422,
"s": 9385,
"text": "By providing initial cluster centers"
},
{
"code": null,
"e": 9529,
"s": 9422,
"text": "By asking for more clusters than is necessary so we can consolidate some of the clusters in the aftermath."
},
{
"code": null,
"e": 9969,
"s": 9529,
"text": "We can also increase the contribution of some features by weighting them more than the others, in an attempt to replace the Euclidean distance by the Mahlanobis distance. For example in the above example if we thought xx is 10 times more important in the separation than yy, then we would multiply xx by 10 after the normalization step. Though this is not always advisable — there are other ways to deal with this like the PCA for example."
}
] |
What is HTML ?
|
Before you begin, it's important that you know Windows or Unix. A working knowledge of Windows or Unix makes it much easier to learn HTML.
You should be familiar with:
Basic word processing using any text editor.
Basic word processing using any text editor.
How to create directories and files.
How to create directories and files.
How to navigate through different directories.
How to navigate through different directories.
Basic understaning on internet browsing using a browser like Internet Explorer or Firefox etc.
Basic understaning on internet browsing using a browser like Internet Explorer or Firefox etc.
HTML stands for Hypertext Markup Language, and it is the most widely used language to write Web Pages. As its name suggests, HTML is a markup language.
Hypertext refers to the way in which Web pages (HTML documents) are linked together. When you click a link in a Web page, you are using hypertext.
Hypertext refers to the way in which Web pages (HTML documents) are linked together. When you click a link in a Web page, you are using hypertext.
Markup Language describes how HTML works. With a markup language, you simply "mark up" a text document with tags that tell a Web browser how to structure it to display.
Markup Language describes how HTML works. With a markup language, you simply "mark up" a text document with tags that tell a Web browser how to structure it to display.
Originally, HTML was developed with the intent of defining the structure of documents like headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information between researchers.
All you need to do to use HTML is to learn what type of markup to use to get the results you want.
Creating an HTML document is easy. To begin coding HTML you need only two things: a simple-text editor and a web browser. Notepad is the most basic of simple-text editors and you will probably code a fair amount of HTML with it.
You can use our HTML Online Editor to learn HTML. Here are the simple steps to create a baisc HTML document:
Open Notepad or another text editor.
Open Notepad or another text editor.
At the top of the page type <html>.
At the top of the page type <html>.
On the next line, indent five spaces and now add the opening header tag: <head>.
On the next line, indent five spaces and now add the opening header tag: <head>.
On the next line, indent ten spaces and type <title> </title>.
On the next line, indent ten spaces and type <title> </title>.
Go to the next line, indent five spaces from the margin and insert the closing header tag: </head>.
Go to the next line, indent five spaces from the margin and insert the closing header tag: </head>.
Five spaces in from the margin on the next line, type<body>.
Five spaces in from the margin on the next line, type<body>.
Now drop down another line and type the closing tag right below its mate: </body>.
Now drop down another line and type the closing tag right below its mate: </body>.
Finally, go to the next line and type </html>.
Finally, go to the next line and type </html>.
In the File menu, choose Save As.
In the File menu, choose Save As.
In the Save as Type option box, choose All Files.
In the Save as Type option box, choose All Files.
Name the file template.htm.
Name the file template.htm.
Click Save.
Click Save.
You have basic HTML document now, to see some result put the following code in title and body tags.
<html>
<head>
<title>This is document title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Document description goes here.....</p>
</body>
</html>
Now you have created one HTML page and you can use a Web Browser to open this HTML file to see the result. Hope you understood that Web Pages are nothing but they are simple HTML files with some content which can be rendered using Web Browsers.
Here <html>, <head>,...<p>, <h1> etc. are called HTML tags. HTML tags are building blocks of an HTML document nd we will learn all the HTML tags in subsequent chapters.
NOTE: One HTML file can have extension as .htm or .html. So you can use either of them based on your comfort.
An HTML document starts and ends with <html> and >/html> tags. These tags tell the browser that the entire document is composed in HTML. Inside these two tags, the document is split into two sections:
The <head>...</head> elements, which contain information about the document such as title of the document, author of the document etc. Information inside this tag does not display outside.
The <head>...</head> elements, which contain information about the document such as title of the document, author of the document etc. Information inside this tag does not display outside.
The <body>...</body> elements, which contain the real content of the document that you see on your screen.
The <body>...</body> elements, which contain the real content of the document that you see on your screen.
HTML language is a markup language and we use many tags to markup text. In the above example you have seen <html>, <body> etc. are called HTML tags or HTML elements.
Every tag consists of a tag name, sometimes followed by an optional list of tag attributes , all placed between opening and closing brackets (< and >). The simplest tag is nothing more than a name appropriately enclosed in brackets, such as <head> and <i>. More complicated tags contain one or more attributes , which specify or modify the behavior of the tag.
According to the HTML standard, tag and attribute names are not case-sensitive. There's no difference in effect between <head>, <Head>, <HEAD>, or even <HeaD>; they are all equivalent. But with XHTML, case is important: all current standard tag and attribute names are in lowercase.
A very good quality associated with all the browsers is that they would not give any error if you have not put any HTML tag or attribute properly. They will just ignore that tag or attribute and will apply only correct tags and attributes before displaying the result.
We can not say, HTML is forgiving because this is just a markup language and required to format documents.
Next you will see baisc HTML tags in more detail and you will have understanding on HTML tags attributes also.
Advertisements
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2514,
"s": 2374,
"text": "Before you begin, it's important that you know Windows or Unix. A working knowledge of Windows or Unix makes it much easier to learn HTML."
},
{
"code": null,
"e": 2543,
"s": 2514,
"text": "You should be familiar with:"
},
{
"code": null,
"e": 2588,
"s": 2543,
"text": "Basic word processing using any text editor."
},
{
"code": null,
"e": 2633,
"s": 2588,
"text": "Basic word processing using any text editor."
},
{
"code": null,
"e": 2670,
"s": 2633,
"text": "How to create directories and files."
},
{
"code": null,
"e": 2707,
"s": 2670,
"text": "How to create directories and files."
},
{
"code": null,
"e": 2755,
"s": 2707,
"text": "How to navigate through different directories."
},
{
"code": null,
"e": 2803,
"s": 2755,
"text": "How to navigate through different directories."
},
{
"code": null,
"e": 2898,
"s": 2803,
"text": "Basic understaning on internet browsing using a browser like Internet Explorer or Firefox etc."
},
{
"code": null,
"e": 2993,
"s": 2898,
"text": "Basic understaning on internet browsing using a browser like Internet Explorer or Firefox etc."
},
{
"code": null,
"e": 3145,
"s": 2993,
"text": "HTML stands for Hypertext Markup Language, and it is the most widely used language to write Web Pages. As its name suggests, HTML is a markup language."
},
{
"code": null,
"e": 3292,
"s": 3145,
"text": "Hypertext refers to the way in which Web pages (HTML documents) are linked together. When you click a link in a Web page, you are using hypertext."
},
{
"code": null,
"e": 3439,
"s": 3292,
"text": "Hypertext refers to the way in which Web pages (HTML documents) are linked together. When you click a link in a Web page, you are using hypertext."
},
{
"code": null,
"e": 3608,
"s": 3439,
"text": "Markup Language describes how HTML works. With a markup language, you simply \"mark up\" a text document with tags that tell a Web browser how to structure it to display."
},
{
"code": null,
"e": 3777,
"s": 3608,
"text": "Markup Language describes how HTML works. With a markup language, you simply \"mark up\" a text document with tags that tell a Web browser how to structure it to display."
},
{
"code": null,
"e": 3983,
"s": 3777,
"text": "Originally, HTML was developed with the intent of defining the structure of documents like headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information between researchers."
},
{
"code": null,
"e": 4082,
"s": 3983,
"text": "All you need to do to use HTML is to learn what type of markup to use to get the results you want."
},
{
"code": null,
"e": 4311,
"s": 4082,
"text": "Creating an HTML document is easy. To begin coding HTML you need only two things: a simple-text editor and a web browser. Notepad is the most basic of simple-text editors and you will probably code a fair amount of HTML with it."
},
{
"code": null,
"e": 4420,
"s": 4311,
"text": "You can use our HTML Online Editor to learn HTML. Here are the simple steps to create a baisc HTML document:"
},
{
"code": null,
"e": 4457,
"s": 4420,
"text": "Open Notepad or another text editor."
},
{
"code": null,
"e": 4494,
"s": 4457,
"text": "Open Notepad or another text editor."
},
{
"code": null,
"e": 4530,
"s": 4494,
"text": "At the top of the page type <html>."
},
{
"code": null,
"e": 4566,
"s": 4530,
"text": "At the top of the page type <html>."
},
{
"code": null,
"e": 4647,
"s": 4566,
"text": "On the next line, indent five spaces and now add the opening header tag: <head>."
},
{
"code": null,
"e": 4728,
"s": 4647,
"text": "On the next line, indent five spaces and now add the opening header tag: <head>."
},
{
"code": null,
"e": 4791,
"s": 4728,
"text": "On the next line, indent ten spaces and type <title> </title>."
},
{
"code": null,
"e": 4854,
"s": 4791,
"text": "On the next line, indent ten spaces and type <title> </title>."
},
{
"code": null,
"e": 4954,
"s": 4854,
"text": "Go to the next line, indent five spaces from the margin and insert the closing header tag: </head>."
},
{
"code": null,
"e": 5054,
"s": 4954,
"text": "Go to the next line, indent five spaces from the margin and insert the closing header tag: </head>."
},
{
"code": null,
"e": 5115,
"s": 5054,
"text": "Five spaces in from the margin on the next line, type<body>."
},
{
"code": null,
"e": 5176,
"s": 5115,
"text": "Five spaces in from the margin on the next line, type<body>."
},
{
"code": null,
"e": 5259,
"s": 5176,
"text": "Now drop down another line and type the closing tag right below its mate: </body>."
},
{
"code": null,
"e": 5342,
"s": 5259,
"text": "Now drop down another line and type the closing tag right below its mate: </body>."
},
{
"code": null,
"e": 5389,
"s": 5342,
"text": "Finally, go to the next line and type </html>."
},
{
"code": null,
"e": 5436,
"s": 5389,
"text": "Finally, go to the next line and type </html>."
},
{
"code": null,
"e": 5470,
"s": 5436,
"text": "In the File menu, choose Save As."
},
{
"code": null,
"e": 5504,
"s": 5470,
"text": "In the File menu, choose Save As."
},
{
"code": null,
"e": 5554,
"s": 5504,
"text": "In the Save as Type option box, choose All Files."
},
{
"code": null,
"e": 5604,
"s": 5554,
"text": "In the Save as Type option box, choose All Files."
},
{
"code": null,
"e": 5632,
"s": 5604,
"text": "Name the file template.htm."
},
{
"code": null,
"e": 5660,
"s": 5632,
"text": "Name the file template.htm."
},
{
"code": null,
"e": 5673,
"s": 5660,
"text": "Click Save. "
},
{
"code": null,
"e": 5686,
"s": 5673,
"text": "Click Save. "
},
{
"code": null,
"e": 5786,
"s": 5686,
"text": "You have basic HTML document now, to see some result put the following code in title and body tags."
},
{
"code": null,
"e": 5939,
"s": 5786,
"text": "<html>\n<head>\n<title>This is document title</title>\n</head>\n<body>\n<h1>This is a heading</h1>\n<p>Document description goes here.....</p>\n</body>\n</html>"
},
{
"code": null,
"e": 6184,
"s": 5939,
"text": "Now you have created one HTML page and you can use a Web Browser to open this HTML file to see the result. Hope you understood that Web Pages are nothing but they are simple HTML files with some content which can be rendered using Web Browsers."
},
{
"code": null,
"e": 6354,
"s": 6184,
"text": "Here <html>, <head>,...<p>, <h1> etc. are called HTML tags. HTML tags are building blocks of an HTML document nd we will learn all the HTML tags in subsequent chapters."
},
{
"code": null,
"e": 6464,
"s": 6354,
"text": "NOTE: One HTML file can have extension as .htm or .html. So you can use either of them based on your comfort."
},
{
"code": null,
"e": 6665,
"s": 6464,
"text": "An HTML document starts and ends with <html> and >/html> tags. These tags tell the browser that the entire document is composed in HTML. Inside these two tags, the document is split into two sections:"
},
{
"code": null,
"e": 6854,
"s": 6665,
"text": "The <head>...</head> elements, which contain information about the document such as title of the document, author of the document etc. Information inside this tag does not display outside."
},
{
"code": null,
"e": 7043,
"s": 6854,
"text": "The <head>...</head> elements, which contain information about the document such as title of the document, author of the document etc. Information inside this tag does not display outside."
},
{
"code": null,
"e": 7150,
"s": 7043,
"text": "The <body>...</body> elements, which contain the real content of the document that you see on your screen."
},
{
"code": null,
"e": 7257,
"s": 7150,
"text": "The <body>...</body> elements, which contain the real content of the document that you see on your screen."
},
{
"code": null,
"e": 7423,
"s": 7257,
"text": "HTML language is a markup language and we use many tags to markup text. In the above example you have seen <html>, <body> etc. are called HTML tags or HTML elements."
},
{
"code": null,
"e": 7784,
"s": 7423,
"text": "Every tag consists of a tag name, sometimes followed by an optional list of tag attributes , all placed between opening and closing brackets (< and >). The simplest tag is nothing more than a name appropriately enclosed in brackets, such as <head> and <i>. More complicated tags contain one or more attributes , which specify or modify the behavior of the tag."
},
{
"code": null,
"e": 8067,
"s": 7784,
"text": "According to the HTML standard, tag and attribute names are not case-sensitive. There's no difference in effect between <head>, <Head>, <HEAD>, or even <HeaD>; they are all equivalent. But with XHTML, case is important: all current standard tag and attribute names are in lowercase."
},
{
"code": null,
"e": 8336,
"s": 8067,
"text": "A very good quality associated with all the browsers is that they would not give any error if you have not put any HTML tag or attribute properly. They will just ignore that tag or attribute and will apply only correct tags and attributes before displaying the result."
},
{
"code": null,
"e": 8443,
"s": 8336,
"text": "We can not say, HTML is forgiving because this is just a markup language and required to format documents."
},
{
"code": null,
"e": 8555,
"s": 8443,
"text": "Next you will see baisc HTML tags in more detail and you will have understanding on HTML tags attributes also."
},
{
"code": null,
"e": 8572,
"s": 8555,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 8605,
"s": 8572,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8619,
"s": 8605,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8654,
"s": 8619,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8668,
"s": 8654,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8703,
"s": 8668,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8720,
"s": 8703,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8755,
"s": 8720,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8786,
"s": 8755,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 8819,
"s": 8786,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8850,
"s": 8819,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 8885,
"s": 8850,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8916,
"s": 8885,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 8923,
"s": 8916,
"text": " Print"
},
{
"code": null,
"e": 8934,
"s": 8923,
"text": " Add Notes"
}
] |
Find sum of exponents of prime factors of numbers 1 to N - GeeksforGeeks
|
25 Mar, 2022
Given an integer N, the task is to find the sum of exponents of prime factors of numbers 1 to N.
Examples:
Input: N = 4Output: 4Explanation:Numbers up to 4 are 1, 2, 3, 4 whereThe exponent of 1 in the prime factorization of 1 is 0 (20), For 2 it is 1 (21), For 3 it is 1 (31), and For 4 it is 2 (22).The sum of the exponent of prime factors of each number up to 4 is 0 + 1 + 1 + 2 = 4.
Input: N = 10Output: 15Explanation:sum of the exponent of prime factors of each number up to 10 is 15.
Approach: The idea is to use the concept of Prime factors and their powers. Below are the steps:
Iterate for each number from 2 to N and for each number do the following:find the power of prime factors for each number N.Find the summation of each power in the above stepsPrint the summation of all the powers of prime factors of N and print the sum.
Iterate for each number from 2 to N and for each number do the following:find the power of prime factors for each number N.Find the summation of each power in the above steps
find the power of prime factors for each number N.Find the summation of each power in the above steps
find the power of prime factors for each number N.
Find the summation of each power in the above steps
Print the summation of all the powers of prime factors of N and print the sum.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to implement sieve of// eratosthenesvoid sieveOfEratosthenes(int N, int s[]){ // Create a boolean array and // initialize all entries as false vector<bool> prime(N + 1, false); // Initializing smallest // factor equal to 2 // for all the even numbers for (int i = 2; i <= N; i += 2) s[i] = 2; // Iterate for odd numbers // less then equal to n for (int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is // the number itself s[i] = i; // For all multiples of // current prime number for (int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest // prime factor for // number "i*j" s[i * j] = i; } } } }} // Function to generate prime// factors and its powerint generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i int s[N + 1]; int sum = 0; sieveOfEratosthenes(N, s); // Current prime factor of N int curr = s[N]; // Power of current prime factor int cnt = 1; // Calculating prime factors // and their powers sum while (N > 1) { N /= s[N]; if (curr == s[N]) { // Increment the count and // continue the process cnt++; continue; } // Add count to the sum sum = sum + cnt; curr = s[N]; // Reinitialize count cnt = 1; } // Return the result return sum;} // Function to find the sum of all the// power of prime factors of Nvoid findSum(int N){ int sum = 0; // Iterate for in [2, N] for (int i = 2; i <= N; i++) { sum += generatePrimeFactors(i); } cout << sum << endl;} // Driver Codeint main(){ // Given Number N int N = 4; // Function Call findSum(N); return 0;}
// Java program for the above approachclass GFG{ // Function to implement sieve of// eratosthenesstatic void sieveOfEratosthenes(int N, int s[]){ // Create a boolean array and // initialize all entries as false boolean []prime = new boolean[N + 1]; // Initializing smallest // factor equal to 2 // for all the even numbers for(int i = 2; i <= N; i += 2) s[i] = 2; // Iterate for odd numbers // less then equal to n for(int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is // the number itself s[i] = i; // For all multiples of // current prime number for(int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest // prime factor for // number "i*j" s[i * j] = i; } } } }} // Function to generate prime// factors and its powerstatic int generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i int []s = new int[N + 1]; int sum = 0; sieveOfEratosthenes(N, s); // Current prime factor of N int curr = s[N]; // Power of current prime factor int cnt = 1; // Calculating prime factors // and their powers sum while (N > 1) { N /= s[N]; if (curr == s[N]) { // Increment the count and // continue the process cnt++; continue; } // Add count to the sum sum = sum + cnt; curr = s[N]; // Reinitialize count cnt = 1; } // Return the result return sum;} // Function to find the sum of all the// power of prime factors of Nstatic void findSum(int N){ int sum = 0; // Iterate for in [2, N] for(int i = 2; i <= N; i++) { sum += generatePrimeFactors(i); } System.out.print(sum + "\n");} // Driver Codepublic static void main(String[] args){ // Given Number N int N = 4; // Function Call findSum(N);}} // This code is contributed by Ajay Kumar
# Python3 program for the above approach # Function to implement sieve of# eratosthenesdef sieveOfEratosthenes(N, s): # Create a boolean array and # initialize all entries as false prime = [False] * (N + 1) # Initializing smallest # factor equal to 2 # for all the even numbers for i in range(2, N + 1, 2): s[i] = 2 # Iterate for odd numbers # less then equal to n for i in range(3, N + 1, 2): if (prime[i] == False): # s(i) for a prime is # the number itself s[i] = i # For all multiples of # current prime number j = i while (j * i <= N): if (prime[i * j] == False): prime[i * j] = True # i is the smallest # prime factor for # number "i*j" s[i * j] = i j += 2 # Function to generate prime# factors and its powerdef generatePrimeFactors(N): # s[i] is going to store # smallest prime factor of i s = [0] * (N + 1) sum = 0 sieveOfEratosthenes(N, s) # Current prime factor of N curr = s[N] # Power of current prime factor cnt = 1 # Calculating prime factors # and their powers sum while (N > 1): N //= s[N] if (curr == s[N]): # Increment the count and # continue the process cnt += 1 continue # Add count to the sum sum = sum + cnt curr = s[N] # Reinitialize count cnt = 1 # Return the result return sum # Function to find the sum of all the# power of prime factors of Ndef findSum (N): sum = 0 # Iterate for in [2, N] for i in range(2, N + 1): sum += generatePrimeFactors(i) print(sum) # Driver Codeif __name__ == '__main__': # Given number N N = 4 # Function call findSum(N) # This code is contributed by himanshu77
// C# program for the above approachusing System; class GFG{ // Function to implement sieve of// eratosthenesstatic void sieveOfEratosthenes(int N, int []s){ // Create a bool array and // initialize all entries as false bool []prime = new bool[N + 1]; // Initializing smallest // factor equal to 2 // for all the even numbers for(int i = 2; i <= N; i += 2) s[i] = 2; // Iterate for odd numbers // less then equal to n for(int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is // the number itself s[i] = i; // For all multiples of // current prime number for(int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest // prime factor for // number "i*j" s[i * j] = i; } } } }} // Function to generate prime// factors and its powerstatic int generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i int []s = new int[N + 1]; int sum = 0; sieveOfEratosthenes(N, s); // Current prime factor of N int curr = s[N]; // Power of current prime factor int cnt = 1; // Calculating prime factors // and their powers sum while (N > 1) { N /= s[N]; if (curr == s[N]) { // Increment the count and // continue the process cnt++; continue; } // Add count to the sum sum = sum + cnt; curr = s[N]; // Reinitialize count cnt = 1; } // Return the result return sum;} // Function to find the sum of all the// power of prime factors of Nstatic void findSum(int N){ int sum = 0; // Iterate for in [2, N] for(int i = 2; i <= N; i++) { sum += generatePrimeFactors(i); } Console.Write(sum + "\n");} // Driver Codepublic static void Main(String[] args){ // Given number N int N = 4; // Function call findSum(N);}} // This code is contributed by 29AjayKumar
<script> // Javascript program for the above approach // Function to implement sieve of// eratosthenesfunction sieveOfEratosthenes(N, s){ // Create a boolean array and // initialize all entries as false let prime = Array.from({length: N+1}, (_, i) => 0); // Initializing smallest // factor equal to 2 // for all the even numbers for(let i = 2; i <= N; i += 2) s[i] = 2; // Iterate for odd numbers // less then equal to n for(let i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is // the number itself s[i] = i; // For all multiples of // current prime number for(let j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest // prime factor for // number "i*j" s[i * j] = i; } } } }} // Function to generate prime// factors and its powerfunction generatePrimeFactors(N){ // s[i] is going to store // smallest prime factor of i let s = Array.from({length: N+1}, (_, i) => 0); let sum = 0; sieveOfEratosthenes(N, s); // Current prime factor of N let curr = s[N]; // Power of current prime factor let cnt = 1; // Calculating prime factors // and their powers sum while (N > 1) { N /= s[N]; if (curr == s[N]) { // Increment the count and // continue the process cnt++; continue; } // Add count to the sum sum = sum + cnt; curr = s[N]; // Reinitialize count cnt = 1; } // Return the result return sum;} // Function to find the sum of all the// power of prime factors of Nfunction findSum(N){ let sum = 0; // Iterate for in [2, N] for(let i = 2; i <= N; i++) { sum += generatePrimeFactors(i); } document.write(sum + "\n");} // Driver Code // Given Number N let N = 4; // Function Call findSum(N); </script>
4
Time Complexity: O(N*log2N)Auxiliary Space: O(N)
29AjayKumar
himanshu77
target_2
sumitgumber28
factor
maths-power
number-theory
Numbers
Prime Number
prime-factor
Greedy
Mathematical
number-theory
Greedy
Mathematical
Prime Number
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Fractional Knapsack Problem
Activity Selection Problem | Greedy Algo-1
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 25232,
"s": 25204,
"text": "\n25 Mar, 2022"
},
{
"code": null,
"e": 25329,
"s": 25232,
"text": "Given an integer N, the task is to find the sum of exponents of prime factors of numbers 1 to N."
},
{
"code": null,
"e": 25339,
"s": 25329,
"text": "Examples:"
},
{
"code": null,
"e": 25618,
"s": 25339,
"text": "Input: N = 4Output: 4Explanation:Numbers up to 4 are 1, 2, 3, 4 whereThe exponent of 1 in the prime factorization of 1 is 0 (20), For 2 it is 1 (21), For 3 it is 1 (31), and For 4 it is 2 (22).The sum of the exponent of prime factors of each number up to 4 is 0 + 1 + 1 + 2 = 4."
},
{
"code": null,
"e": 25721,
"s": 25618,
"text": "Input: N = 10Output: 15Explanation:sum of the exponent of prime factors of each number up to 10 is 15."
},
{
"code": null,
"e": 25818,
"s": 25721,
"text": "Approach: The idea is to use the concept of Prime factors and their powers. Below are the steps:"
},
{
"code": null,
"e": 26071,
"s": 25818,
"text": "Iterate for each number from 2 to N and for each number do the following:find the power of prime factors for each number N.Find the summation of each power in the above stepsPrint the summation of all the powers of prime factors of N and print the sum."
},
{
"code": null,
"e": 26246,
"s": 26071,
"text": "Iterate for each number from 2 to N and for each number do the following:find the power of prime factors for each number N.Find the summation of each power in the above steps"
},
{
"code": null,
"e": 26348,
"s": 26246,
"text": "find the power of prime factors for each number N.Find the summation of each power in the above steps"
},
{
"code": null,
"e": 26399,
"s": 26348,
"text": "find the power of prime factors for each number N."
},
{
"code": null,
"e": 26451,
"s": 26399,
"text": "Find the summation of each power in the above steps"
},
{
"code": null,
"e": 26530,
"s": 26451,
"text": "Print the summation of all the powers of prime factors of N and print the sum."
},
{
"code": null,
"e": 26581,
"s": 26530,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26585,
"s": 26581,
"text": "C++"
},
{
"code": null,
"e": 26590,
"s": 26585,
"text": "Java"
},
{
"code": null,
"e": 26598,
"s": 26590,
"text": "Python3"
},
{
"code": null,
"e": 26601,
"s": 26598,
"text": "C#"
},
{
"code": null,
"e": 26612,
"s": 26601,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to implement sieve of// eratosthenesvoid sieveOfEratosthenes(int N, int s[]){ // Create a boolean array and // initialize all entries as false vector<bool> prime(N + 1, false); // Initializing smallest // factor equal to 2 // for all the even numbers for (int i = 2; i <= N; i += 2) s[i] = 2; // Iterate for odd numbers // less then equal to n for (int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is // the number itself s[i] = i; // For all multiples of // current prime number for (int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest // prime factor for // number \"i*j\" s[i * j] = i; } } } }} // Function to generate prime// factors and its powerint generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i int s[N + 1]; int sum = 0; sieveOfEratosthenes(N, s); // Current prime factor of N int curr = s[N]; // Power of current prime factor int cnt = 1; // Calculating prime factors // and their powers sum while (N > 1) { N /= s[N]; if (curr == s[N]) { // Increment the count and // continue the process cnt++; continue; } // Add count to the sum sum = sum + cnt; curr = s[N]; // Reinitialize count cnt = 1; } // Return the result return sum;} // Function to find the sum of all the// power of prime factors of Nvoid findSum(int N){ int sum = 0; // Iterate for in [2, N] for (int i = 2; i <= N; i++) { sum += generatePrimeFactors(i); } cout << sum << endl;} // Driver Codeint main(){ // Given Number N int N = 4; // Function Call findSum(N); return 0;}",
"e": 28742,
"s": 26612,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to implement sieve of// eratosthenesstatic void sieveOfEratosthenes(int N, int s[]){ // Create a boolean array and // initialize all entries as false boolean []prime = new boolean[N + 1]; // Initializing smallest // factor equal to 2 // for all the even numbers for(int i = 2; i <= N; i += 2) s[i] = 2; // Iterate for odd numbers // less then equal to n for(int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is // the number itself s[i] = i; // For all multiples of // current prime number for(int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest // prime factor for // number \"i*j\" s[i * j] = i; } } } }} // Function to generate prime// factors and its powerstatic int generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i int []s = new int[N + 1]; int sum = 0; sieveOfEratosthenes(N, s); // Current prime factor of N int curr = s[N]; // Power of current prime factor int cnt = 1; // Calculating prime factors // and their powers sum while (N > 1) { N /= s[N]; if (curr == s[N]) { // Increment the count and // continue the process cnt++; continue; } // Add count to the sum sum = sum + cnt; curr = s[N]; // Reinitialize count cnt = 1; } // Return the result return sum;} // Function to find the sum of all the// power of prime factors of Nstatic void findSum(int N){ int sum = 0; // Iterate for in [2, N] for(int i = 2; i <= N; i++) { sum += generatePrimeFactors(i); } System.out.print(sum + \"\\n\");} // Driver Codepublic static void main(String[] args){ // Given Number N int N = 4; // Function Call findSum(N);}} // This code is contributed by Ajay Kumar",
"e": 30987,
"s": 28742,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to implement sieve of# eratosthenesdef sieveOfEratosthenes(N, s): # Create a boolean array and # initialize all entries as false prime = [False] * (N + 1) # Initializing smallest # factor equal to 2 # for all the even numbers for i in range(2, N + 1, 2): s[i] = 2 # Iterate for odd numbers # less then equal to n for i in range(3, N + 1, 2): if (prime[i] == False): # s(i) for a prime is # the number itself s[i] = i # For all multiples of # current prime number j = i while (j * i <= N): if (prime[i * j] == False): prime[i * j] = True # i is the smallest # prime factor for # number \"i*j\" s[i * j] = i j += 2 # Function to generate prime# factors and its powerdef generatePrimeFactors(N): # s[i] is going to store # smallest prime factor of i s = [0] * (N + 1) sum = 0 sieveOfEratosthenes(N, s) # Current prime factor of N curr = s[N] # Power of current prime factor cnt = 1 # Calculating prime factors # and their powers sum while (N > 1): N //= s[N] if (curr == s[N]): # Increment the count and # continue the process cnt += 1 continue # Add count to the sum sum = sum + cnt curr = s[N] # Reinitialize count cnt = 1 # Return the result return sum # Function to find the sum of all the# power of prime factors of Ndef findSum (N): sum = 0 # Iterate for in [2, N] for i in range(2, N + 1): sum += generatePrimeFactors(i) print(sum) # Driver Codeif __name__ == '__main__': # Given number N N = 4 # Function call findSum(N) # This code is contributed by himanshu77",
"e": 32951,
"s": 30987,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to implement sieve of// eratosthenesstatic void sieveOfEratosthenes(int N, int []s){ // Create a bool array and // initialize all entries as false bool []prime = new bool[N + 1]; // Initializing smallest // factor equal to 2 // for all the even numbers for(int i = 2; i <= N; i += 2) s[i] = 2; // Iterate for odd numbers // less then equal to n for(int i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is // the number itself s[i] = i; // For all multiples of // current prime number for(int j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest // prime factor for // number \"i*j\" s[i * j] = i; } } } }} // Function to generate prime// factors and its powerstatic int generatePrimeFactors(int N){ // s[i] is going to store // smallest prime factor of i int []s = new int[N + 1]; int sum = 0; sieveOfEratosthenes(N, s); // Current prime factor of N int curr = s[N]; // Power of current prime factor int cnt = 1; // Calculating prime factors // and their powers sum while (N > 1) { N /= s[N]; if (curr == s[N]) { // Increment the count and // continue the process cnt++; continue; } // Add count to the sum sum = sum + cnt; curr = s[N]; // Reinitialize count cnt = 1; } // Return the result return sum;} // Function to find the sum of all the// power of prime factors of Nstatic void findSum(int N){ int sum = 0; // Iterate for in [2, N] for(int i = 2; i <= N; i++) { sum += generatePrimeFactors(i); } Console.Write(sum + \"\\n\");} // Driver Codepublic static void Main(String[] args){ // Given number N int N = 4; // Function call findSum(N);}} // This code is contributed by 29AjayKumar",
"e": 35228,
"s": 32951,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to implement sieve of// eratosthenesfunction sieveOfEratosthenes(N, s){ // Create a boolean array and // initialize all entries as false let prime = Array.from({length: N+1}, (_, i) => 0); // Initializing smallest // factor equal to 2 // for all the even numbers for(let i = 2; i <= N; i += 2) s[i] = 2; // Iterate for odd numbers // less then equal to n for(let i = 3; i <= N; i += 2) { if (prime[i] == false) { // s(i) for a prime is // the number itself s[i] = i; // For all multiples of // current prime number for(let j = i; j * i <= N; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest // prime factor for // number \"i*j\" s[i * j] = i; } } } }} // Function to generate prime// factors and its powerfunction generatePrimeFactors(N){ // s[i] is going to store // smallest prime factor of i let s = Array.from({length: N+1}, (_, i) => 0); let sum = 0; sieveOfEratosthenes(N, s); // Current prime factor of N let curr = s[N]; // Power of current prime factor let cnt = 1; // Calculating prime factors // and their powers sum while (N > 1) { N /= s[N]; if (curr == s[N]) { // Increment the count and // continue the process cnt++; continue; } // Add count to the sum sum = sum + cnt; curr = s[N]; // Reinitialize count cnt = 1; } // Return the result return sum;} // Function to find the sum of all the// power of prime factors of Nfunction findSum(N){ let sum = 0; // Iterate for in [2, N] for(let i = 2; i <= N; i++) { sum += generatePrimeFactors(i); } document.write(sum + \"\\n\");} // Driver Code // Given Number N let N = 4; // Function Call findSum(N); </script>",
"e": 37427,
"s": 35228,
"text": null
},
{
"code": null,
"e": 37429,
"s": 37427,
"text": "4"
},
{
"code": null,
"e": 37480,
"s": 37431,
"text": "Time Complexity: O(N*log2N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 37492,
"s": 37480,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37503,
"s": 37492,
"text": "himanshu77"
},
{
"code": null,
"e": 37512,
"s": 37503,
"text": "target_2"
},
{
"code": null,
"e": 37526,
"s": 37512,
"text": "sumitgumber28"
},
{
"code": null,
"e": 37533,
"s": 37526,
"text": "factor"
},
{
"code": null,
"e": 37545,
"s": 37533,
"text": "maths-power"
},
{
"code": null,
"e": 37559,
"s": 37545,
"text": "number-theory"
},
{
"code": null,
"e": 37567,
"s": 37559,
"text": "Numbers"
},
{
"code": null,
"e": 37580,
"s": 37567,
"text": "Prime Number"
},
{
"code": null,
"e": 37593,
"s": 37580,
"text": "prime-factor"
},
{
"code": null,
"e": 37600,
"s": 37593,
"text": "Greedy"
},
{
"code": null,
"e": 37613,
"s": 37600,
"text": "Mathematical"
},
{
"code": null,
"e": 37627,
"s": 37613,
"text": "number-theory"
},
{
"code": null,
"e": 37634,
"s": 37627,
"text": "Greedy"
},
{
"code": null,
"e": 37647,
"s": 37634,
"text": "Mathematical"
},
{
"code": null,
"e": 37660,
"s": 37647,
"text": "Prime Number"
},
{
"code": null,
"e": 37668,
"s": 37660,
"text": "Numbers"
},
{
"code": null,
"e": 37766,
"s": 37668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37797,
"s": 37766,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 37816,
"s": 37797,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 37844,
"s": 37816,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 37887,
"s": 37844,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 37968,
"s": 37887,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 37998,
"s": 37968,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38013,
"s": 37998,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38056,
"s": 38013,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 38075,
"s": 38056,
"text": "Coin Change | DP-7"
}
] |
Data Structures and Algorithms | Set 19 - GeeksforGeeks
|
27 Mar, 2017
Following questions have been asked in GATE CS 2009 exam.
1. Let X be a problem that belongs to the class NP. Then which one of the following is TRUE?(A) There is no polynomial time algorithm for X.(B) If X can be solved deterministically in polynomial time, then P = NP.(C) If X is NP-hard, then it is NP-complete.(D) X may be undecidable.
Answer (C)(A) is incorrect because set NP includes both P(Polynomial time solvable) and NP-Complete .(B) is incorrect because X may belong to P (same reason as (A))(C) is correct because NP-Complete set is intersection of NP and NP-Hard sets.(D) is incorrect because all NP problems are decidable in finite set of operations.
2. What is the number of swaps required to sort n elements using selection sort, in the worst case?(A) Θ(n)(B) Θ(n log n)(C) Θ(n2 )(D) Θ(nn2 log n)
Answer (A)Here is Selection Sort algorithm for sorting in ascending order.
1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at
the second position and advancing each time)
As we can see from the algorithm, selection sort performs swap only after finding the appropriate position of the current picked element. So there are O(n) swaps performed in selection sort.Because swaps require writing to the array, selection sort is preferable if writing to memory is significantly more expensive than reading. This is generally the case if the items are huge but the keys are small. Another example where writing times are crucial is an array stored in EEPROM or Flash. There is no other algorithm with less data movement.
References:http://en.wikipedia.org/wiki/Selection_sort
3. The running time of an algorithm is represented by the following recurrence relation:
if n <= 3 then T(n) = n
else T(n) = T(n/3) + cn
Which one of the following represents the time complexity of the algorithm?(A) Θ(n)(B) Θ(n log n)(C) Θ(n2)(D) Θ(n2 log n)
Answer(A)
T(n) = cn + T(n/3)
= cn + cn/3 + T(n/9)
= cn + cn/3 + cn/9 + T(n/27)
Taking the sum of infinite GP series. The value of T(n) will
be less than this sum.
T(n) <= cn(1/(1-1/3))
<= 3cn/2
or we can say
cn <= T(n) <= 3cn/2
Therefore T(n) = Θ(n)
This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the theorem.
4. The keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted into an initially empty hash table of length 10 using open addressing with hash function h(k) = k mod 10 and linear probing. What is the resultant hash table?
Answer (C)To get the idea of open addressing concept, you can go through below lines from Wikipedia.Open addressing, or closed hashing, is a method of collision resolution in hash tables. With this method a hash collision is resolved by probing, or searching through alternate locations in the array (the probe sequence) until either the target record is found, or an unused array slot is found, which indicates that there is no such key in the table. Well known probe sequences include:
linear probing in which the interval between probes is fixed--often at 1.quadratic probing in which the interval between probes increases linearly (hence, the indices are described by a quadratic function).double hashing in which the interval between probes is fixed for each record but is computed by another hash function.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
GATE-CS-2009
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Normal Forms in DBMS
Differences between TCP and UDP
Semaphores in Process Synchronization
Caesar Cipher in Cryptography
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 1
Computer Networks | Set 2
Database Management Systems | Set 1
|
[
{
"code": null,
"e": 24340,
"s": 24312,
"text": "\n27 Mar, 2017"
},
{
"code": null,
"e": 24398,
"s": 24340,
"text": "Following questions have been asked in GATE CS 2009 exam."
},
{
"code": null,
"e": 24681,
"s": 24398,
"text": "1. Let X be a problem that belongs to the class NP. Then which one of the following is TRUE?(A) There is no polynomial time algorithm for X.(B) If X can be solved deterministically in polynomial time, then P = NP.(C) If X is NP-hard, then it is NP-complete.(D) X may be undecidable."
},
{
"code": null,
"e": 25007,
"s": 24681,
"text": "Answer (C)(A) is incorrect because set NP includes both P(Polynomial time solvable) and NP-Complete .(B) is incorrect because X may belong to P (same reason as (A))(C) is correct because NP-Complete set is intersection of NP and NP-Hard sets.(D) is incorrect because all NP problems are decidable in finite set of operations."
},
{
"code": null,
"e": 25155,
"s": 25007,
"text": "2. What is the number of swaps required to sort n elements using selection sort, in the worst case?(A) Θ(n)(B) Θ(n log n)(C) Θ(n2 )(D) Θ(nn2 log n)"
},
{
"code": null,
"e": 25230,
"s": 25155,
"text": "Answer (A)Here is Selection Sort algorithm for sorting in ascending order."
},
{
"code": null,
"e": 25446,
"s": 25230,
"text": " 1. Find the minimum value in the list\n 2. Swap it with the value in the first position\n 3. Repeat the steps above for the remainder of the list (starting at\n the second position and advancing each time)\n"
},
{
"code": null,
"e": 25989,
"s": 25446,
"text": "As we can see from the algorithm, selection sort performs swap only after finding the appropriate position of the current picked element. So there are O(n) swaps performed in selection sort.Because swaps require writing to the array, selection sort is preferable if writing to memory is significantly more expensive than reading. This is generally the case if the items are huge but the keys are small. Another example where writing times are crucial is an array stored in EEPROM or Flash. There is no other algorithm with less data movement."
},
{
"code": null,
"e": 26044,
"s": 25989,
"text": "References:http://en.wikipedia.org/wiki/Selection_sort"
},
{
"code": null,
"e": 26133,
"s": 26044,
"text": "3. The running time of an algorithm is represented by the following recurrence relation:"
},
{
"code": null,
"e": 26194,
"s": 26133,
"text": " if n <= 3 then T(n) = n\n else T(n) = T(n/3) + cn\n"
},
{
"code": null,
"e": 26316,
"s": 26194,
"text": "Which one of the following represents the time complexity of the algorithm?(A) Θ(n)(B) Θ(n log n)(C) Θ(n2)(D) Θ(n2 log n)"
},
{
"code": null,
"e": 26326,
"s": 26316,
"text": "Answer(A)"
},
{
"code": null,
"e": 26584,
"s": 26326,
"text": "T(n) = cn + T(n/3)\n = cn + cn/3 + T(n/9)\n = cn + cn/3 + cn/9 + T(n/27)\nTaking the sum of infinite GP series. The value of T(n) will\nbe less than this sum.\nT(n) <= cn(1/(1-1/3))\n <= 3cn/2\n\nor we can say \ncn <= T(n) <= 3cn/2\nTherefore T(n) = Θ(n)\n"
},
{
"code": null,
"e": 26706,
"s": 26584,
"text": "This can also be solved using Master Theorem for solving recurrences. The given expression lies in Case 3 of the theorem."
},
{
"code": null,
"e": 26921,
"s": 26706,
"text": "4. The keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted into an initially empty hash table of length 10 using open addressing with hash function h(k) = k mod 10 and linear probing. What is the resultant hash table?"
},
{
"code": null,
"e": 27409,
"s": 26921,
"text": "Answer (C)To get the idea of open addressing concept, you can go through below lines from Wikipedia.Open addressing, or closed hashing, is a method of collision resolution in hash tables. With this method a hash collision is resolved by probing, or searching through alternate locations in the array (the probe sequence) until either the target record is found, or an unused array slot is found, which indicates that there is no such key in the table. Well known probe sequences include:"
},
{
"code": null,
"e": 27734,
"s": 27409,
"text": "linear probing in which the interval between probes is fixed--often at 1.quadratic probing in which the interval between probes increases linearly (hence, the indices are described by a quadratic function).double hashing in which the interval between probes is fixed for each record but is computed by another hash function."
},
{
"code": null,
"e": 27883,
"s": 27734,
"text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above."
},
{
"code": null,
"e": 27896,
"s": 27883,
"text": "GATE-CS-2009"
},
{
"code": null,
"e": 27914,
"s": 27896,
"text": "GATE-CS-DS-&-Algo"
},
{
"code": null,
"e": 27922,
"s": 27914,
"text": "GATE CS"
},
{
"code": null,
"e": 27926,
"s": 27922,
"text": "MCQ"
},
{
"code": null,
"e": 28024,
"s": 27926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28073,
"s": 28024,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 28094,
"s": 28073,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 28126,
"s": 28094,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 28164,
"s": 28126,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 28194,
"s": 28164,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 28241,
"s": 28194,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 28267,
"s": 28241,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 28293,
"s": 28267,
"text": "Computer Networks | Set 1"
},
{
"code": null,
"e": 28319,
"s": 28293,
"text": "Computer Networks | Set 2"
}
] |
How to change the aspect ratio of an image in JavaFX?
|
The javafx.scene.image.Image class is used to load an image into a JavaFX application. This supports BMP, GIF, JPEG, and, PNG formats.
JavaFX provides a class named javafx.scene.image.ImageView is a node that is used to display, the loaded image.
The preserveRatio property of the ImageView class (boolean) specifies whether the aspect ratio of an image should be preserved, while displaying it using the current ImageView object. You can set the value to this property using the setPreserveRatio() method.
By default, the value of this property is true, i.e. though you change the width or height of the image, the aspect ratio of the displayed image will be the same as the source.
To change the aspect ratio of an image −
Instantiate the Image class by passing the URL (string) of the required
image as a parameter.
Instantiate the Image class by passing the URL (string) of the required
image as a parameter.
Instantiate the ImageView class.
Instantiate the ImageView class.
Set the image to it by passing above the image object as a parameter to the setImage() method.
Set the image to it by passing above the image object as a parameter to the setImage() method.
Set the preserveRatio property to false using the setPreserveRatio() method.
Set the preserveRatio property to false using the setPreserveRatio() method.
Now, if you change the with or, the height of the image, its aspect ratio will be
tampered.
Now, if you change the with or, the height of the image, its aspect ratio will be
tampered.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PerspectiveRatioExample extends Application {
public void start(Stage stage) throws IOException {
//creating the image object
InputStream stream = new FileInputStream("D:\\images\\elephant.jpg");
Image image = new Image(stream);
//Creating the image view
ImageView imageView1 = new ImageView(image);
//Setting the image view parameters
imageView1.setX(170);
imageView1.setY(10);
imageView1.setFitWidth(270);
imageView1.setPreserveRatio(true);
//Creating the image view
ImageView imageView2 = new ImageView(image);
//Setting the image view parameters
imageView2.setX(10);
imageView2.setY(180);
imageView2.setFitWidth(580);
imageView2.setFitHeight(160);
imageView2.setPreserveRatio(false);
//Setting the Scene object
Group root = new Group(imageView1, imageView2);
Scene scene = new Scene(root, 595, 350, Color.BEIGE);
stage.setTitle("Perspective Ratio Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
|
[
{
"code": null,
"e": 1197,
"s": 1062,
"text": "The javafx.scene.image.Image class is used to load an image into a JavaFX application. This supports BMP, GIF, JPEG, and, PNG formats."
},
{
"code": null,
"e": 1309,
"s": 1197,
"text": "JavaFX provides a class named javafx.scene.image.ImageView is a node that is used to display, the loaded image."
},
{
"code": null,
"e": 1569,
"s": 1309,
"text": "The preserveRatio property of the ImageView class (boolean) specifies whether the aspect ratio of an image should be preserved, while displaying it using the current ImageView object. You can set the value to this property using the setPreserveRatio() method."
},
{
"code": null,
"e": 1746,
"s": 1569,
"text": "By default, the value of this property is true, i.e. though you change the width or height of the image, the aspect ratio of the displayed image will be the same as the source."
},
{
"code": null,
"e": 1787,
"s": 1746,
"text": "To change the aspect ratio of an image −"
},
{
"code": null,
"e": 1881,
"s": 1787,
"text": "Instantiate the Image class by passing the URL (string) of the required\nimage as a parameter."
},
{
"code": null,
"e": 1975,
"s": 1881,
"text": "Instantiate the Image class by passing the URL (string) of the required\nimage as a parameter."
},
{
"code": null,
"e": 2008,
"s": 1975,
"text": "Instantiate the ImageView class."
},
{
"code": null,
"e": 2041,
"s": 2008,
"text": "Instantiate the ImageView class."
},
{
"code": null,
"e": 2136,
"s": 2041,
"text": "Set the image to it by passing above the image object as a parameter to the setImage() method."
},
{
"code": null,
"e": 2231,
"s": 2136,
"text": "Set the image to it by passing above the image object as a parameter to the setImage() method."
},
{
"code": null,
"e": 2308,
"s": 2231,
"text": "Set the preserveRatio property to false using the setPreserveRatio() method."
},
{
"code": null,
"e": 2385,
"s": 2308,
"text": "Set the preserveRatio property to false using the setPreserveRatio() method."
},
{
"code": null,
"e": 2477,
"s": 2385,
"text": "Now, if you change the with or, the height of the image, its aspect ratio will be\ntampered."
},
{
"code": null,
"e": 2569,
"s": 2477,
"text": "Now, if you change the with or, the height of the image, its aspect ratio will be\ntampered."
},
{
"code": null,
"e": 4015,
"s": 2569,
"text": "import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class PerspectiveRatioExample extends Application {\n public void start(Stage stage) throws IOException {\n //creating the image object\n InputStream stream = new FileInputStream(\"D:\\\\images\\\\elephant.jpg\");\n Image image = new Image(stream);\n //Creating the image view\n ImageView imageView1 = new ImageView(image);\n //Setting the image view parameters\n imageView1.setX(170);\n imageView1.setY(10);\n imageView1.setFitWidth(270);\n imageView1.setPreserveRatio(true);\n //Creating the image view\n ImageView imageView2 = new ImageView(image);\n //Setting the image view parameters\n imageView2.setX(10);\n imageView2.setY(180);\n imageView2.setFitWidth(580);\n imageView2.setFitHeight(160);\n imageView2.setPreserveRatio(false);\n //Setting the Scene object\n Group root = new Group(imageView1, imageView2);\n Scene scene = new Scene(root, 595, 350, Color.BEIGE);\n stage.setTitle(\"Perspective Ratio Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]) {\n launch(args);\n }\n}"
}
] |
Explicit AUC maximization. How to explicitly optimize for maximum... | by Michael Larionov, PhD | Towards Data Science
|
I was getting started on “IEEE-CIS Fraud Detection” Kaggle competition, and something caught my eye:
The fact that the results are evaluated based on AUC makes sense for fraud detection tasks for several reasons:
The data sets are often unbalanced, which makes it difficult to optimize for the recall or other simple metrics, unless you use oversampling or undersampling of data.In reality, the cost of false negative and false positive is different, and the actual task should include this information and optimize the actual cost, not mathematical quantities like recall or F1 score.High AUC increases the chance that we will be able to find an optimal threshold that will satisfy these requirements.
The data sets are often unbalanced, which makes it difficult to optimize for the recall or other simple metrics, unless you use oversampling or undersampling of data.
In reality, the cost of false negative and false positive is different, and the actual task should include this information and optimize the actual cost, not mathematical quantities like recall or F1 score.
High AUC increases the chance that we will be able to find an optimal threshold that will satisfy these requirements.
Usually, AUC is optimized only during hyperparameters tuning, whereas during training they use cross-entropy loss. Why not optimize AUC in the first place instead of cross-entropy?
The same question was raised in this paper:
AUC Optimization vs. Error Rate Minimization
Corinna Cortes∗and Mehryar Mohri
AT&T Labs – Research
180 Park Avenue, Florham Park, NJ 07932, USA
{corinna, mohri}@research.att.com
Abstract
The area under an ROC curve (AUC) is a criterion used in many appli-
cations to measure the quality of a classification algorithm. However,
the objective function optimized in most of these algorithms is the error
rate and not the AUC value. We give a detailed statistical analysis of the
relationship between the AUC and the error rate, including the first exact
expression of the expected value and the variance of the AUC for a fixed
error rate. Our results show that the average AUC is monotonically in-
creasing as a function of the classification accuracy, but that the standard
deviation for uneven distributions and higher error rates is noticeable.
Thus, algorithms designed to minimize the error rate may not lead to
the best possible AUC values. We show that, under certain conditions,
the global function optimized by the RankBoost algorithm is exactly the
AUC. We report the results of our experiments with RankBoost in several
datasets demonstrating the benefits of an algorithm specifically designed
to globally optimize the AUC over other existing algorithms optimizing
an approximation of the AUC or only locally optimizing the AUC.
1 Motivation
In many applications, the overall classification error rate is not the most pertinent perfor-
mance measure, criteria such as ordering or ranking seem more appropriate. Consider for
example the list of relevant documents returned by a search engine for a specific query.
That list may contain several thousand documents, but, in practice, only the top fifty or so
are examined by the user. Thus, a search engine’s ranking of the documents is more critical
than the accuracy of its classification of all documents as relevant or not. More gener-
ally, for a binary classifier assigning a real-valued score to each object, a better correlation
between output scores and the probability of correct classification is highly desirable.
A natural criterion or summary statistic often used to measure the ranking quality of a clas-
sifier is the area under an ROC curve (AUC) [8].1 However, the objective function opti-
mized by most classification algorithms is the error rate and not the AUC. Recently, several
algorithms have been proposed for maximizing the AUC value locally [4] or maximizing
some approximations of the global AUC value [9, 15], but, in general, these algorithms do
not obtain AUC values significantly better than those obtained by an algorithm designed to
minimize the error rates. Thus, it is important to determine the relationship between the
AUC values and the error rate.
∗This author’s new address is: Google Labs, 1440 Broadway, New York, NY 10018,
corinna@google.com.
1The AUC value is equivalent to the Wilcoxon-Mann-Whitney statistic [8] and closely related to
the Gini index [1]. It has been re-invented under the name of L-measure by [11], as already pointed
out by [2], and slightly modified under the name of Linear Ranking by [13, 14].
(1,1)
(0,0)
False positive rate
True positive rate
ROC Curve. AUC=0.718
True positive rate =
correctly classified positive
total positive
False positive rate =
incorrectly classified negative
total negative
Figure 1: An example of ROC curve. The line connecting (0, 0) and (1, 1), corresponding to random
classification, is drawn for reference. The true positive (negative) rate is sometimes referred to as the
sensitivity (resp. specificity) in this context.
In the following sections, we give a detailed statistical analysis of the relationship between
the AUC and the error rate, including the first exact expression of the expected value and
the variance of the AUC for a fixed error rate.2 We show that, under certain conditions, the
global function optimized by the RankBoost algorithm is exactly the AUC. We report the
results of our experiments with RankBoost in several datasets and demonstrate the benefits
of an algorithm specifically designed to globally optimize the AUC over other existing
algorithms optimizing an approximation of the AUC or only locally optimizing the AUC.
2 Definition and properties of the AUC
The Receiver Operating Characteristics (ROC) curves were originally developed in signal
detection theory [3] in connection with radio signals, and have been used since then in many
other applications, in particular for medical decision-making. Over the last few years, they
have found increased interest in the machine learning and data mining communities for
model evaluation and selection [12, 10, 4, 9, 15, 2].
The ROC curve for a binary classification problem plots the true positive rate as a function
of the false positive rate. The points of the curve are obtained by sweeping the classifica-
tion threshold from the most positive classification value to the most negative. For a fully
random classification, the ROC curve is a straight line connecting the origin to (1, 1). Any
improvement over random classification results in an ROC curve at least partially above
this straight line. Fig. (1) shows an example of ROC curve. The AUC is defined as the area
under the ROC curve and is closely related to the ranking quality of the classification as
shown more formally by Lemma 1 below.
Consider a binary classification task with m positive examples and n negative examples.
We will assume that a classifier outputs a strictly ordered list for these examples and will
denote by 1X the indicator function of a set X.
Lemma 1 ([8]) Let c be a fixed classifier. Let x1, . . . , xm be the output of c on the positive
examples and y1, . . . , yn its output on the negative examples. Then, the AUC, A, associated
to c is given by:
A =
Pm
i=1
Pn
j=1 1xi>yj
mn
(1)
that is the value of the Wilcoxon-Mann-Whitney statistic [8].
Proof. The proof is based on the observation that the AUC value is exactly the probability
P(X > Y ) where X is the random variable corresponding to the distribution of the out-
puts for the positive examples and Y the one corresponding to the negative examples [7].
The Wilcoxon-Mann-Whitney statistic is clearly the expression of that probability in the
discrete case, which proves the lemma [8].
Thus, the AUC can be viewed as a measure based on pairwise comparisons between classi-
fications of the two classes. With a perfect ranking, all positive examples are ranked higher
than the negative ones and A = 1. Any deviation from this ranking decreases the AUC.
2An attempt in that direction was made by [15], but, unfortunately, the authors’ analysis and the
result are both wrong.
m − (k − x) Positive examples
Threshold θ
k − x Positive examples x Negative examples
n − x Negative examples
Figure 2: For a fixed number of errors k, there may be x, 0 ≤ x ≤ k, false negative examples.
3 The Expected Value of the AUC
In this section, we compute exactly the expected value of the AUC over all classifications
with a fixed number of errors and compare that to the error rate.
Different classifiers may have the same error rate but different AUC values. Indeed, for a
given classification threshold θ, an arbitrary reordering of the examples with outputs more
than θ clearly does not affect the error rate but leads to different AUC values. Similarly,
one may reorder the examples with output less than θ without changing the error rate.
Assume that the number of errors k is fixed. We wish to compute the average value of the
AUC over all classifications with k errors. Our model is based on the simple assumption
that all classifications or rankings with k errors are equiprobable. One could perhaps argue
that errors are not necessarily evenly distributed, e.g., examples with very high or very low
ranks are less likely to be errors, but we cannot justify such biases in general.
For a given classification, there may be x, 0 ≤ x ≤ k, false positive examples. Since the
number of errors is fixed, there are k − x false negative examples. Figure 3 shows the cor-
responding configuration. The two regions of examples with classification outputs above
and below the threshold are separated by a vertical line. For a given x, the computation of
the AUC, A, as given by Eq. (1) can be divided into the following three parts:
A =
A1 + A2 + A3
mn
, with (2)
A1 = the sum over all pairs (xi
, yj) with xi and yj in distinct regions;
A2 = the sum over all pairs (xi
, yj) with xi and yj in the region above the threshold;
A3 = the sum over all pairs (xi
, yj) with xi and yj in the region below the threshold.
The first term, A1, is easy to compute. Since there are (m − (k − x)) positive examples
above the threshold and n − x negative examples below the threshold, A1 is given by:
A1 = (m − (k − x))(n − x) (3)
To compute A2, we can assign to each negative example above the threshold a position
based on its classification rank. Let position one be the first position above the threshold
and let α1 < . . . < αx denote the positions in increasing order of the x negative examples
in the region above the threshold. The total number of examples classified as positive is
N = m − (k − x) + x. Thus, by definition of A2,
A2 =
Xx
i=1
(N − αi) − (x − i) (4)
where the first term N − αi represents the number of examples ranked higher than the ith
example and the second term x − i discounts the number of negative examples incorrectly
ranked higher than the ith example. Similarly, let α
0
1 < . . . < α0
k−x
denote the positions of
the k − x positive examples below the threshold, counting positions in reverse by starting
from the threshold. Then, A3 is given by:
A3 =
xX0
j=1
(N
0 − α
0
j
) − (x
0 − j) (5)
with N0 = n − x + (k − x) and x
0 = k − x. Combining the expressions of A1, A2, and
A3 leads to:
A =
A1 + A2 + A3
mn
= 1 +
(k − 2x)
2 + k
2mn
−
(
Px
i=1 αi +
Px
0
j=1 α
0
j
)
mn
(6)
Lemma 2 For a fixed x, the average value of the AUC A is given by:
< A >x= 1 −
x
n + k−x
m
2
(7)
Proof. The proof is based on the computation of the average values of Px
i=1 αi and
Px
0
j=1 α
0
j
for a given x. We start by computing the average value < αi >x for a given
i, 1 ≤ i ≤ x. Consider all the possible positions for α1 . . . αi−1 and αi+1 . . . αx, when the
value of αi
is fixed at say αi = l. We have i ≤ l ≤ N − (x − i) since there need to be at
least i−1 positions before αi and N −(x−i) above. There are l −1 possible positions for
α1 . . . αi−1 and N − l possible positions for αi+1 . . . αx. Since the total number of ways
of choosing the x positions for α1 . . . αx out of N is
N
x
, the average value < αi >x is:
< αi >x=
PN−(x−i)
l=i
l
l−1
i−1
N−l
x−i
N
x
(8)
Thus,
<
Xx
i=1
αi >x=
Px
i=1
PN−(x−i)
l=i
l
l−1
i−1
N−l
x−i
N
x
=
PN
l=1
l
Px
i=1
l−1
i−1
N−l
x−i
N
x
(9)
Using the classical identity: P
p1+p2=p
u
p1
v
p2
=
u+v
p
, we can write:
<
Xx
i=1
αi >x=
PN
l=1 l
N−1
x−1
N
x
=
N(N + 1)
2
N−1
x−1
N
x
=
x(N + 1)
2
(10)
Similarly, we have:
<
xX0
j=1
α
0
j >x=
x
0
(N0 + 1)
2
(11)
Replacing <
Px
i=1 αi >x and <
Px
0
j=1 α
0
j >x in Eq. (6) by the expressions given by
Eq. (10) and Eq. (11) leads to:
< A >x= 1 +
(k − 2x)
2 + k − x(N + 1) − x
0
(N0 + 1)
2mn
= 1 −
x
n + k−x
m
2
(12)
which ends the proof of the lemma.
Note that Eq. (7) shows that the average AUC value for a given x is simply one minus the
average of the accuracy rates for the positive and negative classes.
Proposition 1 Assume that a binary classification task with m positive examples and n
negative examples is given. Then, the expected value of the AUC A over all classifications
with k errors is given by:
< A >= 1 −
k
m + n
−
(n − m)
2
(m + n + 1)
4mn
k
m + n
−
Pk−1
x=0
m+n
x
Pk
x=0
m+n+1
x
!
(13)
Proof. Lemma 2 gives the average value of the AUC for a fixed value of x. To compute
the average over all possible values of x, we need to weight the expression of Eq. (7) with
the total number of possible classifications for a given x. There are
N
x
possible ways of
choosing the positions of the x misclassified negative examples, and similarly
N0
x0
possible
ways of choosing the positions of the x
0 = k − x misclassified positive examples. Thus, in
view of Lemma 2, the average AUC is given by:
< A >=
Pk
x=0
N
x
N0
x0
(1 −
x
n + k−x
m
2
)
Pk
x=0
N
x
N0
x0
(14)
The problem is summarized well in the paper’s intro:
What if we did use the AUC as the optimization function instead of cross-entropy? The AUC curve can be computed using Wilcoxon-Mann-Whitney statistic:
If x and y are probabilities, the metric penalizes any occurrence where the probability of the actual positive case is less than the probability of the negative case. This is not a conventional optimization function, because it lacks additive property of MSE or cross-entropy cost functions. As it was noted in the paper,
The AUC in the equation above is not a smooth function of probabilities, because it is constructed using step functions. We can try to smooth it out, to make sure the function is always differentiable, so that we can use the conventional optimization algorithms. One of the ways to get around of this, as demonstrated in the paper, is the RankBoost loss function:
Here x and y are probabilities for the positive and negative class respectively. For example, in the logistic regression model both x and y can be expressed as sigmoid functions:
Here ξ is a predictor variable(s).
I have to admit that these models are nothing new. They are called pairwise comparison models and pioneered by Thurstone in the 1920s. For more information see this book. The foundation of this analysis is Bradley-Terry-Luce model, but the most well-known variation is Elo algorithm. The model itself is very simple and is derived by maximizing the likelihood function:
In our context, M_ij is 1 if i is from the positive class and j is from the negative class. In all other cases, it is 0. The ability values α here are logits, not the probabilities. This makes the model simpler than RankBoost, and also allows us to use it as the final layer of a neural network (in which case the values α will be just the activations of the previous layer). The loss function is:
Where i and j are positive and negative examples respectively.
We will demonstrate this approach using a simple classification problem. We will use TensorFlow to take advantage of automatic differentiation.
As you see, this is a binary classification problem using synthetic data. Instead of trying to correctly classify the results, we will try to maximize AUC.
Epoch 0 Cost = -0.12107406 Epoch 100 Cost = -0.24906836 Epoch 200 Cost = -0.2497198 Epoch 300 Cost = -0.24984348 Epoch 400 Cost = -0.24989356
Now we plot our predictions:
The plot below is based on the threshold 0.945. If I were to choose the conventional threshold 0.5 we would get all observations in one class. Why is that? The reason is that AUC is not sensitive to the bias value. Indeed, since in this model we subtracting pairwise activations, the bias value cancels out. We can add additional term to the cost function to bring the bias closer to 0.5. Or choose to do what we have done above, by hand-picking the threshold that works for us. I want to remind you, that we are optimizing for AUC, so if all observations are predicted to fall into a single class, it is cool with us as long as the AUC has the optimal value.
One can wonder if there is any usefulness in this approach for any real machine learning projects, other than data science competitions that use AUC as the evaluation criterion. But I would argue that it can be useful in case of unbalanced data set as the first step in machine learning. The second step would be to learn the bias parameter and generally fine-tuning the model by using a business-based optimization metric.
One disadvantage of the AUC cost function is that it is using pairwise comparison between observation, so the complexity of the function grows as a square of the number of observations, which could become a performance bottleneck as the number of observations grows. Also one has to come up with a good batching strategy that correctly estimates AUC based on a number of smaller samples (batches).
All code is available in my github repository. Also find more information about RankBoost below.
|
[
{
"code": null,
"e": 273,
"s": 172,
"text": "I was getting started on “IEEE-CIS Fraud Detection” Kaggle competition, and something caught my eye:"
},
{
"code": null,
"e": 385,
"s": 273,
"text": "The fact that the results are evaluated based on AUC makes sense for fraud detection tasks for several reasons:"
},
{
"code": null,
"e": 875,
"s": 385,
"text": "The data sets are often unbalanced, which makes it difficult to optimize for the recall or other simple metrics, unless you use oversampling or undersampling of data.In reality, the cost of false negative and false positive is different, and the actual task should include this information and optimize the actual cost, not mathematical quantities like recall or F1 score.High AUC increases the chance that we will be able to find an optimal threshold that will satisfy these requirements."
},
{
"code": null,
"e": 1042,
"s": 875,
"text": "The data sets are often unbalanced, which makes it difficult to optimize for the recall or other simple metrics, unless you use oversampling or undersampling of data."
},
{
"code": null,
"e": 1249,
"s": 1042,
"text": "In reality, the cost of false negative and false positive is different, and the actual task should include this information and optimize the actual cost, not mathematical quantities like recall or F1 score."
},
{
"code": null,
"e": 1367,
"s": 1249,
"text": "High AUC increases the chance that we will be able to find an optimal threshold that will satisfy these requirements."
},
{
"code": null,
"e": 1548,
"s": 1367,
"text": "Usually, AUC is optimized only during hyperparameters tuning, whereas during training they use cross-entropy loss. Why not optimize AUC in the first place instead of cross-entropy?"
},
{
"code": null,
"e": 1592,
"s": 1548,
"text": "The same question was raised in this paper:"
},
{
"code": null,
"e": 1638,
"s": 1592,
"text": "AUC Optimization vs. Error Rate Minimization\n"
},
{
"code": null,
"e": 1672,
"s": 1638,
"text": "Corinna Cortes∗and Mehryar Mohri\n"
},
{
"code": null,
"e": 1694,
"s": 1672,
"text": "AT&T Labs – Research\n"
},
{
"code": null,
"e": 1740,
"s": 1694,
"text": "180 Park Avenue, Florham Park, NJ 07932, USA\n"
},
{
"code": null,
"e": 1775,
"s": 1740,
"text": "{corinna, mohri}@research.att.com\n"
},
{
"code": null,
"e": 1785,
"s": 1775,
"text": "Abstract\n"
},
{
"code": null,
"e": 1926,
"s": 1785,
"text": "The area under an ROC curve (AUC) is a criterion used in many appli-\ncations to measure the quality of a classification algorithm. However,\n"
},
{
"code": null,
"e": 2001,
"s": 1926,
"text": "the objective function optimized in most of these algorithms is the error\n"
},
{
"code": null,
"e": 2077,
"s": 2001,
"text": "rate and not the AUC value. We give a detailed statistical analysis of the\n"
},
{
"code": null,
"e": 2153,
"s": 2077,
"text": "relationship between the AUC and the error rate, including the first exact\n"
},
{
"code": null,
"e": 2227,
"s": 2153,
"text": "expression of the expected value and the variance of the AUC for a fixed\n"
},
{
"code": null,
"e": 2376,
"s": 2227,
"text": "error rate. Our results show that the average AUC is monotonically in-\ncreasing as a function of the classification accuracy, but that the standard\n"
},
{
"code": null,
"e": 2450,
"s": 2376,
"text": "deviation for uneven distributions and higher error rates is noticeable.\n"
},
{
"code": null,
"e": 2520,
"s": 2450,
"text": "Thus, algorithms designed to minimize the error rate may not lead to\n"
},
{
"code": null,
"e": 2591,
"s": 2520,
"text": "the best possible AUC values. We show that, under certain conditions,\n"
},
{
"code": null,
"e": 2664,
"s": 2591,
"text": "the global function optimized by the RankBoost algorithm is exactly the\n"
},
{
"code": null,
"e": 2737,
"s": 2664,
"text": "AUC. We report the results of our experiments with RankBoost in several\n"
},
{
"code": null,
"e": 2812,
"s": 2737,
"text": "datasets demonstrating the benefits of an algorithm specifically designed\n"
},
{
"code": null,
"e": 2884,
"s": 2812,
"text": "to globally optimize the AUC over other existing algorithms optimizing\n"
},
{
"code": null,
"e": 2949,
"s": 2884,
"text": "an approximation of the AUC or only locally optimizing the AUC.\n"
},
{
"code": null,
"e": 2963,
"s": 2949,
"text": "1 Motivation\n"
},
{
"code": null,
"e": 3146,
"s": 2963,
"text": "In many applications, the overall classification error rate is not the most pertinent perfor-\nmance measure, criteria such as ordering or ranking seem more appropriate. Consider for\n"
},
{
"code": null,
"e": 3236,
"s": 3146,
"text": "example the list of relevant documents returned by a search engine for a specific query.\n"
},
{
"code": null,
"e": 3330,
"s": 3236,
"text": "That list may contain several thousand documents, but, in practice, only the top fifty or so\n"
},
{
"code": null,
"e": 3423,
"s": 3330,
"text": "are examined by the user. Thus, a search engine’s ranking of the documents is more critical\n"
},
{
"code": null,
"e": 3610,
"s": 3423,
"text": "than the accuracy of its classification of all documents as relevant or not. More gener-\nally, for a binary classifier assigning a real-valued score to each object, a better correlation\n"
},
{
"code": null,
"e": 3700,
"s": 3610,
"text": "between output scores and the probability of correct classification is highly desirable.\n"
},
{
"code": null,
"e": 3976,
"s": 3700,
"text": "A natural criterion or summary statistic often used to measure the ranking quality of a clas-\nsifier is the area under an ROC curve (AUC) [8].1 However, the objective function opti-\nmized by most classification algorithms is the error rate and not the AUC. Recently, several\n"
},
{
"code": null,
"e": 4062,
"s": 3976,
"text": "algorithms have been proposed for maximizing the AUC value locally [4] or maximizing\n"
},
{
"code": null,
"e": 4153,
"s": 4062,
"text": "some approximations of the global AUC value [9, 15], but, in general, these algorithms do\n"
},
{
"code": null,
"e": 4245,
"s": 4153,
"text": "not obtain AUC values significantly better than those obtained by an algorithm designed to\n"
},
{
"code": null,
"e": 4336,
"s": 4245,
"text": "minimize the error rates. Thus, it is important to determine the relationship between the\n"
},
{
"code": null,
"e": 4368,
"s": 4336,
"text": "AUC values and the error rate.\n"
},
{
"code": null,
"e": 4448,
"s": 4368,
"text": "∗This author’s new address is: Google Labs, 1440 Broadway, New York, NY 10018,\n"
},
{
"code": null,
"e": 4469,
"s": 4448,
"text": "corinna@google.com.\n"
},
{
"code": null,
"e": 4565,
"s": 4469,
"text": "1The AUC value is equivalent to the Wilcoxon-Mann-Whitney statistic [8] and closely related to\n"
},
{
"code": null,
"e": 4666,
"s": 4565,
"text": "the Gini index [1]. It has been re-invented under the name of L-measure by [11], as already pointed\n"
},
{
"code": null,
"e": 4747,
"s": 4666,
"text": "out by [2], and slightly modified under the name of Linear Ranking by [13, 14].\n"
},
{
"code": null,
"e": 4754,
"s": 4747,
"text": "(1,1)\n"
},
{
"code": null,
"e": 4761,
"s": 4754,
"text": "(0,0)\n"
},
{
"code": null,
"e": 4782,
"s": 4761,
"text": "False positive rate\n"
},
{
"code": null,
"e": 4802,
"s": 4782,
"text": "True positive rate\n"
},
{
"code": null,
"e": 4824,
"s": 4802,
"text": "ROC Curve. AUC=0.718\n"
},
{
"code": null,
"e": 4846,
"s": 4824,
"text": "True positive rate =\n"
},
{
"code": null,
"e": 4877,
"s": 4846,
"text": "correctly classified positive\n"
},
{
"code": null,
"e": 4893,
"s": 4877,
"text": "total positive\n"
},
{
"code": null,
"e": 4916,
"s": 4893,
"text": "False positive rate =\n"
},
{
"code": null,
"e": 4949,
"s": 4916,
"text": "incorrectly classified negative\n"
},
{
"code": null,
"e": 4965,
"s": 4949,
"text": "total negative\n"
},
{
"code": null,
"e": 5064,
"s": 4965,
"text": "Figure 1: An example of ROC curve. The line connecting (0, 0) and (1, 1), corresponding to random\n"
},
{
"code": null,
"e": 5171,
"s": 5064,
"text": "classification, is drawn for reference. The true positive (negative) rate is sometimes referred to as the\n"
},
{
"code": null,
"e": 5221,
"s": 5171,
"text": "sensitivity (resp. specificity) in this context.\n"
},
{
"code": null,
"e": 5317,
"s": 5221,
"text": "In the following sections, we give a detailed statistical analysis of the relationship between\n"
},
{
"code": null,
"e": 5409,
"s": 5317,
"text": "the AUC and the error rate, including the first exact expression of the expected value and\n"
},
{
"code": null,
"e": 5503,
"s": 5409,
"text": "the variance of the AUC for a fixed error rate.2 We show that, under certain conditions, the\n"
},
{
"code": null,
"e": 5591,
"s": 5503,
"text": "global function optimized by the RankBoost algorithm is exactly the AUC. We report the\n"
},
{
"code": null,
"e": 5683,
"s": 5591,
"text": "results of our experiments with RankBoost in several datasets and demonstrate the benefits\n"
},
{
"code": null,
"e": 5771,
"s": 5683,
"text": "of an algorithm specifically designed to globally optimize the AUC over other existing\n"
},
{
"code": null,
"e": 5858,
"s": 5771,
"text": "algorithms optimizing an approximation of the AUC or only locally optimizing the AUC.\n"
},
{
"code": null,
"e": 5898,
"s": 5858,
"text": "2 Definition and properties of the AUC\n"
},
{
"code": null,
"e": 5987,
"s": 5898,
"text": "The Receiver Operating Characteristics (ROC) curves were originally developed in signal\n"
},
{
"code": null,
"e": 6081,
"s": 5987,
"text": "detection theory [3] in connection with radio signals, and have been used since then in many\n"
},
{
"code": null,
"e": 6175,
"s": 6081,
"text": "other applications, in particular for medical decision-making. Over the last few years, they\n"
},
{
"code": null,
"e": 6262,
"s": 6175,
"text": "have found increased interest in the machine learning and data mining communities for\n"
},
{
"code": null,
"e": 6317,
"s": 6262,
"text": "model evaluation and selection [12, 10, 4, 9, 15, 2].\n"
},
{
"code": null,
"e": 6411,
"s": 6317,
"text": "The ROC curve for a binary classification problem plots the true positive rate as a function\n"
},
{
"code": null,
"e": 6598,
"s": 6411,
"text": "of the false positive rate. The points of the curve are obtained by sweeping the classifica-\ntion threshold from the most positive classification value to the most negative. For a fully\n"
},
{
"code": null,
"e": 6692,
"s": 6598,
"text": "random classification, the ROC curve is a straight line connecting the origin to (1, 1). Any\n"
},
{
"code": null,
"e": 6781,
"s": 6692,
"text": "improvement over random classification results in an ROC curve at least partially above\n"
},
{
"code": null,
"e": 6873,
"s": 6781,
"text": "this straight line. Fig. (1) shows an example of ROC curve. The AUC is defined as the area\n"
},
{
"code": null,
"e": 6965,
"s": 6873,
"text": "under the ROC curve and is closely related to the ranking quality of the classification as\n"
},
{
"code": null,
"e": 7004,
"s": 6965,
"text": "shown more formally by Lemma 1 below.\n"
},
{
"code": null,
"e": 7093,
"s": 7004,
"text": "Consider a binary classification task with m positive examples and n negative examples.\n"
},
{
"code": null,
"e": 7187,
"s": 7093,
"text": "We will assume that a classifier outputs a strictly ordered list for these examples and will\n"
},
{
"code": null,
"e": 7236,
"s": 7187,
"text": "denote by 1X the indicator function of a set X.\n"
},
{
"code": null,
"e": 7334,
"s": 7236,
"text": "Lemma 1 ([8]) Let c be a fixed classifier. Let x1, . . . , xm be the output of c on the positive\n"
},
{
"code": null,
"e": 7429,
"s": 7334,
"text": "examples and y1, . . . , yn its output on the negative examples. Then, the AUC, A, associated\n"
},
{
"code": null,
"e": 7448,
"s": 7429,
"text": "to c is given by:\n"
},
{
"code": null,
"e": 7453,
"s": 7448,
"text": "A =\n"
},
{
"code": null,
"e": 7457,
"s": 7453,
"text": "Pm\n"
},
{
"code": null,
"e": 7462,
"s": 7457,
"text": "i=1\n"
},
{
"code": null,
"e": 7466,
"s": 7462,
"text": "Pn\n"
},
{
"code": null,
"e": 7478,
"s": 7466,
"text": "j=1 1xi>yj\n"
},
{
"code": null,
"e": 7482,
"s": 7478,
"text": "mn\n"
},
{
"code": null,
"e": 7487,
"s": 7482,
"text": "(1)\n"
},
{
"code": null,
"e": 7550,
"s": 7487,
"text": "that is the value of the Wilcoxon-Mann-Whitney statistic [8].\n"
},
{
"code": null,
"e": 7642,
"s": 7550,
"text": "Proof. The proof is based on the observation that the AUC value is exactly the probability\n"
},
{
"code": null,
"e": 7819,
"s": 7642,
"text": "P(X > Y ) where X is the random variable corresponding to the distribution of the out-\nputs for the positive examples and Y the one corresponding to the negative examples [7].\n"
},
{
"code": null,
"e": 7909,
"s": 7819,
"text": "The Wilcoxon-Mann-Whitney statistic is clearly the expression of that probability in the\n"
},
{
"code": null,
"e": 7953,
"s": 7909,
"text": "discrete case, which proves the lemma [8].\n"
},
{
"code": null,
"e": 8135,
"s": 7953,
"text": "Thus, the AUC can be viewed as a measure based on pairwise comparisons between classi-\nfications of the two classes. With a perfect ranking, all positive examples are ranked higher\n"
},
{
"code": null,
"e": 8221,
"s": 8135,
"text": "than the negative ones and A = 1. Any deviation from this ranking decreases the AUC.\n"
},
{
"code": null,
"e": 8320,
"s": 8221,
"text": "2An attempt in that direction was made by [15], but, unfortunately, the authors’ analysis and the\n"
},
{
"code": null,
"e": 8344,
"s": 8320,
"text": "result are both wrong.\n"
},
{
"code": null,
"e": 8375,
"s": 8344,
"text": "m − (k − x) Positive examples\n"
},
{
"code": null,
"e": 8388,
"s": 8375,
"text": "Threshold θ\n"
},
{
"code": null,
"e": 8433,
"s": 8388,
"text": "k − x Positive examples x Negative examples\n"
},
{
"code": null,
"e": 8458,
"s": 8433,
"text": "n − x Negative examples\n"
},
{
"code": null,
"e": 8553,
"s": 8458,
"text": "Figure 2: For a fixed number of errors k, there may be x, 0 ≤ x ≤ k, false negative examples.\n"
},
{
"code": null,
"e": 8586,
"s": 8553,
"text": "3 The Expected Value of the AUC\n"
},
{
"code": null,
"e": 8678,
"s": 8586,
"text": "In this section, we compute exactly the expected value of the AUC over all classifications\n"
},
{
"code": null,
"e": 8745,
"s": 8678,
"text": "with a fixed number of errors and compare that to the error rate.\n"
},
{
"code": null,
"e": 8837,
"s": 8745,
"text": "Different classifiers may have the same error rate but different AUC values. Indeed, for a\n"
},
{
"code": null,
"e": 8930,
"s": 8837,
"text": "given classification threshold θ, an arbitrary reordering of the examples with outputs more\n"
},
{
"code": null,
"e": 9023,
"s": 8930,
"text": "than θ clearly does not affect the error rate but leads to different AUC values. Similarly,\n"
},
{
"code": null,
"e": 9110,
"s": 9023,
"text": "one may reorder the examples with output less than θ without changing the error rate.\n"
},
{
"code": null,
"e": 9200,
"s": 9110,
"text": "Assume that the number of errors k is fixed. We wish to compute the average value of the\n"
},
{
"code": null,
"e": 9289,
"s": 9200,
"text": "AUC over all classifications with k errors. Our model is based on the simple assumption\n"
},
{
"code": null,
"e": 9383,
"s": 9289,
"text": "that all classifications or rankings with k errors are equiprobable. One could perhaps argue\n"
},
{
"code": null,
"e": 9478,
"s": 9383,
"text": "that errors are not necessarily evenly distributed, e.g., examples with very high or very low\n"
},
{
"code": null,
"e": 9561,
"s": 9478,
"text": "ranks are less likely to be errors, but we cannot justify such biases in general.\n"
},
{
"code": null,
"e": 9652,
"s": 9561,
"text": "For a given classification, there may be x, 0 ≤ x ≤ k, false positive examples. Since the\n"
},
{
"code": null,
"e": 9833,
"s": 9652,
"text": "number of errors is fixed, there are k − x false negative examples. Figure 3 shows the cor-\nresponding configuration. The two regions of examples with classification outputs above\n"
},
{
"code": null,
"e": 9926,
"s": 9833,
"text": "and below the threshold are separated by a vertical line. For a given x, the computation of\n"
},
{
"code": null,
"e": 10006,
"s": 9926,
"text": "the AUC, A, as given by Eq. (1) can be divided into the following three parts:\n"
},
{
"code": null,
"e": 10011,
"s": 10006,
"text": "A =\n"
},
{
"code": null,
"e": 10025,
"s": 10011,
"text": "A1 + A2 + A3\n"
},
{
"code": null,
"e": 10029,
"s": 10025,
"text": "mn\n"
},
{
"code": null,
"e": 10041,
"s": 10029,
"text": ", with (2)\n"
},
{
"code": null,
"e": 10074,
"s": 10041,
"text": "A1 = the sum over all pairs (xi\n"
},
{
"code": null,
"e": 10117,
"s": 10074,
"text": ", yj) with xi and yj in distinct regions;\n"
},
{
"code": null,
"e": 10150,
"s": 10117,
"text": "A2 = the sum over all pairs (xi\n"
},
{
"code": null,
"e": 10207,
"s": 10150,
"text": ", yj) with xi and yj in the region above the threshold;\n"
},
{
"code": null,
"e": 10240,
"s": 10207,
"text": "A3 = the sum over all pairs (xi\n"
},
{
"code": null,
"e": 10297,
"s": 10240,
"text": ", yj) with xi and yj in the region below the threshold.\n"
},
{
"code": null,
"e": 10386,
"s": 10297,
"text": "The first term, A1, is easy to compute. Since there are (m − (k − x)) positive examples\n"
},
{
"code": null,
"e": 10472,
"s": 10386,
"text": "above the threshold and n − x negative examples below the threshold, A1 is given by:\n"
},
{
"code": null,
"e": 10503,
"s": 10472,
"text": "A1 = (m − (k − x))(n − x) (3)\n"
},
{
"code": null,
"e": 10589,
"s": 10503,
"text": "To compute A2, we can assign to each negative example above the threshold a position\n"
},
{
"code": null,
"e": 10683,
"s": 10589,
"text": "based on its classification rank. Let position one be the first position above the threshold\n"
},
{
"code": null,
"e": 10776,
"s": 10683,
"text": "and let α1 < . . . < αx denote the positions in increasing order of the x negative examples\n"
},
{
"code": null,
"e": 10867,
"s": 10776,
"text": "in the region above the threshold. The total number of examples classified as positive is\n"
},
{
"code": null,
"e": 10916,
"s": 10867,
"text": "N = m − (k − x) + x. Thus, by definition of A2,\n"
},
{
"code": null,
"e": 10922,
"s": 10916,
"text": "A2 =\n"
},
{
"code": null,
"e": 10926,
"s": 10922,
"text": "Xx\n"
},
{
"code": null,
"e": 10931,
"s": 10926,
"text": "i=1\n"
},
{
"code": null,
"e": 10955,
"s": 10931,
"text": "(N − αi) − (x − i) (4)\n"
},
{
"code": null,
"e": 11045,
"s": 10955,
"text": "where the first term N − αi represents the number of examples ranked higher than the ith\n"
},
{
"code": null,
"e": 11134,
"s": 11045,
"text": "example and the second term x − i discounts the number of negative examples incorrectly\n"
},
{
"code": null,
"e": 11188,
"s": 11134,
"text": "ranked higher than the ith example. Similarly, let α\n"
},
{
"code": null,
"e": 11191,
"s": 11188,
"text": "0\n"
},
{
"code": null,
"e": 11207,
"s": 11191,
"text": "1 < . . . < α0\n"
},
{
"code": null,
"e": 11212,
"s": 11207,
"text": "k−x\n"
},
{
"code": null,
"e": 11237,
"s": 11212,
"text": "denote the positions of\n"
},
{
"code": null,
"e": 11329,
"s": 11237,
"text": "the k − x positive examples below the threshold, counting positions in reverse by starting\n"
},
{
"code": null,
"e": 11372,
"s": 11329,
"text": "from the threshold. Then, A3 is given by:\n"
},
{
"code": null,
"e": 11378,
"s": 11372,
"text": "A3 =\n"
},
{
"code": null,
"e": 11383,
"s": 11378,
"text": "xX0\n"
},
{
"code": null,
"e": 11388,
"s": 11383,
"text": "j=1\n"
},
{
"code": null,
"e": 11392,
"s": 11388,
"text": "(N\n"
},
{
"code": null,
"e": 11399,
"s": 11392,
"text": "0 − α\n"
},
{
"code": null,
"e": 11402,
"s": 11399,
"text": "0\n"
},
{
"code": null,
"e": 11405,
"s": 11402,
"text": "j\n"
},
{
"code": null,
"e": 11413,
"s": 11405,
"text": ") − (x\n"
},
{
"code": null,
"e": 11425,
"s": 11413,
"text": "0 − j) (5)\n"
},
{
"code": null,
"e": 11458,
"s": 11425,
"text": "with N0 = n − x + (k − x) and x\n"
},
{
"code": null,
"e": 11511,
"s": 11458,
"text": "0 = k − x. Combining the expressions of A1, A2, and\n"
},
{
"code": null,
"e": 11525,
"s": 11511,
"text": "A3 leads to:\n"
},
{
"code": null,
"e": 11530,
"s": 11525,
"text": "A =\n"
},
{
"code": null,
"e": 11544,
"s": 11530,
"text": "A1 + A2 + A3\n"
},
{
"code": null,
"e": 11548,
"s": 11544,
"text": "mn\n"
},
{
"code": null,
"e": 11555,
"s": 11548,
"text": "= 1 +\n"
},
{
"code": null,
"e": 11565,
"s": 11555,
"text": "(k − 2x)\n"
},
{
"code": null,
"e": 11572,
"s": 11565,
"text": "2 + k\n"
},
{
"code": null,
"e": 11577,
"s": 11572,
"text": "2mn\n"
},
{
"code": null,
"e": 11580,
"s": 11577,
"text": "−\n"
},
{
"code": null,
"e": 11583,
"s": 11580,
"text": "(\n"
},
{
"code": null,
"e": 11587,
"s": 11583,
"text": "Px\n"
},
{
"code": null,
"e": 11597,
"s": 11587,
"text": "i=1 αi +\n"
},
{
"code": null,
"e": 11601,
"s": 11597,
"text": "Px\n"
},
{
"code": null,
"e": 11604,
"s": 11601,
"text": "0\n"
},
{
"code": null,
"e": 11611,
"s": 11604,
"text": "j=1 α\n"
},
{
"code": null,
"e": 11614,
"s": 11611,
"text": "0\n"
},
{
"code": null,
"e": 11617,
"s": 11614,
"text": "j\n"
},
{
"code": null,
"e": 11620,
"s": 11617,
"text": ")\n"
},
{
"code": null,
"e": 11624,
"s": 11620,
"text": "mn\n"
},
{
"code": null,
"e": 11629,
"s": 11624,
"text": "(6)\n"
},
{
"code": null,
"e": 11697,
"s": 11629,
"text": "Lemma 2 For a fixed x, the average value of the AUC A is given by:\n"
},
{
"code": null,
"e": 11710,
"s": 11697,
"text": "< A >x= 1 −\n"
},
{
"code": null,
"e": 11713,
"s": 11710,
"text": "x\n"
},
{
"code": null,
"e": 11722,
"s": 11713,
"text": "n + k−x\n"
},
{
"code": null,
"e": 11725,
"s": 11722,
"text": "m\n"
},
{
"code": null,
"e": 11728,
"s": 11725,
"text": "2\n"
},
{
"code": null,
"e": 11733,
"s": 11728,
"text": "(7)\n"
},
{
"code": null,
"e": 11807,
"s": 11733,
"text": "Proof. The proof is based on the computation of the average values of Px\n"
},
{
"code": null,
"e": 11819,
"s": 11807,
"text": "i=1 αi and\n"
},
{
"code": null,
"e": 11823,
"s": 11819,
"text": "Px\n"
},
{
"code": null,
"e": 11826,
"s": 11823,
"text": "0\n"
},
{
"code": null,
"e": 11833,
"s": 11826,
"text": "j=1 α\n"
},
{
"code": null,
"e": 11836,
"s": 11833,
"text": "0\n"
},
{
"code": null,
"e": 11839,
"s": 11836,
"text": "j\n"
},
{
"code": null,
"e": 11915,
"s": 11839,
"text": "for a given x. We start by computing the average value < αi >x for a given\n"
},
{
"code": null,
"e": 12012,
"s": 11915,
"text": "i, 1 ≤ i ≤ x. Consider all the possible positions for α1 . . . αi−1 and αi+1 . . . αx, when the\n"
},
{
"code": null,
"e": 12025,
"s": 12012,
"text": "value of αi\n"
},
{
"code": null,
"e": 12104,
"s": 12025,
"text": "is fixed at say αi = l. We have i ≤ l ≤ N − (x − i) since there need to be at\n"
},
{
"code": null,
"e": 12193,
"s": 12104,
"text": "least i−1 positions before αi and N −(x−i) above. There are l −1 possible positions for\n"
},
{
"code": null,
"e": 12287,
"s": 12193,
"text": "α1 . . . αi−1 and N − l possible positions for αi+1 . . . αx. Since the total number of ways\n"
},
{
"code": null,
"e": 12344,
"s": 12287,
"text": "of choosing the x positions for α1 . . . αx out of N is\n"
},
{
"code": null,
"e": 12347,
"s": 12344,
"text": "N\n"
},
{
"code": null,
"e": 12350,
"s": 12347,
"text": "x\n"
},
{
"code": null,
"e": 12385,
"s": 12352,
"text": ", the average value < αi >x is:\n"
},
{
"code": null,
"e": 12395,
"s": 12385,
"text": "< αi >x=\n"
},
{
"code": null,
"e": 12405,
"s": 12395,
"text": "PN−(x−i)\n"
},
{
"code": null,
"e": 12410,
"s": 12405,
"text": "l=i\n"
},
{
"code": null,
"e": 12413,
"s": 12410,
"text": "l\n"
},
{
"code": null,
"e": 12418,
"s": 12413,
"text": "l−1\n"
},
{
"code": null,
"e": 12423,
"s": 12418,
"text": "i−1\n"
},
{
"code": null,
"e": 12430,
"s": 12425,
"text": "N−l\n"
},
{
"code": null,
"e": 12435,
"s": 12430,
"text": "x−i\n"
},
{
"code": null,
"e": 12440,
"s": 12437,
"text": "N\n"
},
{
"code": null,
"e": 12443,
"s": 12440,
"text": "x\n"
},
{
"code": null,
"e": 12449,
"s": 12443,
"text": " (8)\n"
},
{
"code": null,
"e": 12456,
"s": 12449,
"text": "Thus,\n"
},
{
"code": null,
"e": 12459,
"s": 12456,
"text": "<\n"
},
{
"code": null,
"e": 12463,
"s": 12459,
"text": "Xx\n"
},
{
"code": null,
"e": 12468,
"s": 12463,
"text": "i=1\n"
},
{
"code": null,
"e": 12476,
"s": 12468,
"text": "αi >x=\n"
},
{
"code": null,
"e": 12480,
"s": 12476,
"text": "Px\n"
},
{
"code": null,
"e": 12485,
"s": 12480,
"text": "i=1\n"
},
{
"code": null,
"e": 12495,
"s": 12485,
"text": "PN−(x−i)\n"
},
{
"code": null,
"e": 12500,
"s": 12495,
"text": "l=i\n"
},
{
"code": null,
"e": 12503,
"s": 12500,
"text": "l\n"
},
{
"code": null,
"e": 12508,
"s": 12503,
"text": "l−1\n"
},
{
"code": null,
"e": 12513,
"s": 12508,
"text": "i−1\n"
},
{
"code": null,
"e": 12520,
"s": 12515,
"text": "N−l\n"
},
{
"code": null,
"e": 12525,
"s": 12520,
"text": "x−i\n"
},
{
"code": null,
"e": 12530,
"s": 12527,
"text": "N\n"
},
{
"code": null,
"e": 12533,
"s": 12530,
"text": "x\n"
},
{
"code": null,
"e": 12537,
"s": 12533,
"text": " =\n"
},
{
"code": null,
"e": 12541,
"s": 12537,
"text": "PN\n"
},
{
"code": null,
"e": 12546,
"s": 12541,
"text": "l=1\n"
},
{
"code": null,
"e": 12549,
"s": 12546,
"text": "l\n"
},
{
"code": null,
"e": 12553,
"s": 12549,
"text": "Px\n"
},
{
"code": null,
"e": 12558,
"s": 12553,
"text": "i=1\n"
},
{
"code": null,
"e": 12563,
"s": 12558,
"text": "l−1\n"
},
{
"code": null,
"e": 12568,
"s": 12563,
"text": "i−1\n"
},
{
"code": null,
"e": 12575,
"s": 12570,
"text": "N−l\n"
},
{
"code": null,
"e": 12580,
"s": 12575,
"text": "x−i\n"
},
{
"code": null,
"e": 12585,
"s": 12582,
"text": "N\n"
},
{
"code": null,
"e": 12588,
"s": 12585,
"text": "x\n"
},
{
"code": null,
"e": 12594,
"s": 12588,
"text": " (9)\n"
},
{
"code": null,
"e": 12627,
"s": 12594,
"text": "Using the classical identity: P\n"
},
{
"code": null,
"e": 12636,
"s": 12627,
"text": "p1+p2=p\n"
},
{
"code": null,
"e": 12639,
"s": 12636,
"text": "u\n"
},
{
"code": null,
"e": 12643,
"s": 12639,
"text": "p1\n"
},
{
"code": null,
"e": 12648,
"s": 12645,
"text": "v\n"
},
{
"code": null,
"e": 12652,
"s": 12648,
"text": "p2\n"
},
{
"code": null,
"e": 12657,
"s": 12654,
"text": "=\n"
},
{
"code": null,
"e": 12662,
"s": 12657,
"text": "u+v\n"
},
{
"code": null,
"e": 12665,
"s": 12662,
"text": "p\n"
},
{
"code": null,
"e": 12684,
"s": 12667,
"text": ", we can write:\n"
},
{
"code": null,
"e": 12687,
"s": 12684,
"text": "<\n"
},
{
"code": null,
"e": 12691,
"s": 12687,
"text": "Xx\n"
},
{
"code": null,
"e": 12696,
"s": 12691,
"text": "i=1\n"
},
{
"code": null,
"e": 12704,
"s": 12696,
"text": "αi >x=\n"
},
{
"code": null,
"e": 12708,
"s": 12704,
"text": "PN\n"
},
{
"code": null,
"e": 12715,
"s": 12708,
"text": "l=1 l\n"
},
{
"code": null,
"e": 12720,
"s": 12715,
"text": "N−1\n"
},
{
"code": null,
"e": 12725,
"s": 12720,
"text": "x−1\n"
},
{
"code": null,
"e": 12730,
"s": 12727,
"text": "N\n"
},
{
"code": null,
"e": 12733,
"s": 12730,
"text": "x\n"
},
{
"code": null,
"e": 12737,
"s": 12733,
"text": " =\n"
},
{
"code": null,
"e": 12747,
"s": 12737,
"text": "N(N + 1)\n"
},
{
"code": null,
"e": 12750,
"s": 12747,
"text": "2\n"
},
{
"code": null,
"e": 12755,
"s": 12750,
"text": "N−1\n"
},
{
"code": null,
"e": 12760,
"s": 12755,
"text": "x−1\n"
},
{
"code": null,
"e": 12765,
"s": 12762,
"text": "N\n"
},
{
"code": null,
"e": 12768,
"s": 12765,
"text": "x\n"
},
{
"code": null,
"e": 12772,
"s": 12768,
"text": " =\n"
},
{
"code": null,
"e": 12782,
"s": 12772,
"text": "x(N + 1)\n"
},
{
"code": null,
"e": 12785,
"s": 12782,
"text": "2\n"
},
{
"code": null,
"e": 12791,
"s": 12785,
"text": "(10)\n"
},
{
"code": null,
"e": 12812,
"s": 12791,
"text": "Similarly, we have:\n"
},
{
"code": null,
"e": 12815,
"s": 12812,
"text": "<\n"
},
{
"code": null,
"e": 12820,
"s": 12815,
"text": "xX0\n"
},
{
"code": null,
"e": 12825,
"s": 12820,
"text": "j=1\n"
},
{
"code": null,
"e": 12828,
"s": 12825,
"text": "α\n"
},
{
"code": null,
"e": 12831,
"s": 12828,
"text": "0\n"
},
{
"code": null,
"e": 12838,
"s": 12831,
"text": "j >x=\n"
},
{
"code": null,
"e": 12841,
"s": 12838,
"text": "x\n"
},
{
"code": null,
"e": 12844,
"s": 12841,
"text": "0\n"
},
{
"code": null,
"e": 12854,
"s": 12844,
"text": "(N0 + 1)\n"
},
{
"code": null,
"e": 12857,
"s": 12854,
"text": "2\n"
},
{
"code": null,
"e": 12863,
"s": 12857,
"text": "(11)\n"
},
{
"code": null,
"e": 12876,
"s": 12863,
"text": "Replacing <\n"
},
{
"code": null,
"e": 12880,
"s": 12876,
"text": "Px\n"
},
{
"code": null,
"e": 12897,
"s": 12880,
"text": "i=1 αi >x and <\n"
},
{
"code": null,
"e": 12901,
"s": 12897,
"text": "Px\n"
},
{
"code": null,
"e": 12904,
"s": 12901,
"text": "0\n"
},
{
"code": null,
"e": 12911,
"s": 12904,
"text": "j=1 α\n"
},
{
"code": null,
"e": 12914,
"s": 12911,
"text": "0\n"
},
{
"code": null,
"e": 12959,
"s": 12914,
"text": "j >x in Eq. (6) by the expressions given by\n"
},
{
"code": null,
"e": 12992,
"s": 12959,
"text": "Eq. (10) and Eq. (11) leads to:\n"
},
{
"code": null,
"e": 13005,
"s": 12992,
"text": "< A >x= 1 +\n"
},
{
"code": null,
"e": 13015,
"s": 13005,
"text": "(k − 2x)\n"
},
{
"code": null,
"e": 13037,
"s": 13015,
"text": "2 + k − x(N + 1) − x\n"
},
{
"code": null,
"e": 13040,
"s": 13037,
"text": "0\n"
},
{
"code": null,
"e": 13050,
"s": 13040,
"text": "(N0 + 1)\n"
},
{
"code": null,
"e": 13055,
"s": 13050,
"text": "2mn\n"
},
{
"code": null,
"e": 13062,
"s": 13055,
"text": "= 1 −\n"
},
{
"code": null,
"e": 13065,
"s": 13062,
"text": "x\n"
},
{
"code": null,
"e": 13074,
"s": 13065,
"text": "n + k−x\n"
},
{
"code": null,
"e": 13077,
"s": 13074,
"text": "m\n"
},
{
"code": null,
"e": 13080,
"s": 13077,
"text": "2\n"
},
{
"code": null,
"e": 13086,
"s": 13080,
"text": "(12)\n"
},
{
"code": null,
"e": 13122,
"s": 13086,
"text": "which ends the proof of the lemma.\n"
},
{
"code": null,
"e": 13212,
"s": 13122,
"text": "Note that Eq. (7) shows that the average AUC value for a given x is simply one minus the\n"
},
{
"code": null,
"e": 13282,
"s": 13212,
"text": "average of the accuracy rates for the positive and negative classes.\n"
},
{
"code": null,
"e": 13369,
"s": 13282,
"text": "Proposition 1 Assume that a binary classification task with m positive examples and n\n"
},
{
"code": null,
"e": 13461,
"s": 13369,
"text": "negative examples is given. Then, the expected value of the AUC A over all classifications\n"
},
{
"code": null,
"e": 13489,
"s": 13461,
"text": "with k errors is given by:\n"
},
{
"code": null,
"e": 13501,
"s": 13489,
"text": "< A >= 1 −\n"
},
{
"code": null,
"e": 13504,
"s": 13501,
"text": "k\n"
},
{
"code": null,
"e": 13511,
"s": 13504,
"text": "m + n\n"
},
{
"code": null,
"e": 13514,
"s": 13511,
"text": "−\n"
},
{
"code": null,
"e": 13523,
"s": 13514,
"text": "(n − m)\n"
},
{
"code": null,
"e": 13526,
"s": 13523,
"text": "2\n"
},
{
"code": null,
"e": 13539,
"s": 13526,
"text": "(m + n + 1)\n"
},
{
"code": null,
"e": 13544,
"s": 13539,
"text": "4mn\n"
},
{
"code": null,
"e": 13549,
"s": 13546,
"text": "k\n"
},
{
"code": null,
"e": 13556,
"s": 13549,
"text": "m + n\n"
},
{
"code": null,
"e": 13559,
"s": 13556,
"text": "−\n"
},
{
"code": null,
"e": 13565,
"s": 13559,
"text": "Pk−1\n"
},
{
"code": null,
"e": 13570,
"s": 13565,
"text": "x=0\n"
},
{
"code": null,
"e": 13575,
"s": 13570,
"text": "m+n\n"
},
{
"code": null,
"e": 13578,
"s": 13575,
"text": "x\n"
},
{
"code": null,
"e": 13584,
"s": 13580,
"text": "Pk\n"
},
{
"code": null,
"e": 13589,
"s": 13584,
"text": "x=0\n"
},
{
"code": null,
"e": 13596,
"s": 13589,
"text": "m+n+1\n"
},
{
"code": null,
"e": 13599,
"s": 13596,
"text": "x\n"
},
{
"code": null,
"e": 13604,
"s": 13601,
"text": "!\n"
},
{
"code": null,
"e": 13610,
"s": 13604,
"text": "(13)\n"
},
{
"code": null,
"e": 13696,
"s": 13610,
"text": "Proof. Lemma 2 gives the average value of the AUC for a fixed value of x. To compute\n"
},
{
"code": null,
"e": 13789,
"s": 13696,
"text": "the average over all possible values of x, we need to weight the expression of Eq. (7) with\n"
},
{
"code": null,
"e": 13860,
"s": 13789,
"text": "the total number of possible classifications for a given x. There are\n"
},
{
"code": null,
"e": 13863,
"s": 13860,
"text": "N\n"
},
{
"code": null,
"e": 13866,
"s": 13863,
"text": "x\n"
},
{
"code": null,
"e": 13886,
"s": 13868,
"text": "possible ways of\n"
},
{
"code": null,
"e": 13966,
"s": 13886,
"text": "choosing the positions of the x misclassified negative examples, and similarly\n"
},
{
"code": null,
"e": 13970,
"s": 13966,
"text": "N0\n"
},
{
"code": null,
"e": 13974,
"s": 13970,
"text": "x0\n"
},
{
"code": null,
"e": 13986,
"s": 13976,
"text": "possible\n"
},
{
"code": null,
"e": 14027,
"s": 13986,
"text": "ways of choosing the positions of the x\n"
},
{
"code": null,
"e": 14080,
"s": 14027,
"text": "0 = k − x misclassified positive examples. Thus, in\n"
},
{
"code": null,
"e": 14127,
"s": 14080,
"text": "view of Lemma 2, the average AUC is given by:\n"
},
{
"code": null,
"e": 14135,
"s": 14127,
"text": "< A >=\n"
},
{
"code": null,
"e": 14139,
"s": 14135,
"text": "Pk\n"
},
{
"code": null,
"e": 14144,
"s": 14139,
"text": "x=0\n"
},
{
"code": null,
"e": 14147,
"s": 14144,
"text": "N\n"
},
{
"code": null,
"e": 14150,
"s": 14147,
"text": "x\n"
},
{
"code": null,
"e": 14156,
"s": 14152,
"text": "N0\n"
},
{
"code": null,
"e": 14160,
"s": 14156,
"text": "x0\n"
},
{
"code": null,
"e": 14168,
"s": 14162,
"text": "(1 −\n"
},
{
"code": null,
"e": 14171,
"s": 14168,
"text": "x\n"
},
{
"code": null,
"e": 14180,
"s": 14171,
"text": "n + k−x\n"
},
{
"code": null,
"e": 14183,
"s": 14180,
"text": "m\n"
},
{
"code": null,
"e": 14186,
"s": 14183,
"text": "2\n"
},
{
"code": null,
"e": 14189,
"s": 14186,
"text": ")\n"
},
{
"code": null,
"e": 14193,
"s": 14189,
"text": "Pk\n"
},
{
"code": null,
"e": 14198,
"s": 14193,
"text": "x=0\n"
},
{
"code": null,
"e": 14201,
"s": 14198,
"text": "N\n"
},
{
"code": null,
"e": 14204,
"s": 14201,
"text": "x\n"
},
{
"code": null,
"e": 14210,
"s": 14206,
"text": "N0\n"
},
{
"code": null,
"e": 14214,
"s": 14210,
"text": "x0\n"
},
{
"code": null,
"e": 14221,
"s": 14214,
"text": " (14)\n"
},
{
"code": null,
"e": 14274,
"s": 14221,
"text": "The problem is summarized well in the paper’s intro:"
},
{
"code": null,
"e": 14425,
"s": 14274,
"text": "What if we did use the AUC as the optimization function instead of cross-entropy? The AUC curve can be computed using Wilcoxon-Mann-Whitney statistic:"
},
{
"code": null,
"e": 14747,
"s": 14425,
"text": "If x and y are probabilities, the metric penalizes any occurrence where the probability of the actual positive case is less than the probability of the negative case. This is not a conventional optimization function, because it lacks additive property of MSE or cross-entropy cost functions. As it was noted in the paper,"
},
{
"code": null,
"e": 15111,
"s": 14747,
"text": "The AUC in the equation above is not a smooth function of probabilities, because it is constructed using step functions. We can try to smooth it out, to make sure the function is always differentiable, so that we can use the conventional optimization algorithms. One of the ways to get around of this, as demonstrated in the paper, is the RankBoost loss function:"
},
{
"code": null,
"e": 15290,
"s": 15111,
"text": "Here x and y are probabilities for the positive and negative class respectively. For example, in the logistic regression model both x and y can be expressed as sigmoid functions:"
},
{
"code": null,
"e": 15325,
"s": 15290,
"text": "Here ξ is a predictor variable(s)."
},
{
"code": null,
"e": 15695,
"s": 15325,
"text": "I have to admit that these models are nothing new. They are called pairwise comparison models and pioneered by Thurstone in the 1920s. For more information see this book. The foundation of this analysis is Bradley-Terry-Luce model, but the most well-known variation is Elo algorithm. The model itself is very simple and is derived by maximizing the likelihood function:"
},
{
"code": null,
"e": 16093,
"s": 15695,
"text": "In our context, M_ij is 1 if i is from the positive class and j is from the negative class. In all other cases, it is 0. The ability values α here are logits, not the probabilities. This makes the model simpler than RankBoost, and also allows us to use it as the final layer of a neural network (in which case the values α will be just the activations of the previous layer). The loss function is:"
},
{
"code": null,
"e": 16156,
"s": 16093,
"text": "Where i and j are positive and negative examples respectively."
},
{
"code": null,
"e": 16300,
"s": 16156,
"text": "We will demonstrate this approach using a simple classification problem. We will use TensorFlow to take advantage of automatic differentiation."
},
{
"code": null,
"e": 16456,
"s": 16300,
"text": "As you see, this is a binary classification problem using synthetic data. Instead of trying to correctly classify the results, we will try to maximize AUC."
},
{
"code": null,
"e": 16598,
"s": 16456,
"text": "Epoch 0 Cost = -0.12107406 Epoch 100 Cost = -0.24906836 Epoch 200 Cost = -0.2497198 Epoch 300 Cost = -0.24984348 Epoch 400 Cost = -0.24989356"
},
{
"code": null,
"e": 16627,
"s": 16598,
"text": "Now we plot our predictions:"
},
{
"code": null,
"e": 17287,
"s": 16627,
"text": "The plot below is based on the threshold 0.945. If I were to choose the conventional threshold 0.5 we would get all observations in one class. Why is that? The reason is that AUC is not sensitive to the bias value. Indeed, since in this model we subtracting pairwise activations, the bias value cancels out. We can add additional term to the cost function to bring the bias closer to 0.5. Or choose to do what we have done above, by hand-picking the threshold that works for us. I want to remind you, that we are optimizing for AUC, so if all observations are predicted to fall into a single class, it is cool with us as long as the AUC has the optimal value."
},
{
"code": null,
"e": 17711,
"s": 17287,
"text": "One can wonder if there is any usefulness in this approach for any real machine learning projects, other than data science competitions that use AUC as the evaluation criterion. But I would argue that it can be useful in case of unbalanced data set as the first step in machine learning. The second step would be to learn the bias parameter and generally fine-tuning the model by using a business-based optimization metric."
},
{
"code": null,
"e": 18109,
"s": 17711,
"text": "One disadvantage of the AUC cost function is that it is using pairwise comparison between observation, so the complexity of the function grows as a square of the number of observations, which could become a performance bottleneck as the number of observations grows. Also one has to come up with a good batching strategy that correctly estimates AUC based on a number of smaller samples (batches)."
}
] |
Assembly - CMPS Instruction
|
The CMPS instruction compares two strings. This instruction compares two data items of one byte, word or doubleword, pointed to by the DS:SI and ES:DI registers and sets the flags accordingly. You can also use the conditional jump instructions along with this instruction.
The following example demonstrates comparing two strings using the CMPS instruction −
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov esi, s1
mov edi, s2
mov ecx, lens2
cld
repe cmpsb
jecxz equal ;jump when ecx is zero
;If not equal then the following code
mov eax, 4
mov ebx, 1
mov ecx, msg_neq
mov edx, len_neq
int 80h
jmp exit
equal:
mov eax, 4
mov ebx, 1
mov ecx, msg_eq
mov edx, len_eq
int 80h
exit:
mov eax, 1
mov ebx, 0
int 80h
section .data
s1 db 'Hello, world!',0 ;our first string
lens1 equ $-s1
s2 db 'Hello, there!', 0 ;our second string
lens2 equ $-s2
msg_eq db 'Strings are equal!', 0xa
len_eq equ $-msg_eq
msg_neq db 'Strings are not equal!'
len_neq equ $-msg_neq
When the above code is compiled and executed, it produces the following result −
Strings are not equal!
46 Lectures
2 hours
Frahaan Hussain
23 Lectures
12 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2358,
"s": 2085,
"text": "The CMPS instruction compares two strings. This instruction compares two data items of one byte, word or doubleword, pointed to by the DS:SI and ES:DI registers and sets the flags accordingly. You can also use the conditional jump instructions along with this instruction."
},
{
"code": null,
"e": 2444,
"s": 2358,
"text": "The following example demonstrates comparing two strings using the CMPS instruction −"
},
{
"code": null,
"e": 3199,
"s": 2444,
"text": "section\t.text\n global _start ;must be declared for using gcc\n\t\n_start:\t;tell linker entry point\n mov esi, s1\n mov edi, s2\n mov ecx, lens2\n cld\n repe cmpsb\n jecxz equal ;jump when ecx is zero\n\n ;If not equal then the following code\n mov eax, 4\n mov ebx, 1\n mov ecx, msg_neq\n mov edx, len_neq\n int 80h\n jmp exit\n\t\nequal:\n mov eax, 4\n mov ebx, 1\n mov ecx, msg_eq\n mov edx, len_eq\n int 80h\n\t\nexit:\n mov eax, 1\n mov ebx, 0\n int 80h\n\t\nsection\t.data\ns1 db 'Hello, world!',0 ;our first string\nlens1 equ $-s1\n\ns2 db 'Hello, there!', 0 ;our second string\nlens2 equ $-s2\n\nmsg_eq db 'Strings are equal!', 0xa\nlen_eq equ $-msg_eq\n\nmsg_neq db 'Strings are not equal!'\nlen_neq equ $-msg_neq"
},
{
"code": null,
"e": 3280,
"s": 3199,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3304,
"s": 3280,
"text": "Strings are not equal!\n"
},
{
"code": null,
"e": 3337,
"s": 3304,
"text": "\n 46 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3354,
"s": 3337,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3388,
"s": 3354,
"text": "\n 23 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3396,
"s": 3388,
"text": " Uplatz"
},
{
"code": null,
"e": 3403,
"s": 3396,
"text": " Print"
},
{
"code": null,
"e": 3414,
"s": 3403,
"text": " Add Notes"
}
] |
CodeIgniter - Internationalization
|
The language class in CodeIgniter provides an easy way to support multiple languages for internationalization. To some extent, we can use different language files to display text in many different languages.
We can put different language files in application/language directory. System language files can be found at system/language directory, but to add your own language to your application, you should create a separate folder for each language in application/language directory.
To create a language file, you must end it with _lang.php. For example, you want to create a language file for French language, then you must save it with french_lang.php. Within this file you can store all your language texts in key, value combination in $lang array as shown below.
$lang[‘key’] = ‘val’;
To use any of the language in your application, you must first load the file of that particular language to retrieve various texts stored in that file. You can use the following code to load the language file.
$this->lang->load('filename', 'language');
filename − It is the name of file you want to load. Don’t use extension of file here but only name of file.
filename − It is the name of file you want to load. Don’t use extension of file here but only name of file.
Language − It is the language set containing it.
Language − It is the language set containing it.
To fetch a line from the language file simply execute the following code.
$this->lang->line('language_key');
Where language_key is the key parameter used to fetch value of the key in the loaded language file.
If you need some language globally, then you can autoload it in application/config/autoload.php file as shown below.
| -----------------------------------------------------------------------
| Auto-load Language files
| -----------------------------------------------------------------------
| Prototype:
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
Simply, pass the different languages to be autoloaded by CodeIgniter.
Create a controller called Lang_controller.php and save it in application/controller/Lang_controller.php
<?php
class Lang_controller extends CI_Controller {
public function index(){
//Load form helper
$this->load->helper('form');
//Get the selected language
$language = $this->input->post('language');
//Choose language file according to selected lanaguage
if($language == "french")
$this->lang->load('french_lang','french');
else if($language == "german")
$this->lang->load('german_lang','german');
else
$this->lang->load('english_lang','english');
//Fetch the message from language file.
$data['msg'] = $this->lang->line('msg');
$data['language'] = $language;
//Load the view file
$this->load->view('lang_view',$data);
}
}
?>
Create a view file called lang_view.php and save it at application/views/ lang_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Internationalization Example</title>
</head>
<body>
<?php
echo form_open('/lang');
?>
<select name = "language" onchange = "javascript:this.form.submit();">
<?php
$lang = array('english'=>"English",'french'=>"French",'german'=>"German");
foreach($lang as $key=>$val) {
if($key == $language)
echo "<option value = '".$key."' selected>".$val."</option>";
else
echo "<option value = '".$key."'>".$val."</option>";
}
?>
</select>
<br>
<?php
form_close();
echo $msg;
?>
</body>
</html>
Create three folders called English, French, and German in application/language as shown in the figure below.
Copy the below given code and save it in english_lang.php file in application/language/english folder.
<?php
$lang['msg'] = "CodeIgniter Internationalization example.";
?>
Copy the below given code and save it in french_lang.php file in application/language/French folder.
<?php
$lang['msg'] = "Exemple CodeIgniter internationalisation.";
?>
Copy the below given code and save it in german_lang.php file in application/language/german folder.
<?php
$lang['msg'] = "CodeIgniter Internationalisierung Beispiel.";
?>
Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file.
$route['lang'] = "Lang_controller";
Execute the following URL in the browser to execute the above example.
http://yoursite.com/index.php/lang
It will produce an output as shown in the following screenshot. If you change the language in the dropdown list, the language of the sentence written below the dropdown will also change accordingly.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2527,
"s": 2319,
"text": "The language class in CodeIgniter provides an easy way to support multiple languages for internationalization. To some extent, we can use different language files to display text in many different languages."
},
{
"code": null,
"e": 2802,
"s": 2527,
"text": "We can put different language files in application/language directory. System language files can be found at system/language directory, but to add your own language to your application, you should create a separate folder for each language in application/language directory."
},
{
"code": null,
"e": 3086,
"s": 2802,
"text": "To create a language file, you must end it with _lang.php. For example, you want to create a language file for French language, then you must save it with french_lang.php. Within this file you can store all your language texts in key, value combination in $lang array as shown below."
},
{
"code": null,
"e": 3109,
"s": 3086,
"text": "$lang[‘key’] = ‘val’;\n"
},
{
"code": null,
"e": 3319,
"s": 3109,
"text": "To use any of the language in your application, you must first load the file of that particular language to retrieve various texts stored in that file. You can use the following code to load the language file."
},
{
"code": null,
"e": 3363,
"s": 3319,
"text": "$this->lang->load('filename', 'language');\n"
},
{
"code": null,
"e": 3471,
"s": 3363,
"text": "filename − It is the name of file you want to load. Don’t use extension of file here but only name of file."
},
{
"code": null,
"e": 3579,
"s": 3471,
"text": "filename − It is the name of file you want to load. Don’t use extension of file here but only name of file."
},
{
"code": null,
"e": 3628,
"s": 3579,
"text": "Language − It is the language set containing it."
},
{
"code": null,
"e": 3677,
"s": 3628,
"text": "Language − It is the language set containing it."
},
{
"code": null,
"e": 3751,
"s": 3677,
"text": "To fetch a line from the language file simply execute the following code."
},
{
"code": null,
"e": 3787,
"s": 3751,
"text": "$this->lang->line('language_key');\n"
},
{
"code": null,
"e": 3887,
"s": 3787,
"text": "Where language_key is the key parameter used to fetch value of the key in the loaded language file."
},
{
"code": null,
"e": 4004,
"s": 3887,
"text": "If you need some language globally, then you can autoload it in application/config/autoload.php file as shown below."
},
{
"code": null,
"e": 4422,
"s": 4004,
"text": "| -----------------------------------------------------------------------\n| Auto-load Language files\n| -----------------------------------------------------------------------\n| Prototype:\n| $autoload['language'] = array('lang1', 'lang2');\n|\n| NOTE: Do not include the \"_lang\" part of your file. For example\n| \"codeigniter_lang.php\" would be referenced as array('codeigniter');\n|\n*/\n$autoload['language'] = array();"
},
{
"code": null,
"e": 4492,
"s": 4422,
"text": "Simply, pass the different languages to be autoloaded by CodeIgniter."
},
{
"code": null,
"e": 4597,
"s": 4492,
"text": "Create a controller called Lang_controller.php and save it in application/controller/Lang_controller.php"
},
{
"code": null,
"e": 5399,
"s": 4597,
"text": "<?php\n class Lang_controller extends CI_Controller {\n\n public function index(){\n //Load form helper\n $this->load->helper('form');\n\n //Get the selected language\n $language = $this->input->post('language');\n\t\t\n //Choose language file according to selected lanaguage\n if($language == \"french\")\n $this->lang->load('french_lang','french');\n else if($language == \"german\")\n $this->lang->load('german_lang','german');\n else\n $this->lang->load('english_lang','english');\n\t\t\n //Fetch the message from language file.\n $data['msg'] = $this->lang->line('msg');\n\t\t\n $data['language'] = $language;\n //Load the view file\n $this->load->view('lang_view',$data);\n }\n }\n?>"
},
{
"code": null,
"e": 5487,
"s": 5399,
"text": "Create a view file called lang_view.php and save it at application/views/ lang_view.php"
},
{
"code": null,
"e": 6293,
"s": 5487,
"text": "<!DOCTYPE html>\n<html lang = \"en\"> \n\n <head>\n <meta charset = \"utf-8\">\n <title>CodeIgniter Internationalization Example</title>\n </head>\n\t\n <body>\n <?php\n echo form_open('/lang');\n ?>\n\t\t\n <select name = \"language\" onchange = \"javascript:this.form.submit();\">\n <?php\n $lang = array('english'=>\"English\",'french'=>\"French\",'german'=>\"German\");\n\t\t\t\t\n foreach($lang as $key=>$val) {\n if($key == $language)\n echo \"<option value = '\".$key.\"' selected>\".$val.\"</option>\";\n else\n echo \"<option value = '\".$key.\"'>\".$val.\"</option>\";\n }\n\t\t\t\t\n ?>\n\t\t\t\n </select>\n\t\t\n <br>\n\t\t\n <?php\n form_close();\n echo $msg;\n ?>\n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 6403,
"s": 6293,
"text": "Create three folders called English, French, and German in application/language as shown in the figure below."
},
{
"code": null,
"e": 6506,
"s": 6403,
"text": "Copy the below given code and save it in english_lang.php file in application/language/english folder."
},
{
"code": null,
"e": 6578,
"s": 6506,
"text": "<?php\n $lang['msg'] = \"CodeIgniter Internationalization example.\";\n?>"
},
{
"code": null,
"e": 6679,
"s": 6578,
"text": "Copy the below given code and save it in french_lang.php file in application/language/French folder."
},
{
"code": null,
"e": 6751,
"s": 6679,
"text": "<?php\n $lang['msg'] = \"Exemple CodeIgniter internationalisation.\";\n?>"
},
{
"code": null,
"e": 6852,
"s": 6751,
"text": "Copy the below given code and save it in german_lang.php file in application/language/german folder."
},
{
"code": null,
"e": 6926,
"s": 6852,
"text": "<?php\n $lang['msg'] = \"CodeIgniter Internationalisierung Beispiel.\";\n?>"
},
{
"code": null,
"e": 7075,
"s": 6926,
"text": "Change the routes.php file in application/config/routes.php to add route for the above controller and add the following line at the end of the file."
},
{
"code": null,
"e": 7112,
"s": 7075,
"text": "$route['lang'] = \"Lang_controller\";\n"
},
{
"code": null,
"e": 7183,
"s": 7112,
"text": "Execute the following URL in the browser to execute the above example."
},
{
"code": null,
"e": 7219,
"s": 7183,
"text": "http://yoursite.com/index.php/lang\n"
},
{
"code": null,
"e": 7418,
"s": 7219,
"text": "It will produce an output as shown in the following screenshot. If you change the language in the dropdown list, the language of the sentence written below the dropdown will also change accordingly."
},
{
"code": null,
"e": 7425,
"s": 7418,
"text": " Print"
},
{
"code": null,
"e": 7436,
"s": 7425,
"text": " Add Notes"
}
] |
Ensemble Methods in Python - GeeksforGeeks
|
23 Nov, 2021
Ensemble means a group of elements viewed as a whole rather than individually. An Ensemble method creates multiple models and combines them to solve it. Ensemble methods help to improve the robustness/generalizability of the model. In this article, we will discuss some methods with their implementation in Python. For this, we choose a dataset from the UCI repository.
1. Averaging method: It is mainly used for regression problems. The method consists of building multiple models independently and returning the average of the prediction of all the models. In general, the combined output is better than an individual output because variance is reduced.
In the below example, three regression models (linear regression, xgboost, and random forest) are trained and their predictions are averaged. The final prediction output is pred_final.
Python3
# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionfrom sklearn.ensemble import RandomForestRegressorimport xgboost as xgbfrom sklearn.linear_model import LinearRegression # loading train data set in dataframe from train_data.csv filedf = pd.read_csv("train_data.csv") # getting target data from the dataframetarget = df["target"] # getting train data from the dataframetrain = df.drop("target") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing all the model objects with default parametersmodel_1 = LinearRegression()model_2 = xgb.XGBRegressor()model_3 = RandomForestRegressor() # training all the model on the training datasetmodel_1.fit(X_train, y_target)model_2.fit(X_train, y_target)model_3.fit(X_train, y_target) # predicting the output on the validation datasetpred_1 = model_1.predict(X_test)pred_2 = model_2.predict(X_test)pred_3 = model_3.predict(X_test) # final prediction after averaging on the prediction of all 3 modelspred_final = (pred_1+pred_2+pred_3)/3.0 # printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))
Output:
4560
2. Max voting: It is mainly used for classification problems. The method consists of building multiple models independently and getting their individual output called ‘vote’. The class with maximum votes is returned as output.
In the below example, three classification models (logistic regression, xgboost, and random forest) are combined using sklearn VotingClassifier, that model is trained and the class with maximum votes is returned as output. The final prediction output is pred_final. Please note it’s a classification, not regression, so the loss may be different from other types of ensemble methods.
Python
# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import log_loss # importing machine learning models for predictionfrom sklearn.ensemble import RandomForestClassifierfrom xgboost import XGBClassifierfrom sklearn.linear_model import LogisticRegression # importing voting classifierfrom sklearn.ensemble import VotingClassifier # loading train data set in dataframe from train_data.csv filedf = pd.read_csv("train_data.csv") # getting target data from the dataframetarget = df["Weekday"] # getting train data from the dataframetrain = df.drop("Weekday") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing all the model objects with default parametersmodel_1 = LogisticRegression()model_2 = XGBClassifier()model_3 = RandomForestClassifier() # Making the final model using voting classifierfinal_model = VotingClassifier( estimators=[('lr', model_1), ('xgb', model_2), ('rf', model_3)], voting='hard') # training all the model on the train datasetfinal_model.fit(X_train, y_train) # predicting the output on the test datasetpred_final = final_model.predict(X_test) # printing log loss between actual and predicted valueprint(log_loss(y_test, pred_final))
Output:
231
Let’s have a look at a bit more advanced ensemble methods
Ensemble methods are extensively used in classical machine learning. Examples of algorithms using bagging are random forest and bagging meta-estimator and examples of algorithms using boosting are GBM, XGBM, Adaboost, etc.
As a developer of a machine learning model, it is highly recommended to use ensemble methods. The ensemble methods are used extensively in almost all competitions and research papers.
1. Stacking: It is an ensemble method that combines multiple models (classification or regression) via meta-model (meta-classifier or meta-regression). The base models are trained on the complete dataset, then the meta-model is trained on features returned (as output) from base models. The base models in stacking are typically different. The meta-model helps to find the features from base models to achieve the best accuracy.
Algorithm:
Split the train dataset into n partsA base model (say linear regression) is fitted on n-1 parts and predictions are made for the nth part. This is done for each one of the n part of the train set.The base model is then fitted on the whole train dataset.This model is used to predict the test dataset.The Steps 2 to 4 are repeated for another base model which results in another set of predictions for the train and test dataset.The predictions on train data set are used as a feature to build the new model.This final model is used to make the predictions on test dataset
Split the train dataset into n parts
A base model (say linear regression) is fitted on n-1 parts and predictions are made for the nth part. This is done for each one of the n part of the train set.
The base model is then fitted on the whole train dataset.
This model is used to predict the test dataset.
The Steps 2 to 4 are repeated for another base model which results in another set of predictions for the train and test dataset.
The predictions on train data set are used as a feature to build the new model.
This final model is used to make the predictions on test dataset
Stacking is a bit different from the basic ensembling methods because it has first-level and second-level models. Stacking features are first extracted by training the dataset with all the first-level models. A first-level model is then using the train stacking features to train the model than this model predicts the final output with test stacking features.
Python3
# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionfrom sklearn.ensemble import RandomForestRegressorimport xgboost as xgbfrom sklearn.linear_model import LinearRegression # importing stacking libfrom vecstack import stacking # loading train data set in dataframe from train_data.csv filedf = pd.read_csv("train_data.csv") # getting target data from the dataframetarget = df["target"] # getting train data from the dataframetrain = df.drop("target") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing all the base model objects with default parametersmodel_1 = LinearRegression()model_2 = xgb.XGBRegressor()model_3 = RandomForestRegressor() # putting all base model objects in one listall_models = [model_1, model_2, model_3] # computing the stack featuress_train, s_test = stacking(all_models, X_train, X_test, y_train, regression=True, n_folds=4) # initializing the second-level modelfinal_model = model_1 # fitting the second level model with stack featuresfinal_model = final_model.fit(s_train, y_train) # predicting the final output using stackingpred_final = final_model.predict(X_test) # printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))
Output:
4510
2. Blending: It is similar to the stacking method explained above, but rather than using the whole dataset for training the base-models, a validation dataset is kept separate to make predictions.
Algorithm:
Split the training dataset into train, test and validation dataset.Fit all the base models using train dataset.Make predictions on validation and test dataset.These predictions are used as features to build a second level modelThis model is used to make predictions on test and meta-features
Split the training dataset into train, test and validation dataset.
Fit all the base models using train dataset.
Make predictions on validation and test dataset.
These predictions are used as features to build a second level model
This model is used to make predictions on test and meta-features
Python3
# importing utility modulesimport pandas as pdfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionfrom sklearn.ensemble import RandomForestRegressorimport xgboost as xgbfrom sklearn.linear_model import LinearRegression # importing train test splitfrom sklearn.model_selection import train_test_split # loading train data set in dataframe from train_data.csv filedf = pd.read_csv("train_data.csv") # getting target data from the dataframetarget = df["target"] # getting train data from the dataframetrain = df.drop("target") #Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split(train, target, test_size=0.20) # performing the train test and validation splittrain_ratio = 0.70validation_ratio = 0.20test_ratio = 0.10 # performing train test splitx_train, x_test, y_train, y_test = train_test_split( train, target, test_size=1 - train_ratio) # performing test validation splitx_val, x_test, y_val, y_test = train_test_split( x_test, y_test, test_size=test_ratio/(test_ratio + validation_ratio)) # initializing all the base model objects with default parametersmodel_1 = LinearRegression()model_2 = xgb.XGBRegressor()model_3 = RandomForestRegressor() # training all the model on the train dataset # training first modelmodel_1.fit(x_train, y_train)val_pred_1 = model_1.predict(x_val)test_pred_1 = model_1.predict(x_test) # converting to dataframeval_pred_1 = pd.DataFrame(val_pred_1)test_pred_1 = pd.DataFrame(test_pred_1) # training second modelmodel_2.fit(x_train, y_train)val_pred_2 = model_2.predict(x_val)test_pred_2 = model_2.predict(x_test) # converting to dataframeval_pred_2 = pd.DataFrame(val_pred_2)test_pred_2 = pd.DataFrame(test_pred_2) # training third modelmodel_3.fit(x_train, y_train)val_pred_3 = model_1.predict(x_val)test_pred_3 = model_1.predict(x_test) # converting to dataframeval_pred_3 = pd.DataFrame(val_pred_3)test_pred_3 = pd.DataFrame(test_pred_3) # concatenating validation dataset along with all the predicted validation data (meta features)df_val = pd.concat([x_val, val_pred_1, val_pred_2, val_pred_3], axis=1)df_test = pd.concat([x_test, test_pred_1, test_pred_2, test_pred_3], axis=1) # making the final model using the meta featuresfinal_model = LinearRegression()final_model.fit(df_val, y_val) # getting the final outputfinal_pred = final_model.predict(df_test) #printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))
Output:
4790
3. Bagging: It is also known as a bootstrapping method. Base models are run on bags to get a fair distribution of the whole dataset. A bag is a subset of the dataset along with a replacement to make the size of the bag the same as the whole dataset. The final output is formed after combining the output of all base models.
Algorithm:
Create multiple datasets from the train dataset by selecting observations with replacementsRun a base model on each of the created datasets independentlyCombine the predictions of all the base models to each the final output
Create multiple datasets from the train dataset by selecting observations with replacements
Run a base model on each of the created datasets independently
Combine the predictions of all the base models to each the final output
Bagging normally uses only one base model (XGBoost Regressor used in the code below).
Python
# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionimport xgboost as xgb # importing bagging modulefrom sklearn.ensemble import BaggingRegressor # loading train data set in dataframe from train_data.csv filedf = pd.read_csv("train_data.csv") # getting target data from the dataframetarget = df["target"] # getting train data from the dataframetrain = df.drop("target") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing the bagging model using XGboost as base model with default parametersmodel = BaggingRegressor(base_estimator=xgb.XGBRegressor()) # training modelmodel.fit(X_train, y_train) # predicting the output on the test datasetpred = model.predict(X_test) # printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))
Output:
4666
4. Boosting: Boosting is a sequential method–it aims to prevent a wrong base model from affecting the final output. Instead of combing the base models, the method focuses on building a new model that is dependent on the previous one. A new model tries to remove the errors made by its previous one. Each of these models is called weak learners. The final model (aka strong learner) is formed by getting the weighted mean of all the weak learners.
Algorithm:
Take a subset of the train dataset.Train a base model on that dataset.Use third model to make predictions on the whole dataset.Calculate errors using the predicted values and actual values.Initialize all data points with same weight.Assign higher weight to incorrectly predicted data points.Make another model, make predictions using the new model in such a way that errors made by the previous model are mitigated/corrected.Similarly, create multiple models–each successive model correcting the errors of the previous model.The final model (strong learner) is the weighted mean of all the previous models (weak learners).
Take a subset of the train dataset.
Train a base model on that dataset.
Use third model to make predictions on the whole dataset.
Calculate errors using the predicted values and actual values.
Initialize all data points with same weight.
Assign higher weight to incorrectly predicted data points.
Make another model, make predictions using the new model in such a way that errors made by the previous model are mitigated/corrected.
Similarly, create multiple models–each successive model correcting the errors of the previous model.
The final model (strong learner) is the weighted mean of all the previous models (weak learners).
Python3
# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionfrom sklearn.ensemble import GradientBoostingRegressor # loading train data set in dataframe from train_data.csv filedf = pd.read_csv("train_data.csv") # getting target data from the dataframetarget = df["target"] # getting train data from the dataframetrain = df.drop("target") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing the boosting module with default parametersmodel = GradientBoostingRegressor() # training the model on the train datasetmodel.fit(X_train, y_train) # predicting the output on the test datasetpred_final = model.predict(X_test) # printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))
Output:
4789
Note: The scikit-learn provides several modules/methods for ensemble methods. Please note the accuracy of a method does not suggest one method is superior to another. The article aims to give a brief introduction to ensemble methods–not to compare between them. The programmer must use a method that suits the data.
gabaa406
arorakashish0911
sumitgumber28
punamsingh628700
Picked
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Difference between Informed and Uninformed Search in AI
Normalization vs Standardization
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": 24344,
"s": 24316,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 24714,
"s": 24344,
"text": "Ensemble means a group of elements viewed as a whole rather than individually. An Ensemble method creates multiple models and combines them to solve it. Ensemble methods help to improve the robustness/generalizability of the model. In this article, we will discuss some methods with their implementation in Python. For this, we choose a dataset from the UCI repository."
},
{
"code": null,
"e": 25000,
"s": 24714,
"text": "1. Averaging method: It is mainly used for regression problems. The method consists of building multiple models independently and returning the average of the prediction of all the models. In general, the combined output is better than an individual output because variance is reduced."
},
{
"code": null,
"e": 25185,
"s": 25000,
"text": "In the below example, three regression models (linear regression, xgboost, and random forest) are trained and their predictions are averaged. The final prediction output is pred_final."
},
{
"code": null,
"e": 25193,
"s": 25185,
"text": "Python3"
},
{
"code": "# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionfrom sklearn.ensemble import RandomForestRegressorimport xgboost as xgbfrom sklearn.linear_model import LinearRegression # loading train data set in dataframe from train_data.csv filedf = pd.read_csv(\"train_data.csv\") # getting target data from the dataframetarget = df[\"target\"] # getting train data from the dataframetrain = df.drop(\"target\") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing all the model objects with default parametersmodel_1 = LinearRegression()model_2 = xgb.XGBRegressor()model_3 = RandomForestRegressor() # training all the model on the training datasetmodel_1.fit(X_train, y_target)model_2.fit(X_train, y_target)model_3.fit(X_train, y_target) # predicting the output on the validation datasetpred_1 = model_1.predict(X_test)pred_2 = model_2.predict(X_test)pred_3 = model_3.predict(X_test) # final prediction after averaging on the prediction of all 3 modelspred_final = (pred_1+pred_2+pred_3)/3.0 # printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))",
"e": 26553,
"s": 25193,
"text": null
},
{
"code": null,
"e": 26561,
"s": 26553,
"text": "Output:"
},
{
"code": null,
"e": 26566,
"s": 26561,
"text": "4560"
},
{
"code": null,
"e": 26794,
"s": 26566,
"text": "2. Max voting: It is mainly used for classification problems. The method consists of building multiple models independently and getting their individual output called ‘vote’. The class with maximum votes is returned as output. "
},
{
"code": null,
"e": 27178,
"s": 26794,
"text": "In the below example, three classification models (logistic regression, xgboost, and random forest) are combined using sklearn VotingClassifier, that model is trained and the class with maximum votes is returned as output. The final prediction output is pred_final. Please note it’s a classification, not regression, so the loss may be different from other types of ensemble methods."
},
{
"code": null,
"e": 27185,
"s": 27178,
"text": "Python"
},
{
"code": "# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import log_loss # importing machine learning models for predictionfrom sklearn.ensemble import RandomForestClassifierfrom xgboost import XGBClassifierfrom sklearn.linear_model import LogisticRegression # importing voting classifierfrom sklearn.ensemble import VotingClassifier # loading train data set in dataframe from train_data.csv filedf = pd.read_csv(\"train_data.csv\") # getting target data from the dataframetarget = df[\"Weekday\"] # getting train data from the dataframetrain = df.drop(\"Weekday\") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing all the model objects with default parametersmodel_1 = LogisticRegression()model_2 = XGBClassifier()model_3 = RandomForestClassifier() # Making the final model using voting classifierfinal_model = VotingClassifier( estimators=[('lr', model_1), ('xgb', model_2), ('rf', model_3)], voting='hard') # training all the model on the train datasetfinal_model.fit(X_train, y_train) # predicting the output on the test datasetpred_final = final_model.predict(X_test) # printing log loss between actual and predicted valueprint(log_loss(y_test, pred_final))",
"e": 28527,
"s": 27185,
"text": null
},
{
"code": null,
"e": 28535,
"s": 28527,
"text": "Output:"
},
{
"code": null,
"e": 28539,
"s": 28535,
"text": "231"
},
{
"code": null,
"e": 28597,
"s": 28539,
"text": "Let’s have a look at a bit more advanced ensemble methods"
},
{
"code": null,
"e": 28821,
"s": 28597,
"text": "Ensemble methods are extensively used in classical machine learning. Examples of algorithms using bagging are random forest and bagging meta-estimator and examples of algorithms using boosting are GBM, XGBM, Adaboost, etc. "
},
{
"code": null,
"e": 29005,
"s": 28821,
"text": "As a developer of a machine learning model, it is highly recommended to use ensemble methods. The ensemble methods are used extensively in almost all competitions and research papers."
},
{
"code": null,
"e": 29434,
"s": 29005,
"text": "1. Stacking: It is an ensemble method that combines multiple models (classification or regression) via meta-model (meta-classifier or meta-regression). The base models are trained on the complete dataset, then the meta-model is trained on features returned (as output) from base models. The base models in stacking are typically different. The meta-model helps to find the features from base models to achieve the best accuracy."
},
{
"code": null,
"e": 29445,
"s": 29434,
"text": "Algorithm:"
},
{
"code": null,
"e": 30017,
"s": 29445,
"text": "Split the train dataset into n partsA base model (say linear regression) is fitted on n-1 parts and predictions are made for the nth part. This is done for each one of the n part of the train set.The base model is then fitted on the whole train dataset.This model is used to predict the test dataset.The Steps 2 to 4 are repeated for another base model which results in another set of predictions for the train and test dataset.The predictions on train data set are used as a feature to build the new model.This final model is used to make the predictions on test dataset"
},
{
"code": null,
"e": 30054,
"s": 30017,
"text": "Split the train dataset into n parts"
},
{
"code": null,
"e": 30215,
"s": 30054,
"text": "A base model (say linear regression) is fitted on n-1 parts and predictions are made for the nth part. This is done for each one of the n part of the train set."
},
{
"code": null,
"e": 30273,
"s": 30215,
"text": "The base model is then fitted on the whole train dataset."
},
{
"code": null,
"e": 30321,
"s": 30273,
"text": "This model is used to predict the test dataset."
},
{
"code": null,
"e": 30450,
"s": 30321,
"text": "The Steps 2 to 4 are repeated for another base model which results in another set of predictions for the train and test dataset."
},
{
"code": null,
"e": 30530,
"s": 30450,
"text": "The predictions on train data set are used as a feature to build the new model."
},
{
"code": null,
"e": 30595,
"s": 30530,
"text": "This final model is used to make the predictions on test dataset"
},
{
"code": null,
"e": 30956,
"s": 30595,
"text": "Stacking is a bit different from the basic ensembling methods because it has first-level and second-level models. Stacking features are first extracted by training the dataset with all the first-level models. A first-level model is then using the train stacking features to train the model than this model predicts the final output with test stacking features."
},
{
"code": null,
"e": 30964,
"s": 30956,
"text": "Python3"
},
{
"code": "# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionfrom sklearn.ensemble import RandomForestRegressorimport xgboost as xgbfrom sklearn.linear_model import LinearRegression # importing stacking libfrom vecstack import stacking # loading train data set in dataframe from train_data.csv filedf = pd.read_csv(\"train_data.csv\") # getting target data from the dataframetarget = df[\"target\"] # getting train data from the dataframetrain = df.drop(\"target\") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing all the base model objects with default parametersmodel_1 = LinearRegression()model_2 = xgb.XGBRegressor()model_3 = RandomForestRegressor() # putting all base model objects in one listall_models = [model_1, model_2, model_3] # computing the stack featuress_train, s_test = stacking(all_models, X_train, X_test, y_train, regression=True, n_folds=4) # initializing the second-level modelfinal_model = model_1 # fitting the second level model with stack featuresfinal_model = final_model.fit(s_train, y_train) # predicting the final output using stackingpred_final = final_model.predict(X_test) # printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))",
"e": 32469,
"s": 30964,
"text": null
},
{
"code": null,
"e": 32477,
"s": 32469,
"text": "Output:"
},
{
"code": null,
"e": 32483,
"s": 32477,
"text": "4510 "
},
{
"code": null,
"e": 32680,
"s": 32483,
"text": "2. Blending: It is similar to the stacking method explained above, but rather than using the whole dataset for training the base-models, a validation dataset is kept separate to make predictions. "
},
{
"code": null,
"e": 32692,
"s": 32680,
"text": "Algorithm: "
},
{
"code": null,
"e": 32984,
"s": 32692,
"text": "Split the training dataset into train, test and validation dataset.Fit all the base models using train dataset.Make predictions on validation and test dataset.These predictions are used as features to build a second level modelThis model is used to make predictions on test and meta-features"
},
{
"code": null,
"e": 33052,
"s": 32984,
"text": "Split the training dataset into train, test and validation dataset."
},
{
"code": null,
"e": 33097,
"s": 33052,
"text": "Fit all the base models using train dataset."
},
{
"code": null,
"e": 33146,
"s": 33097,
"text": "Make predictions on validation and test dataset."
},
{
"code": null,
"e": 33215,
"s": 33146,
"text": "These predictions are used as features to build a second level model"
},
{
"code": null,
"e": 33280,
"s": 33215,
"text": "This model is used to make predictions on test and meta-features"
},
{
"code": null,
"e": 33288,
"s": 33280,
"text": "Python3"
},
{
"code": "# importing utility modulesimport pandas as pdfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionfrom sklearn.ensemble import RandomForestRegressorimport xgboost as xgbfrom sklearn.linear_model import LinearRegression # importing train test splitfrom sklearn.model_selection import train_test_split # loading train data set in dataframe from train_data.csv filedf = pd.read_csv(\"train_data.csv\") # getting target data from the dataframetarget = df[\"target\"] # getting train data from the dataframetrain = df.drop(\"target\") #Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split(train, target, test_size=0.20) # performing the train test and validation splittrain_ratio = 0.70validation_ratio = 0.20test_ratio = 0.10 # performing train test splitx_train, x_test, y_train, y_test = train_test_split( train, target, test_size=1 - train_ratio) # performing test validation splitx_val, x_test, y_val, y_test = train_test_split( x_test, y_test, test_size=test_ratio/(test_ratio + validation_ratio)) # initializing all the base model objects with default parametersmodel_1 = LinearRegression()model_2 = xgb.XGBRegressor()model_3 = RandomForestRegressor() # training all the model on the train dataset # training first modelmodel_1.fit(x_train, y_train)val_pred_1 = model_1.predict(x_val)test_pred_1 = model_1.predict(x_test) # converting to dataframeval_pred_1 = pd.DataFrame(val_pred_1)test_pred_1 = pd.DataFrame(test_pred_1) # training second modelmodel_2.fit(x_train, y_train)val_pred_2 = model_2.predict(x_val)test_pred_2 = model_2.predict(x_test) # converting to dataframeval_pred_2 = pd.DataFrame(val_pred_2)test_pred_2 = pd.DataFrame(test_pred_2) # training third modelmodel_3.fit(x_train, y_train)val_pred_3 = model_1.predict(x_val)test_pred_3 = model_1.predict(x_test) # converting to dataframeval_pred_3 = pd.DataFrame(val_pred_3)test_pred_3 = pd.DataFrame(test_pred_3) # concatenating validation dataset along with all the predicted validation data (meta features)df_val = pd.concat([x_val, val_pred_1, val_pred_2, val_pred_3], axis=1)df_test = pd.concat([x_test, test_pred_1, test_pred_2, test_pred_3], axis=1) # making the final model using the meta featuresfinal_model = LinearRegression()final_model.fit(df_val, y_val) # getting the final outputfinal_pred = final_model.predict(df_test) #printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))",
"e": 35820,
"s": 33288,
"text": null
},
{
"code": null,
"e": 35829,
"s": 35820,
"text": " Output:"
},
{
"code": null,
"e": 35835,
"s": 35829,
"text": "4790 "
},
{
"code": null,
"e": 36160,
"s": 35835,
"text": "3. Bagging: It is also known as a bootstrapping method. Base models are run on bags to get a fair distribution of the whole dataset. A bag is a subset of the dataset along with a replacement to make the size of the bag the same as the whole dataset. The final output is formed after combining the output of all base models. "
},
{
"code": null,
"e": 36171,
"s": 36160,
"text": "Algorithm:"
},
{
"code": null,
"e": 36396,
"s": 36171,
"text": "Create multiple datasets from the train dataset by selecting observations with replacementsRun a base model on each of the created datasets independentlyCombine the predictions of all the base models to each the final output"
},
{
"code": null,
"e": 36488,
"s": 36396,
"text": "Create multiple datasets from the train dataset by selecting observations with replacements"
},
{
"code": null,
"e": 36551,
"s": 36488,
"text": "Run a base model on each of the created datasets independently"
},
{
"code": null,
"e": 36623,
"s": 36551,
"text": "Combine the predictions of all the base models to each the final output"
},
{
"code": null,
"e": 36709,
"s": 36623,
"text": "Bagging normally uses only one base model (XGBoost Regressor used in the code below)."
},
{
"code": null,
"e": 36716,
"s": 36709,
"text": "Python"
},
{
"code": "# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionimport xgboost as xgb # importing bagging modulefrom sklearn.ensemble import BaggingRegressor # loading train data set in dataframe from train_data.csv filedf = pd.read_csv(\"train_data.csv\") # getting target data from the dataframetarget = df[\"target\"] # getting train data from the dataframetrain = df.drop(\"target\") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing the bagging model using XGboost as base model with default parametersmodel = BaggingRegressor(base_estimator=xgb.XGBRegressor()) # training modelmodel.fit(X_train, y_train) # predicting the output on the test datasetpred = model.predict(X_test) # printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))",
"e": 37766,
"s": 36716,
"text": null
},
{
"code": null,
"e": 37774,
"s": 37766,
"text": "Output:"
},
{
"code": null,
"e": 37780,
"s": 37774,
"text": "4666 "
},
{
"code": null,
"e": 38228,
"s": 37780,
"text": "4. Boosting: Boosting is a sequential method–it aims to prevent a wrong base model from affecting the final output. Instead of combing the base models, the method focuses on building a new model that is dependent on the previous one. A new model tries to remove the errors made by its previous one. Each of these models is called weak learners. The final model (aka strong learner) is formed by getting the weighted mean of all the weak learners. "
},
{
"code": null,
"e": 38239,
"s": 38228,
"text": "Algorithm:"
},
{
"code": null,
"e": 38862,
"s": 38239,
"text": "Take a subset of the train dataset.Train a base model on that dataset.Use third model to make predictions on the whole dataset.Calculate errors using the predicted values and actual values.Initialize all data points with same weight.Assign higher weight to incorrectly predicted data points.Make another model, make predictions using the new model in such a way that errors made by the previous model are mitigated/corrected.Similarly, create multiple models–each successive model correcting the errors of the previous model.The final model (strong learner) is the weighted mean of all the previous models (weak learners)."
},
{
"code": null,
"e": 38898,
"s": 38862,
"text": "Take a subset of the train dataset."
},
{
"code": null,
"e": 38934,
"s": 38898,
"text": "Train a base model on that dataset."
},
{
"code": null,
"e": 38992,
"s": 38934,
"text": "Use third model to make predictions on the whole dataset."
},
{
"code": null,
"e": 39055,
"s": 38992,
"text": "Calculate errors using the predicted values and actual values."
},
{
"code": null,
"e": 39100,
"s": 39055,
"text": "Initialize all data points with same weight."
},
{
"code": null,
"e": 39159,
"s": 39100,
"text": "Assign higher weight to incorrectly predicted data points."
},
{
"code": null,
"e": 39294,
"s": 39159,
"text": "Make another model, make predictions using the new model in such a way that errors made by the previous model are mitigated/corrected."
},
{
"code": null,
"e": 39395,
"s": 39294,
"text": "Similarly, create multiple models–each successive model correcting the errors of the previous model."
},
{
"code": null,
"e": 39493,
"s": 39395,
"text": "The final model (strong learner) is the weighted mean of all the previous models (weak learners)."
},
{
"code": null,
"e": 39501,
"s": 39493,
"text": "Python3"
},
{
"code": "# importing utility modulesimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error # importing machine learning models for predictionfrom sklearn.ensemble import GradientBoostingRegressor # loading train data set in dataframe from train_data.csv filedf = pd.read_csv(\"train_data.csv\") # getting target data from the dataframetarget = df[\"target\"] # getting train data from the dataframetrain = df.drop(\"target\") # Splitting between train data into training and validation datasetX_train, X_test, y_train, y_test = train_test_split( train, target, test_size=0.20) # initializing the boosting module with default parametersmodel = GradientBoostingRegressor() # training the model on the train datasetmodel.fit(X_train, y_train) # predicting the output on the test datasetpred_final = model.predict(X_test) # printing the root mean squared error between real value and predicted valueprint(mean_squared_error(y_test, pred_final))",
"e": 40493,
"s": 39501,
"text": null
},
{
"code": null,
"e": 40501,
"s": 40493,
"text": "Output:"
},
{
"code": null,
"e": 40507,
"s": 40501,
"text": "4789 "
},
{
"code": null,
"e": 40823,
"s": 40507,
"text": "Note: The scikit-learn provides several modules/methods for ensemble methods. Please note the accuracy of a method does not suggest one method is superior to another. The article aims to give a brief introduction to ensemble methods–not to compare between them. The programmer must use a method that suits the data."
},
{
"code": null,
"e": 40832,
"s": 40823,
"text": "gabaa406"
},
{
"code": null,
"e": 40849,
"s": 40832,
"text": "arorakashish0911"
},
{
"code": null,
"e": 40863,
"s": 40849,
"text": "sumitgumber28"
},
{
"code": null,
"e": 40880,
"s": 40863,
"text": "punamsingh628700"
},
{
"code": null,
"e": 40887,
"s": 40880,
"text": "Picked"
},
{
"code": null,
"e": 40904,
"s": 40887,
"text": "Machine Learning"
},
{
"code": null,
"e": 40911,
"s": 40904,
"text": "Python"
},
{
"code": null,
"e": 40928,
"s": 40911,
"text": "Machine Learning"
},
{
"code": null,
"e": 41026,
"s": 40928,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41059,
"s": 41026,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 41098,
"s": 41059,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 41133,
"s": 41098,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 41189,
"s": 41133,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 41222,
"s": 41189,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 41250,
"s": 41222,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 41300,
"s": 41250,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 41322,
"s": 41300,
"text": "Python map() function"
}
] |
How to create Multiline TextBox in C#?
|
29 Nov, 2019
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to create a multiline TextBox which stores multiple lines of the content using Multiline property of the TextBox. Set the value of this property to true from multiline TextBox, otherwise set false. The default value of this property is false. In Windows form, you can set this property in two different ways:
1. Design-Time: It is the simplest way to set the Multiline property of the TextBox as shown in the following steps:
Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the TextBox control to set the Multiline property of the TextBox.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Multiline property of the TextBox programmatically with the help of given syntax:
public override bool Multiline { get; set; }
Here, the value of this property is of System.Boolean type. Following steps are used to set the Multiline property of the TextBox:
Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox
TextBox Mytextbox = new TextBox();
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2 : After creating TextBox, set the Multiline property of the TextBox provided by the TextBox class.// Set Multiline property
Mytextbox.Multiline = true;
// Set Multiline property
Mytextbox.Multiline = true;
Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form
this.Controls.Add(Mytextbox);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Introduction"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.Height = 140; Mytextbox.Width = 200; Mytextbox.Name = "text_box1"; Mytextbox.Multiline = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:
// Add this textbox to form
this.Controls.Add(Mytextbox);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Introduction"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.Height = 140; Mytextbox.Width = 200; Mytextbox.Name = "text_box1"; Mytextbox.Multiline = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 535,
"s": 28,
"text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to create a multiline TextBox which stores multiple lines of the content using Multiline property of the TextBox. Set the value of this property to true from multiline TextBox, otherwise set false. The default value of this property is false. In Windows form, you can set this property in two different ways:"
},
{
"code": null,
"e": 652,
"s": 535,
"text": "1. Design-Time: It is the simplest way to set the Multiline property of the TextBox as shown in the following steps:"
},
{
"code": null,
"e": 740,
"s": 652,
"text": "Step 1: Create a windows form.Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 898,
"s": 740,
"text": "Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need."
},
{
"code": null,
"e": 1032,
"s": 898,
"text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the Multiline property of the TextBox.Output:"
},
{
"code": null,
"e": 1040,
"s": 1032,
"text": "Output:"
},
{
"code": null,
"e": 1218,
"s": 1040,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Multiline property of the TextBox programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1263,
"s": 1218,
"text": "public override bool Multiline { get; set; }"
},
{
"code": null,
"e": 1394,
"s": 1263,
"text": "Here, the value of this property is of System.Boolean type. Following steps are used to set the Multiline property of the TextBox:"
},
{
"code": null,
"e": 1538,
"s": 1394,
"text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 1594,
"s": 1538,
"text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 1754,
"s": 1594,
"text": "Step 2 : After creating TextBox, set the Multiline property of the TextBox provided by the TextBox class.// Set Multiline property\nMytextbox.Multiline = true;\n"
},
{
"code": null,
"e": 1809,
"s": 1754,
"text": "// Set Multiline property\nMytextbox.Multiline = true;\n"
},
{
"code": null,
"e": 3123,
"s": 1809,
"text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Introduction\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.Height = 140; Mytextbox.Width = 200; Mytextbox.Name = \"text_box1\"; Mytextbox.Multiline = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:"
},
{
"code": null,
"e": 3182,
"s": 3123,
"text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox);\n"
},
{
"code": null,
"e": 3191,
"s": 3182,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Introduction\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.Height = 140; Mytextbox.Width = 200; Mytextbox.Name = \"text_box1\"; Mytextbox.Multiline = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}",
"e": 4362,
"s": 3191,
"text": null
},
{
"code": null,
"e": 4370,
"s": 4362,
"text": "Output:"
},
{
"code": null,
"e": 4401,
"s": 4370,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 4404,
"s": 4401,
"text": "C#"
}
] |
Circle Sort - GeeksforGeeks
|
13 Feb, 2018
Circle sort algorithm can be visualized by drawing concentric circles on an array of integers. The elements of the array lying on the same circle diametrically opposite to each other are compared and if found in the wrong order they are swapped. This goes on in a recursive fashion in which the array is divided into sub-arrays on which the above process is repeated until we get pairs of sorted elements which when put together form a sorted array.
In short below two steps are repeated while there are swap operations involved in the steps.
Compare the first element to the last element, then the second element to the second last element, etc.
Then split the array in two and recurse until there is only one single element in the array.
It can be better explained by the image below.
Below is the implementation of above algorithm.
// CPP implementation of Circle Sort#include<bits/stdc++.h>using namespace std; // Function to perform circular swaps recursively// This function returns true if there was a swap// operation performed.bool circleSortRec(int a[], int low, int high){ bool swapped = false; // base case if (low == high) return false; // storing the upper and lower bounds // of list to be used later in the // recursive case int lo = low, hi = high; while (lo < hi) { // swaps the pair of elements // if true if (a[lo] > a[hi]) { swap(a[lo], a[hi]); swapped = true; } lo++; hi--; } // special case arises only for list // of odd size if (lo == hi) if (a[lo] > a[hi + 1]) { swap(a[low], a[hi+1]); swapped = true; } // recursive case to check the // traverse lists as sub lists int mid = (high - low) / 2; bool firstHalf = circleSortRec(a, low, low+mid); bool secondHalf = circleSortRec(a, low+mid+1, high); return swapped || firstHalf || secondHalf;} // This function mainly calls circleSortRecvoid circleSort(int a[], int n){ // Keep calling circleSortRec while // there is a swap operation. while (circleSortRec(a, 0, n-1)) { ; }} // Driver programint main(){ int a[] = {7, 5, 3, 1, 2, 4, 6, 8}; int n = sizeof(a)/sizeof(a[0]); printf("\nUnsorted : "); for (int i=0; i<n; i++) cout << a[i] << " "; circleSort(a, n); printf("\nSorted : "); for (int i=0; i<n; i++) cout << a[i] << " "; return 0;}
Output :
Unsorted : [6, 5, 3, 1, 8, 7, 2, 4]
Sorted : [1, 2, 3, 4, 5, 6, 7, 8]
References :SourceForge
This article is contributed by Palash Nigam . 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.
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Program for QuickSort
Stability in sorting algorithms
Quick Sort vs Merge Sort
Check if two arrays are equal or not
Sorting in Java
Quickselect Algorithm
QuickSort using Random Pivoting
Program to check if an array is sorted or not (Iterative and Recursive)
Longest Common Prefix using Sorting
Sort a nearly sorted (or K sorted) array
|
[
{
"code": null,
"e": 23998,
"s": 23970,
"text": "\n13 Feb, 2018"
},
{
"code": null,
"e": 24448,
"s": 23998,
"text": "Circle sort algorithm can be visualized by drawing concentric circles on an array of integers. The elements of the array lying on the same circle diametrically opposite to each other are compared and if found in the wrong order they are swapped. This goes on in a recursive fashion in which the array is divided into sub-arrays on which the above process is repeated until we get pairs of sorted elements which when put together form a sorted array."
},
{
"code": null,
"e": 24541,
"s": 24448,
"text": "In short below two steps are repeated while there are swap operations involved in the steps."
},
{
"code": null,
"e": 24645,
"s": 24541,
"text": "Compare the first element to the last element, then the second element to the second last element, etc."
},
{
"code": null,
"e": 24738,
"s": 24645,
"text": "Then split the array in two and recurse until there is only one single element in the array."
},
{
"code": null,
"e": 24785,
"s": 24738,
"text": "It can be better explained by the image below."
},
{
"code": null,
"e": 24833,
"s": 24785,
"text": "Below is the implementation of above algorithm."
},
{
"code": "// CPP implementation of Circle Sort#include<bits/stdc++.h>using namespace std; // Function to perform circular swaps recursively// This function returns true if there was a swap// operation performed.bool circleSortRec(int a[], int low, int high){ bool swapped = false; // base case if (low == high) return false; // storing the upper and lower bounds // of list to be used later in the // recursive case int lo = low, hi = high; while (lo < hi) { // swaps the pair of elements // if true if (a[lo] > a[hi]) { swap(a[lo], a[hi]); swapped = true; } lo++; hi--; } // special case arises only for list // of odd size if (lo == hi) if (a[lo] > a[hi + 1]) { swap(a[low], a[hi+1]); swapped = true; } // recursive case to check the // traverse lists as sub lists int mid = (high - low) / 2; bool firstHalf = circleSortRec(a, low, low+mid); bool secondHalf = circleSortRec(a, low+mid+1, high); return swapped || firstHalf || secondHalf;} // This function mainly calls circleSortRecvoid circleSort(int a[], int n){ // Keep calling circleSortRec while // there is a swap operation. while (circleSortRec(a, 0, n-1)) { ; }} // Driver programint main(){ int a[] = {7, 5, 3, 1, 2, 4, 6, 8}; int n = sizeof(a)/sizeof(a[0]); printf(\"\\nUnsorted : \"); for (int i=0; i<n; i++) cout << a[i] << \" \"; circleSort(a, n); printf(\"\\nSorted : \"); for (int i=0; i<n; i++) cout << a[i] << \" \"; return 0;}",
"e": 26470,
"s": 24833,
"text": null
},
{
"code": null,
"e": 26479,
"s": 26470,
"text": "Output :"
},
{
"code": null,
"e": 26552,
"s": 26479,
"text": "Unsorted : [6, 5, 3, 1, 8, 7, 2, 4]\nSorted : [1, 2, 3, 4, 5, 6, 7, 8]\n"
},
{
"code": null,
"e": 26576,
"s": 26552,
"text": "References :SourceForge"
},
{
"code": null,
"e": 26877,
"s": 26576,
"text": "This article is contributed by Palash Nigam . 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."
},
{
"code": null,
"e": 27002,
"s": 26877,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27010,
"s": 27002,
"text": "Sorting"
},
{
"code": null,
"e": 27018,
"s": 27010,
"text": "Sorting"
},
{
"code": null,
"e": 27116,
"s": 27018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27125,
"s": 27116,
"text": "Comments"
},
{
"code": null,
"e": 27138,
"s": 27125,
"text": "Old Comments"
},
{
"code": null,
"e": 27164,
"s": 27138,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27196,
"s": 27164,
"text": "Stability in sorting algorithms"
},
{
"code": null,
"e": 27221,
"s": 27196,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 27258,
"s": 27221,
"text": "Check if two arrays are equal or not"
},
{
"code": null,
"e": 27274,
"s": 27258,
"text": "Sorting in Java"
},
{
"code": null,
"e": 27296,
"s": 27274,
"text": "Quickselect Algorithm"
},
{
"code": null,
"e": 27328,
"s": 27296,
"text": "QuickSort using Random Pivoting"
},
{
"code": null,
"e": 27400,
"s": 27328,
"text": "Program to check if an array is sorted or not (Iterative and Recursive)"
},
{
"code": null,
"e": 27436,
"s": 27400,
"text": "Longest Common Prefix using Sorting"
}
] |
Java - String equalsIgnoreCase() Method
|
This method compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case, if they are of the same length, and corresponding characters in the two strings are equal ignoring case.
Here is the syntax of this method −
public boolean equalsIgnoreCase(String anotherString)
Here is the detail of parameters −
anotherString − the String to compare this String against.
anotherString − the String to compare this String against.
This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
public class Test {
public static void main(String args[]) {
String Str1 = new String("This is really not immutable!!");
String Str2 = Str1;
String Str3 = new String("This is really not immutable!!");
String Str4 = new String("This IS REALLY NOT IMMUTABLE!!");
boolean retVal;
retVal = Str1.equals( Str2 );
System.out.println("Returned Value = " + retVal );
retVal = Str1.equals( Str3 );
System.out.println("Returned Value = " + retVal );
retVal = Str1.equalsIgnoreCase( Str4 );
System.out.println("Returned Value = " + retVal );
}
}
This will produce the following result −
Returned Value = true
Returned Value = true
Returned Value = true
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": 2612,
"s": 2377,
"text": "This method compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case, if they are of the same length, and corresponding characters in the two strings are equal ignoring case."
},
{
"code": null,
"e": 2648,
"s": 2612,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2703,
"s": 2648,
"text": "public boolean equalsIgnoreCase(String anotherString)\n"
},
{
"code": null,
"e": 2738,
"s": 2703,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2797,
"s": 2738,
"text": "anotherString − the String to compare this String against."
},
{
"code": null,
"e": 2856,
"s": 2797,
"text": "anotherString − the String to compare this String against."
},
{
"code": null,
"e": 2968,
"s": 2856,
"text": "This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise."
},
{
"code": null,
"e": 3080,
"s": 2968,
"text": "This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise."
},
{
"code": null,
"e": 3690,
"s": 3080,
"text": "public class Test {\n\n public static void main(String args[]) {\n String Str1 = new String(\"This is really not immutable!!\");\n String Str2 = Str1;\n String Str3 = new String(\"This is really not immutable!!\");\n String Str4 = new String(\"This IS REALLY NOT IMMUTABLE!!\");\n boolean retVal;\n\n retVal = Str1.equals( Str2 );\n System.out.println(\"Returned Value = \" + retVal );\n\n retVal = Str1.equals( Str3 );\n System.out.println(\"Returned Value = \" + retVal );\n\n retVal = Str1.equalsIgnoreCase( Str4 );\n System.out.println(\"Returned Value = \" + retVal );\n }\n}"
},
{
"code": null,
"e": 3731,
"s": 3690,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3798,
"s": 3731,
"text": "Returned Value = true\nReturned Value = true\nReturned Value = true\n"
},
{
"code": null,
"e": 3831,
"s": 3798,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3847,
"s": 3831,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3880,
"s": 3847,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3896,
"s": 3880,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3931,
"s": 3896,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3945,
"s": 3931,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3979,
"s": 3945,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3993,
"s": 3979,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4030,
"s": 3993,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4045,
"s": 4030,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4078,
"s": 4045,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4097,
"s": 4078,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4104,
"s": 4097,
"text": " Print"
},
{
"code": null,
"e": 4115,
"s": 4104,
"text": " Add Notes"
}
] |
Mapping Avocado Prices in Python. Photo by Peter de Vink from Pexels | by Craig Dickson | Towards Data Science
|
I love avocados. They’re tasty and healthy and I enjoy eating them. I know that makes me a basic cliche millenial, but the heart wants what the heart wants! When I came across the Avocado Prices dataset posted by Justin Kiggins on Kaggle, I immediately wanted to have a look at it and play with it. This contains information about avocado sales in the United States between 2015 and 2018, compiled by the Hass Avocado Board.
There’s a lot of good information contained in this dataset, and I could have chosen a few different things to explore (and perhaps I still will later on). I’d seen some cool choropleth maps on twitter and wanted to try my hand at that. I saw that each price observation was tied to a particular region, and I decided to see if I could get that information from text form into map form somehow.
In this post I’ll take you step by step through how I did it, and you can find my complete Jupyter Notebook containing the code here. This was my first attempt at making this kind of map using Python, so I welcome all feedback and ideas on how I could have made this process easier on myself!
Let’s get into it! The first thing I did was import my libraries and import the data itself. Using pd.read_csv() creates a pandas DataFrame directly from our CSV file.
import pandas as pdimport geopandas as gpdimport matplotlib.pyplot as pltdata = pd.read_csv('avocado.csv', index_col = 'Date')
This gives us a nice DataFrame.
But that’s too much information for us just now. I want to make a map including price and region data (and perhaps later do something with volume and year), so let’s drop a lot of these columns.
columns_to_drop = ['Unnamed: 0', '4046', '4225', '4770', 'Total Bags', 'Small Bags', 'Large Bags', 'XLarge Bags', 'type']avo_df = data.drop(columns_to_drop, axis=1)
Nice! That’s more streamlined. Doing some Exploratory Data Analysis gave me an idea of the dataset I was looking at, the maximum price for an avocado in the dataset was $3.25(!) — the cheapest was $0.44 — more than 7 times cheaper. That’s some variation! The median price for a single avocado in our dataset was $1.37, the mean $1.41 and the standard deviation was $0.40. This gives an idea of the distribution of prices in the data.
It’s always helpful to do some EDA visually. Here is a histogram of the AveragePrice column to give us a clearer sense of the overall distribution.
To make the map that I want to make (a choropleth showing the price of an avocado in each region, to clearly show regional variations in price), I want to collapse the many different price measurements into one value for each region. It could be interesting to explore differences year-on-year, or by volume (who buys the most avocados?), but to answer the question I’ve set myself, I want to squash this all down.
There are a few options here, but I think the clearest and most honest way to do this is to take a simple mean of all AveragePrice data, grouped by region. How do we do that?
First, we need to identify all the regions.
regions = avo_df.region.unique()
This give us a list of all the regions contained in the dataset:
['Albany' 'Atlanta' 'BaltimoreWashington' 'Boise' 'Boston' 'BuffaloRochester' 'California' 'Charlotte' 'Chicago' 'CincinnatiDayton' 'Columbus' 'DallasFtWorth' 'Denver' 'Detroit' 'GrandRapids' 'GreatLakes' 'HarrisburgScranton' 'HartfordSpringfield' 'Houston' 'Indianapolis' 'Jacksonville' 'LasVegas' 'LosAngeles' 'Louisville' 'MiamiFtLauderdale' 'Midsouth' 'Nashville' 'NewOrleansMobile' 'NewYork' 'Northeast' 'NorthernNewEngland' 'Orlando' 'Philadelphia' 'PhoenixTucson' 'Pittsburgh' 'Plains' 'Portland' 'RaleighGreensboro' 'RichmondNorfolk' 'Roanoke' 'Sacramento' 'SanDiego' 'SanFrancisco' 'Seattle' 'SouthCarolina' 'SouthCentral' 'Southeast' 'Spokane' 'StLouis' 'Syracuse' 'Tampa' 'TotalUS' 'West' 'WestTexNewMexico']
Now we want to use this list to group our DataFrame and get down to one AveragePrice value per region-
group_by_region = avo_df.groupby(by=['region'])avo_df_avg = group_by_region.mean()avo_df_avg = avo_df_avg.drop(['year'], axis=1)
That should do the trick.
Now we have one price value per region, but each region is stored as text, e.g. ‘Albany’, ‘SanDiego’, ‘Roanoke’ etc. Matplotlib is smart, but not yet smart enough to plot those on a map just based on the text. We need to find a way to get geographical data (specifically, co-ordinates) from those region names.
Well, we are not the first people to want to do this! We can use the geocode feature of GeoPy to do exactly that. After playing with this for a while I went with Bing Maps (it was free to get an API Key, and I could get it to work!), but there are other geocoding services available, so feel free to try it with those.
from geopy.geocoders import Bingfrom geopy.extra.rate_limiter import RateLimitergeolocator = Bing(api_key='GetYourOwnAPIKeyYouScallywag', timeout=30)geocode = RateLimiter(geolocator.geocode, min_delay_seconds=2)regions_dict = {i : geolocator.geocode(i) for i in regions}
I found using the RateLimiter useful to not overload the API with too many requests, but it significantly increases the time for the request to run and might not be necessary for you, so bear that in mind.
This returns a dictionary full of information, from which we just want the co-ordinates. We can convert this to a DataFrame ready to join to our existing DataFrame using the following steps:
regions_df = pd.DataFrame(regions_dict)regions_df_melted = regions_df.iloc[1:2,:].melt()regions_df_melted.columns = ['region', 'co-ordinates']
Here is the head of the DataFrame which results.
Now we have the co-ordinates for each region in our dataset, we want to join this to our existing DataFrame so we have one DataFrame which contains the average price and the co-ordinates for each region. Happily, pandas makes this extremely easy using its merge function. Thanks, pandas!
df = pd.merge(avo_df_avg, regions_df_melted, left_on='region', right_on='region')
Our next step is to bring this all together and create a GeoPandas GeoDataFrame which contains our average price for each region, plus the geographic information we need to plot each are on our map. To do that we first need to create a column for latitude and one for longitude (GeoPandas, very reasonably, wants to have that information to create its ‘geometry’ column, which is its way of storing the geodata).
df[['latitude', 'longitude']] = pd.DataFrame(df['co-ordinates'].tolist(), index=df.index)avo_gdf = gpd.GeoDataFrame( df, geometry=gpd.points_from_xy(df.longitude, df.latitude))
Great! Now we’ve got a GeoDataFrame with all our data. Let’s take a quick look to see how it looks!
avo_gdf.plot()
OK — I’ll admit this doesn’t look too inspiring yet, but I promise you, we’re getting there! If you squint you can see that the majority of the data does kind of look like it could be in the United States. We have one outlier way down in the bottom right, which will be explained and dealt with shortly.
But for now, onwards!
As we saw above, just getting our GeoDataFrame did not lead to the immediate production of the beautiful choropleth of our dreams. We need to give Python (and Matplotlib) instructions on how we want to present that information. After all, we’re the Data Analysts, we’re making the decisions on how to present our data and there’s a huge range of ways we might choose to do so. This flexibility means we still have some work to do!
So, we want to superimpose our GeoDataFrame of avocado prices onto a map of the continental United States. How can we do that? There is a very useful Python library called shapely that can help us here. mattymecks has a super helpful post about all of this stuff here — I strongly recommend giving the whole post a read if you’re trying to get your head around this.
A Shape file stores a shape as a polygon, which is simply a series of co-ordinates, each connected to the next. So a triangle would be saved as 3 points identified by their co-ordinates, a square by 4, and more complex shapes by thousands or more points.
Anyway, for our purposes you just need to know that Shape files exist and can provide us the map that we are seeking. But where to find the best ones? Of course the best way is with some Furious GooglingTM, but I can perhaps save you some pain and point you to the TIGER/Line Shapefiles offered by the US Census Bureau. If those guys don’t know what the shapes of the US States, Territories and Dominions look like, then I don’t know who would!
Download those files, unzip them and keep all of them in your active folder. Then import Point and Polygon from Shapely and you’re ready to rock!
from shapely.geometry import Point, Polygonusa = gpd.read_file('tl_2017_us_state.shp')
OK, let’s take a look at that bad boy.
usa.plot()
We can see here the foundations of what we need. Now why does this map have so much white space? I thought the USA was just in the Western Hemisphere? Well, without getting into too much geopolitical detail here, let’s just say there is some territory which belongs to the United States of America that is in other geographical locations than would first come to mind.
Let’s take a closer look at our Shape data here.
print(usa.shape)print(usa.NAME)----(56, 15)0 West Virginia1 Florida2 Illinois3 Minnesota4 Maryland5 Rhode Island6 Idaho7 New Hampshire8 North Carolina9 Vermont10 Connecticut11 Delaware12 New Mexico13 California14 New Jersey15 Wisconsin16 Oregon17 Nebraska18 Pennsylvania19 Washington20 Louisiana21 Georgia22 Alabama23 Utah24 Ohio25 Texas26 Colorado27 South Carolina28 Oklahoma29 Tennessee30 Wyoming31 Hawaii32 North Dakota33 Kentucky34 United States Virgin Islands35 Commonwealth of the Northern Mariana Islands36 Guam37 Maine38 New York39 Nevada40 Alaska41 American Samoa42 Michigan43 Arkansas44 Mississippi45 Missouri46 Montana47 Kansas48 Indiana49 Puerto Rico50 South Dakota51 Massachusetts52 Virginia53 District of Columbia54 Iowa55 ArizonaName: NAME, dtype: object
We already confirmed that our avocado price data is confined to the continental United States (except for that one weird outlier, which I promise we’re getting to), so we can get rid of some of these other entries.
to_drop = ['Commonwealth of the Northern Mariana Islands', 'United States Virgin Islands', 'Hawaii', 'Alaska', 'Guam', 'Puerto Rico', 'American Samoa']for index, row in usa.iterrows(): if row['NAME'] in to_drop : usa.drop(index, inplace=True)usa.plot()
Now we have the Shape files for the US ready to form the basis of our map, and we have our price data geographically located and ready to go. But, there were a few weird things going on, specifically with that outlier on our map a few steps back. Now it’s time to investigate that and do some sanity checks on our data.
If we display our whole DataFrame (it’s too big to do here, but if you’re following along at home, I’d encourage you to do it), we can see that some of our co-ordinates are NaNs (e.g. entry 25 — Midsouth), some are suspiciously round (e.g. entry 29 — Northeast), and some are way off (e.g. entry 52 — West — this was our outlier on the map!). What’s happening here is that our original CSV file from the Hass Avocado Board (by way of Justin Kiggens) contains some meta-region summary data for some over-arching regions (such as Midsouth, Northeast and West).
When we used our geolocator (in our case Bing Maps, but this problem would have happened whichever service we used), the service tried its best to provide an accurate location. In some cases (like Midsouth) it wasn’t able to, so we ended up with NaN. In others (like Northeast) it found something very general and went with that. In yet others (such as West) it was able to locate somewhere with that name, but not the place we were looking for (in this case it returned the co-ordinates for Western, Zambia). This is why it’s important to check your data where possible by plotting it in different ways and investigating things that look suspicious.
For our purposes, we don’t need this meta-region data, so we can just get rid of it en masse.
to_drop = ['Midsouth', 'Northeast', 'Plains', 'SouthCentral', 'Southeast', 'TotalUS', 'West']for index, row in avo_gdf.iterrows(): if row['region'] in to_drop : df.drop(index, inplace=True)
Now that we’ve improved df, our DataFrame, and we have our shapefile saved as usa, let’s put these together using the same CRS — Co-ordinate Reference System. This will ensure that our GeoDataFrames use the same reference system, so as long as the co-ordinates for each of our regions are accurate, they will be accurately represented on the US map. Here I used epsg:4326, as that’s what the Shapefile was already using.
crs = {'init': 'epsg:4326'}avo_gdf = gpd.GeoDataFrame(df, crs=crs)usa_gdf = gpd.GeoDataFrame(usa, crs=crs)
This is it! We’re ready to go!
With the help of a few nice features from Matplotlib we can make this very beautiful indeed.
from mpl_toolkits.axes_grid1 import make_axes_locatable # This is a function to allow us to make the legend prettyfig, ax = plt.subplots(figsize = (20,16)) plt.title('Avocado Prices by region in the United States', fontsize=26, fontfamily='serif')#this part makes the legend the same size as our map, for prettinessdivider = make_axes_locatable(ax)cax = divider.append_axes("right", size="5%", pad=0.1)usa.boundary.plot(ax=ax, color='DarkSlateBlue') # using the boundary method here to get the outlines of the states, an aesthetic decisionavo_gdf.plot(cmap='Greens', column='AveragePrice', legend=True, ax=ax, s=2000, alpha=0.7, cax=cax)# this saves a copy of the viz as a jpg so we can easily share it with our friends on twitter!plt.savefig('Avocado Prices.jpg', format='jpg')
Now we have made real the beautiful choropleth that until now existed only in our dreams! Congratulations to us! It looks like we want to avoid the built-up Northeastern USA and San Francisco, and instead head down to Ohio or Texas to live that cheap avocado dream.
I hope this helped you to see how we can use some powerful tools in GeoPandas, GeoPy and Matplotlib to take data in text and number form, use an API to find the co-ordinates, and then create an appealing and clear visualisation to show people at a glance the information we want to highlight.
Thanks very much for taking the time to come with me on this journey. I always welcome your feedback — please get in touch with me on Twitter at @craigdoesdata and let me know how I could have done this more effectively! I am very much still learning and I want to learn your secrets too, so please share them with me.
Again, the whole Jupyter Notebook and associated files are available on my Github page, and I encourage you to play around with them.
Until next time!
|
[
{
"code": null,
"e": 597,
"s": 172,
"text": "I love avocados. They’re tasty and healthy and I enjoy eating them. I know that makes me a basic cliche millenial, but the heart wants what the heart wants! When I came across the Avocado Prices dataset posted by Justin Kiggins on Kaggle, I immediately wanted to have a look at it and play with it. This contains information about avocado sales in the United States between 2015 and 2018, compiled by the Hass Avocado Board."
},
{
"code": null,
"e": 992,
"s": 597,
"text": "There’s a lot of good information contained in this dataset, and I could have chosen a few different things to explore (and perhaps I still will later on). I’d seen some cool choropleth maps on twitter and wanted to try my hand at that. I saw that each price observation was tied to a particular region, and I decided to see if I could get that information from text form into map form somehow."
},
{
"code": null,
"e": 1285,
"s": 992,
"text": "In this post I’ll take you step by step through how I did it, and you can find my complete Jupyter Notebook containing the code here. This was my first attempt at making this kind of map using Python, so I welcome all feedback and ideas on how I could have made this process easier on myself!"
},
{
"code": null,
"e": 1453,
"s": 1285,
"text": "Let’s get into it! The first thing I did was import my libraries and import the data itself. Using pd.read_csv() creates a pandas DataFrame directly from our CSV file."
},
{
"code": null,
"e": 1580,
"s": 1453,
"text": "import pandas as pdimport geopandas as gpdimport matplotlib.pyplot as pltdata = pd.read_csv('avocado.csv', index_col = 'Date')"
},
{
"code": null,
"e": 1612,
"s": 1580,
"text": "This gives us a nice DataFrame."
},
{
"code": null,
"e": 1807,
"s": 1612,
"text": "But that’s too much information for us just now. I want to make a map including price and region data (and perhaps later do something with volume and year), so let’s drop a lot of these columns."
},
{
"code": null,
"e": 1972,
"s": 1807,
"text": "columns_to_drop = ['Unnamed: 0', '4046', '4225', '4770', 'Total Bags', 'Small Bags', 'Large Bags', 'XLarge Bags', 'type']avo_df = data.drop(columns_to_drop, axis=1)"
},
{
"code": null,
"e": 2406,
"s": 1972,
"text": "Nice! That’s more streamlined. Doing some Exploratory Data Analysis gave me an idea of the dataset I was looking at, the maximum price for an avocado in the dataset was $3.25(!) — the cheapest was $0.44 — more than 7 times cheaper. That’s some variation! The median price for a single avocado in our dataset was $1.37, the mean $1.41 and the standard deviation was $0.40. This gives an idea of the distribution of prices in the data."
},
{
"code": null,
"e": 2554,
"s": 2406,
"text": "It’s always helpful to do some EDA visually. Here is a histogram of the AveragePrice column to give us a clearer sense of the overall distribution."
},
{
"code": null,
"e": 2969,
"s": 2554,
"text": "To make the map that I want to make (a choropleth showing the price of an avocado in each region, to clearly show regional variations in price), I want to collapse the many different price measurements into one value for each region. It could be interesting to explore differences year-on-year, or by volume (who buys the most avocados?), but to answer the question I’ve set myself, I want to squash this all down."
},
{
"code": null,
"e": 3144,
"s": 2969,
"text": "There are a few options here, but I think the clearest and most honest way to do this is to take a simple mean of all AveragePrice data, grouped by region. How do we do that?"
},
{
"code": null,
"e": 3188,
"s": 3144,
"text": "First, we need to identify all the regions."
},
{
"code": null,
"e": 3221,
"s": 3188,
"text": "regions = avo_df.region.unique()"
},
{
"code": null,
"e": 3286,
"s": 3221,
"text": "This give us a list of all the regions contained in the dataset:"
},
{
"code": null,
"e": 4006,
"s": 3286,
"text": "['Albany' 'Atlanta' 'BaltimoreWashington' 'Boise' 'Boston' 'BuffaloRochester' 'California' 'Charlotte' 'Chicago' 'CincinnatiDayton' 'Columbus' 'DallasFtWorth' 'Denver' 'Detroit' 'GrandRapids' 'GreatLakes' 'HarrisburgScranton' 'HartfordSpringfield' 'Houston' 'Indianapolis' 'Jacksonville' 'LasVegas' 'LosAngeles' 'Louisville' 'MiamiFtLauderdale' 'Midsouth' 'Nashville' 'NewOrleansMobile' 'NewYork' 'Northeast' 'NorthernNewEngland' 'Orlando' 'Philadelphia' 'PhoenixTucson' 'Pittsburgh' 'Plains' 'Portland' 'RaleighGreensboro' 'RichmondNorfolk' 'Roanoke' 'Sacramento' 'SanDiego' 'SanFrancisco' 'Seattle' 'SouthCarolina' 'SouthCentral' 'Southeast' 'Spokane' 'StLouis' 'Syracuse' 'Tampa' 'TotalUS' 'West' 'WestTexNewMexico']"
},
{
"code": null,
"e": 4109,
"s": 4006,
"text": "Now we want to use this list to group our DataFrame and get down to one AveragePrice value per region-"
},
{
"code": null,
"e": 4238,
"s": 4109,
"text": "group_by_region = avo_df.groupby(by=['region'])avo_df_avg = group_by_region.mean()avo_df_avg = avo_df_avg.drop(['year'], axis=1)"
},
{
"code": null,
"e": 4264,
"s": 4238,
"text": "That should do the trick."
},
{
"code": null,
"e": 4575,
"s": 4264,
"text": "Now we have one price value per region, but each region is stored as text, e.g. ‘Albany’, ‘SanDiego’, ‘Roanoke’ etc. Matplotlib is smart, but not yet smart enough to plot those on a map just based on the text. We need to find a way to get geographical data (specifically, co-ordinates) from those region names."
},
{
"code": null,
"e": 4894,
"s": 4575,
"text": "Well, we are not the first people to want to do this! We can use the geocode feature of GeoPy to do exactly that. After playing with this for a while I went with Bing Maps (it was free to get an API Key, and I could get it to work!), but there are other geocoding services available, so feel free to try it with those."
},
{
"code": null,
"e": 5165,
"s": 4894,
"text": "from geopy.geocoders import Bingfrom geopy.extra.rate_limiter import RateLimitergeolocator = Bing(api_key='GetYourOwnAPIKeyYouScallywag', timeout=30)geocode = RateLimiter(geolocator.geocode, min_delay_seconds=2)regions_dict = {i : geolocator.geocode(i) for i in regions}"
},
{
"code": null,
"e": 5371,
"s": 5165,
"text": "I found using the RateLimiter useful to not overload the API with too many requests, but it significantly increases the time for the request to run and might not be necessary for you, so bear that in mind."
},
{
"code": null,
"e": 5562,
"s": 5371,
"text": "This returns a dictionary full of information, from which we just want the co-ordinates. We can convert this to a DataFrame ready to join to our existing DataFrame using the following steps:"
},
{
"code": null,
"e": 5705,
"s": 5562,
"text": "regions_df = pd.DataFrame(regions_dict)regions_df_melted = regions_df.iloc[1:2,:].melt()regions_df_melted.columns = ['region', 'co-ordinates']"
},
{
"code": null,
"e": 5754,
"s": 5705,
"text": "Here is the head of the DataFrame which results."
},
{
"code": null,
"e": 6042,
"s": 5754,
"text": "Now we have the co-ordinates for each region in our dataset, we want to join this to our existing DataFrame so we have one DataFrame which contains the average price and the co-ordinates for each region. Happily, pandas makes this extremely easy using its merge function. Thanks, pandas!"
},
{
"code": null,
"e": 6124,
"s": 6042,
"text": "df = pd.merge(avo_df_avg, regions_df_melted, left_on='region', right_on='region')"
},
{
"code": null,
"e": 6537,
"s": 6124,
"text": "Our next step is to bring this all together and create a GeoPandas GeoDataFrame which contains our average price for each region, plus the geographic information we need to plot each are on our map. To do that we first need to create a column for latitude and one for longitude (GeoPandas, very reasonably, wants to have that information to create its ‘geometry’ column, which is its way of storing the geodata)."
},
{
"code": null,
"e": 6717,
"s": 6537,
"text": "df[['latitude', 'longitude']] = pd.DataFrame(df['co-ordinates'].tolist(), index=df.index)avo_gdf = gpd.GeoDataFrame( df, geometry=gpd.points_from_xy(df.longitude, df.latitude))"
},
{
"code": null,
"e": 6817,
"s": 6717,
"text": "Great! Now we’ve got a GeoDataFrame with all our data. Let’s take a quick look to see how it looks!"
},
{
"code": null,
"e": 6832,
"s": 6817,
"text": "avo_gdf.plot()"
},
{
"code": null,
"e": 7136,
"s": 6832,
"text": "OK — I’ll admit this doesn’t look too inspiring yet, but I promise you, we’re getting there! If you squint you can see that the majority of the data does kind of look like it could be in the United States. We have one outlier way down in the bottom right, which will be explained and dealt with shortly."
},
{
"code": null,
"e": 7158,
"s": 7136,
"text": "But for now, onwards!"
},
{
"code": null,
"e": 7589,
"s": 7158,
"text": "As we saw above, just getting our GeoDataFrame did not lead to the immediate production of the beautiful choropleth of our dreams. We need to give Python (and Matplotlib) instructions on how we want to present that information. After all, we’re the Data Analysts, we’re making the decisions on how to present our data and there’s a huge range of ways we might choose to do so. This flexibility means we still have some work to do!"
},
{
"code": null,
"e": 7956,
"s": 7589,
"text": "So, we want to superimpose our GeoDataFrame of avocado prices onto a map of the continental United States. How can we do that? There is a very useful Python library called shapely that can help us here. mattymecks has a super helpful post about all of this stuff here — I strongly recommend giving the whole post a read if you’re trying to get your head around this."
},
{
"code": null,
"e": 8211,
"s": 7956,
"text": "A Shape file stores a shape as a polygon, which is simply a series of co-ordinates, each connected to the next. So a triangle would be saved as 3 points identified by their co-ordinates, a square by 4, and more complex shapes by thousands or more points."
},
{
"code": null,
"e": 8656,
"s": 8211,
"text": "Anyway, for our purposes you just need to know that Shape files exist and can provide us the map that we are seeking. But where to find the best ones? Of course the best way is with some Furious GooglingTM, but I can perhaps save you some pain and point you to the TIGER/Line Shapefiles offered by the US Census Bureau. If those guys don’t know what the shapes of the US States, Territories and Dominions look like, then I don’t know who would!"
},
{
"code": null,
"e": 8802,
"s": 8656,
"text": "Download those files, unzip them and keep all of them in your active folder. Then import Point and Polygon from Shapely and you’re ready to rock!"
},
{
"code": null,
"e": 8889,
"s": 8802,
"text": "from shapely.geometry import Point, Polygonusa = gpd.read_file('tl_2017_us_state.shp')"
},
{
"code": null,
"e": 8928,
"s": 8889,
"text": "OK, let’s take a look at that bad boy."
},
{
"code": null,
"e": 8939,
"s": 8928,
"text": "usa.plot()"
},
{
"code": null,
"e": 9308,
"s": 8939,
"text": "We can see here the foundations of what we need. Now why does this map have so much white space? I thought the USA was just in the Western Hemisphere? Well, without getting into too much geopolitical detail here, let’s just say there is some territory which belongs to the United States of America that is in other geographical locations than would first come to mind."
},
{
"code": null,
"e": 9357,
"s": 9308,
"text": "Let’s take a closer look at our Shape data here."
},
{
"code": null,
"e": 12226,
"s": 9357,
"text": "print(usa.shape)print(usa.NAME)----(56, 15)0 West Virginia1 Florida2 Illinois3 Minnesota4 Maryland5 Rhode Island6 Idaho7 New Hampshire8 North Carolina9 Vermont10 Connecticut11 Delaware12 New Mexico13 California14 New Jersey15 Wisconsin16 Oregon17 Nebraska18 Pennsylvania19 Washington20 Louisiana21 Georgia22 Alabama23 Utah24 Ohio25 Texas26 Colorado27 South Carolina28 Oklahoma29 Tennessee30 Wyoming31 Hawaii32 North Dakota33 Kentucky34 United States Virgin Islands35 Commonwealth of the Northern Mariana Islands36 Guam37 Maine38 New York39 Nevada40 Alaska41 American Samoa42 Michigan43 Arkansas44 Mississippi45 Missouri46 Montana47 Kansas48 Indiana49 Puerto Rico50 South Dakota51 Massachusetts52 Virginia53 District of Columbia54 Iowa55 ArizonaName: NAME, dtype: object"
},
{
"code": null,
"e": 12441,
"s": 12226,
"text": "We already confirmed that our avocado price data is confined to the continental United States (except for that one weird outlier, which I promise we’re getting to), so we can get rid of some of these other entries."
},
{
"code": null,
"e": 12704,
"s": 12441,
"text": "to_drop = ['Commonwealth of the Northern Mariana Islands', 'United States Virgin Islands', 'Hawaii', 'Alaska', 'Guam', 'Puerto Rico', 'American Samoa']for index, row in usa.iterrows(): if row['NAME'] in to_drop : usa.drop(index, inplace=True)usa.plot()"
},
{
"code": null,
"e": 13024,
"s": 12704,
"text": "Now we have the Shape files for the US ready to form the basis of our map, and we have our price data geographically located and ready to go. But, there were a few weird things going on, specifically with that outlier on our map a few steps back. Now it’s time to investigate that and do some sanity checks on our data."
},
{
"code": null,
"e": 13583,
"s": 13024,
"text": "If we display our whole DataFrame (it’s too big to do here, but if you’re following along at home, I’d encourage you to do it), we can see that some of our co-ordinates are NaNs (e.g. entry 25 — Midsouth), some are suspiciously round (e.g. entry 29 — Northeast), and some are way off (e.g. entry 52 — West — this was our outlier on the map!). What’s happening here is that our original CSV file from the Hass Avocado Board (by way of Justin Kiggens) contains some meta-region summary data for some over-arching regions (such as Midsouth, Northeast and West)."
},
{
"code": null,
"e": 14234,
"s": 13583,
"text": "When we used our geolocator (in our case Bing Maps, but this problem would have happened whichever service we used), the service tried its best to provide an accurate location. In some cases (like Midsouth) it wasn’t able to, so we ended up with NaN. In others (like Northeast) it found something very general and went with that. In yet others (such as West) it was able to locate somewhere with that name, but not the place we were looking for (in this case it returned the co-ordinates for Western, Zambia). This is why it’s important to check your data where possible by plotting it in different ways and investigating things that look suspicious."
},
{
"code": null,
"e": 14328,
"s": 14234,
"text": "For our purposes, we don’t need this meta-region data, so we can just get rid of it en masse."
},
{
"code": null,
"e": 14528,
"s": 14328,
"text": "to_drop = ['Midsouth', 'Northeast', 'Plains', 'SouthCentral', 'Southeast', 'TotalUS', 'West']for index, row in avo_gdf.iterrows(): if row['region'] in to_drop : df.drop(index, inplace=True)"
},
{
"code": null,
"e": 14949,
"s": 14528,
"text": "Now that we’ve improved df, our DataFrame, and we have our shapefile saved as usa, let’s put these together using the same CRS — Co-ordinate Reference System. This will ensure that our GeoDataFrames use the same reference system, so as long as the co-ordinates for each of our regions are accurate, they will be accurately represented on the US map. Here I used epsg:4326, as that’s what the Shapefile was already using."
},
{
"code": null,
"e": 15056,
"s": 14949,
"text": "crs = {'init': 'epsg:4326'}avo_gdf = gpd.GeoDataFrame(df, crs=crs)usa_gdf = gpd.GeoDataFrame(usa, crs=crs)"
},
{
"code": null,
"e": 15087,
"s": 15056,
"text": "This is it! We’re ready to go!"
},
{
"code": null,
"e": 15180,
"s": 15087,
"text": "With the help of a few nice features from Matplotlib we can make this very beautiful indeed."
},
{
"code": null,
"e": 15959,
"s": 15180,
"text": "from mpl_toolkits.axes_grid1 import make_axes_locatable # This is a function to allow us to make the legend prettyfig, ax = plt.subplots(figsize = (20,16)) plt.title('Avocado Prices by region in the United States', fontsize=26, fontfamily='serif')#this part makes the legend the same size as our map, for prettinessdivider = make_axes_locatable(ax)cax = divider.append_axes(\"right\", size=\"5%\", pad=0.1)usa.boundary.plot(ax=ax, color='DarkSlateBlue') # using the boundary method here to get the outlines of the states, an aesthetic decisionavo_gdf.plot(cmap='Greens', column='AveragePrice', legend=True, ax=ax, s=2000, alpha=0.7, cax=cax)# this saves a copy of the viz as a jpg so we can easily share it with our friends on twitter!plt.savefig('Avocado Prices.jpg', format='jpg')"
},
{
"code": null,
"e": 16225,
"s": 15959,
"text": "Now we have made real the beautiful choropleth that until now existed only in our dreams! Congratulations to us! It looks like we want to avoid the built-up Northeastern USA and San Francisco, and instead head down to Ohio or Texas to live that cheap avocado dream."
},
{
"code": null,
"e": 16518,
"s": 16225,
"text": "I hope this helped you to see how we can use some powerful tools in GeoPandas, GeoPy and Matplotlib to take data in text and number form, use an API to find the co-ordinates, and then create an appealing and clear visualisation to show people at a glance the information we want to highlight."
},
{
"code": null,
"e": 16837,
"s": 16518,
"text": "Thanks very much for taking the time to come with me on this journey. I always welcome your feedback — please get in touch with me on Twitter at @craigdoesdata and let me know how I could have done this more effectively! I am very much still learning and I want to learn your secrets too, so please share them with me."
},
{
"code": null,
"e": 16971,
"s": 16837,
"text": "Again, the whole Jupyter Notebook and associated files are available on my Github page, and I encourage you to play around with them."
}
] |
Online JSON Minifier
|
Editable JSON Code
12345678910111213141516{"Company": {"Employee": {"FirstName": "Tanmay","LastName": "Patil","ContactNo": "1234567890","Email": "tanmaypatil@xyz.com","Address": {"City": "Bangalore","State": "Karnataka","Zip": "560212"}}}}X
Privacy Policy
Cookies Policy
Terms of Use
|
[
{
"code": null,
"e": 19,
"s": 0,
"text": "Editable JSON Code"
},
{
"code": null,
"e": 241,
"s": 19,
"text": "12345678910111213141516{\"Company\": {\"Employee\": {\"FirstName\": \"Tanmay\",\"LastName\": \"Patil\",\"ContactNo\": \"1234567890\",\"Email\": \"tanmaypatil@xyz.com\",\"Address\": {\"City\": \"Bangalore\",\"State\": \"Karnataka\",\"Zip\": \"560212\"}}}}X"
},
{
"code": null,
"e": 256,
"s": 241,
"text": "Privacy Policy"
},
{
"code": null,
"e": 271,
"s": 256,
"text": "Cookies Policy"
}
] |
Create A Simple Search Engine Using Python | Towards Data Science
|
All of us have used a search engine, in example Google, in every single day for searching everything, even on simple things. But have you ever imagined, how that search engine can retrieve all of our documents based on what we want to search (query)?
In this article, I will show you on how to build a simple search engine from scratch using Python and its supporting library. After you read the article, I hope you can understand how to build your own search engine based on what you need. Without further, let’s go!
Side note: I’ve also created a notebook of the code, so if you want to follow along with me you can click on this link here. Also, the documents that I will use is in Indonesian. But don’t worry, you can use any documents regardless of the language.
Before we get our hands dirty, let me give you the steps on how to implement this, and on each section, I will explain on how to build it. They are,
Preparing the documents
Create a Term-Document Matrix with TF-IDF weighting
Calculate the similarities between query and documents using Cosine Similarity
Retrieve the articles that have the highest similarity on it.
The first thing that we have to do is to retrieve the documents from the Internet. In this case, we can use web scraping to extract documents from a website. I will scrape documents from kompas.com on sport category, especially on the popular articles. Because of the documents are using HTML format, we initialize a BeautifulSoup object to parse the HTML file, so we can extract each element that we want much easier.
Based on the figures below, I’ve shown the screenshot of the website with an inspect element to it. On Figure 1, I’ve shown the tags that we want to retrieve, which is the href attribute of the highlighted <a> tag with class “most__link”. On the Figure 2, We will retrieve text on <p> tags from <div> tag with class “read__content”.
Here is the code that I used for extracting the documents and its explanations on each line,
import requestsfrom bs4 import BeautifulSoup# Make a request to the websiter = requests.get('https://bola.kompas.com/')# Create an object to parse the HTML formatsoup = BeautifulSoup(r.content, 'html.parser')# Retrieve all popular news links (Fig. 1)link = []for i in soup.find('div', {'class':'most__wrap'}).find_all('a'): i['href'] = i['href'] + '?page=all' link.append(i['href'])# For each link, we retrieve paragraphs from it, combine each paragraph as one string, and save it to documents (Fig. 2)documents = []for i in link: # Make a request to the link r = requests.get(i) # Initialize BeautifulSoup object to parse the content soup = BeautifulSoup(r.content, 'html.parser') # Retrieve all paragraphs and combine it as one sen = [] for i in soup.find('div', {'class':'read__content'}).find_all('p'): sen.append(i.text) # Add the combined paragraphs to documents documents.append(' '.join(sen))
Right after we extract the documents, we have to clean it, so our retrieval process becomes much easier. For each document, we have to remove all unnecessary words, numbers and punctuations, lowercase the word, and remove the doubled space. Here is the code for it,
import redocuments_clean = []for d in documents: # Remove Unicode document_test = re.sub(r'[^\x00-\x7F]+', ' ', d) # Remove Mentions document_test = re.sub(r'@\w+', '', document_test) # Lowercase the document document_test = document_test.lower() # Remove punctuations document_test = re.sub(r'[%s]' % re.escape(string.punctuation), ' ', document_test) # Lowercase the numbers document_test = re.sub(r'[0-9]', '', document_test) # Remove the doubled space document_test = re.sub(r'\s{2,}', ' ', document_test) documents_clean.append(document_test)
After each document is clean, it’s time to create a matrix. Thankfully, scikit-learn library has prepared for us the code of it, so we don’t have to implement it from scratch. The code looks like this,
from sklearn.feature_extraction.text import TfidfVectorizer# Instantiate a TfidfVectorizer objectvectorizer = TfidfVectorizer()# It fits the data and transform it as a vectorX = vectorizer.fit_transform(docs)# Convert the X as transposed matrixX = X.T.toarray()# Create a DataFrame and set the vocabulary as the indexdf = pd.DataFrame(X, index=vectorizer.get_feature_names())
The result (matrix) will become a representation of the documents. By using that, we can find the similarity between different documents based on the matrix. The matrix looks like this,
The matrix above is called as Term-Document Matrix. It consists of rows that represent by each token (term) from all documents, and the columns consist of the identifier of the document. Inside of the cell is the number of frequency of each word that is weighted by some number.
We will use the column vector, which is a vector that represents each document to calculate the similarity with a given query. We can call this vector as embeddings.
For calculating the cell value, the code uses the TF-IDF method to do this. TF-IDF (Term Frequency — Inverse Document Frequency) is a frequency of a word that is weighted by IDF. Let me explain each one of them,
Term Frequency (TF) is a frequency of term (t) on document (d). The formula looks like this,
Beside of that, we can use a log with bases of 10 to calculate the TF, so the number becomes smaller, and the computation process becomes faster. Also, make sure to add one on it because we don’t want log 0 exist.
Then, there is the Inverse Document Frequency (IDF). This formula will be used for calculating the rarity of the word in all documents. It will be used as weights for the TF. If a word is frequent, then the IDF will be smaller. In opposite, if the word is less frequent, then the IDF will be larger. The formula looks like this,
Recall the TF-IDF, we can see how does it affect the value on each cell. It will remove all the words that are frequently shown in documents but at the same time not important, such as and, or, even, actually, etc. Based on that, we use this as the value on each cell on our matrix.
After we create the matrix, we can prepare our query to find articles based on the highest similarity between the document and the query. To calculate the similarity, we can use the cosine similarity formula to do this. It looks like this,
The formula calculates the dot product divided by the multiplication of the length on each vector. The value ranges from [1, 0], but in general, the cosine value ranges from [-1, 1]. Because there are no negative values on it, we can ignore the negative value because it never happens.
Now, we will implement the code to find similarities on documents based on a query. The first thing that we have to do is to transform the query as a vector on the matrix that we have. Then, we calculate the similarities between them. And finally, we retrieve all documents that have values above 0 in similarity. The code looks like this,
def get_similar_articles(q, df): print("query:", q) print("Berikut artikel dengan nilai cosine similarity tertinggi: ") # Convert the query become a vector q = [q] q_vec = vectorizer.transform(q).toarray().reshape(df.shape[0],) sim = {} # Calculate the similarity for i in range(10): sim[i] = np.dot(df.loc[:, i].values, q_vec) / np.linalg.norm(df.loc[:, i]) * np.linalg.norm(q_vec) # Sort the values sim_sorted = sorted(sim.items(), key=lambda x: x[1], reverse=True) # Print the articles and their similarity values for k, v in sim_sorted: if v != 0.0: print("Nilai Similaritas:", v) print(docs[k]) print()# Add The Queryq1 = 'barcelona'# Call the functionget_similar_articles(q1, df)
Suppose that we want to find articles that talk about Barcelona. If we run the code based on that, we will get the result like this,
query: barcelonaBerikut artikel dengan nilai cosine similarity tertinggi:Nilai Similaritas: 0.4641990113096689 kompas com perombakan skuad yang dilakukan pelatih anyar barcelona ronald koeman memakan korban baru terkini ronald koeman dikabarkan akan mendepak bintang muda barcelona yang baru berusia tahun riqui puig menurut media spanyol rac koeman sudah meminta riqui puig mencari tim baru karena tidak masuk dalam rencananya di barcelona rumor itu semakin kuat karena puig....Nilai Similaritas: 0.4254860197361395kompas com pertandingan trofeo joan gamper mempertemukan barcelona dengan salah satu tim promosi liga spanyol elche laga barcelona vs elche usai digelar di camp nou pada minggu dini hari wib trofeo joan gamper merupakan laga tahunan yang diadakan oleh barca kali ini sudah memasuki edisi ke blaugrana julukan tuan rumah menang dengan skor gol kemenangan barcelona....
That is how we can create a simple search engine using Python and its dependencies. It still very basic, but I hope you can learn something from here and can implement your own search engine based on what you need. Thank you.
[1] Jurafsky, D. & Martin, J.H. Speech and Language Processing (2000), Prentice Hall.
|
[
{
"code": null,
"e": 423,
"s": 172,
"text": "All of us have used a search engine, in example Google, in every single day for searching everything, even on simple things. But have you ever imagined, how that search engine can retrieve all of our documents based on what we want to search (query)?"
},
{
"code": null,
"e": 690,
"s": 423,
"text": "In this article, I will show you on how to build a simple search engine from scratch using Python and its supporting library. After you read the article, I hope you can understand how to build your own search engine based on what you need. Without further, let’s go!"
},
{
"code": null,
"e": 940,
"s": 690,
"text": "Side note: I’ve also created a notebook of the code, so if you want to follow along with me you can click on this link here. Also, the documents that I will use is in Indonesian. But don’t worry, you can use any documents regardless of the language."
},
{
"code": null,
"e": 1089,
"s": 940,
"text": "Before we get our hands dirty, let me give you the steps on how to implement this, and on each section, I will explain on how to build it. They are,"
},
{
"code": null,
"e": 1113,
"s": 1089,
"text": "Preparing the documents"
},
{
"code": null,
"e": 1165,
"s": 1113,
"text": "Create a Term-Document Matrix with TF-IDF weighting"
},
{
"code": null,
"e": 1244,
"s": 1165,
"text": "Calculate the similarities between query and documents using Cosine Similarity"
},
{
"code": null,
"e": 1306,
"s": 1244,
"text": "Retrieve the articles that have the highest similarity on it."
},
{
"code": null,
"e": 1725,
"s": 1306,
"text": "The first thing that we have to do is to retrieve the documents from the Internet. In this case, we can use web scraping to extract documents from a website. I will scrape documents from kompas.com on sport category, especially on the popular articles. Because of the documents are using HTML format, we initialize a BeautifulSoup object to parse the HTML file, so we can extract each element that we want much easier."
},
{
"code": null,
"e": 2058,
"s": 1725,
"text": "Based on the figures below, I’ve shown the screenshot of the website with an inspect element to it. On Figure 1, I’ve shown the tags that we want to retrieve, which is the href attribute of the highlighted <a> tag with class “most__link”. On the Figure 2, We will retrieve text on <p> tags from <div> tag with class “read__content”."
},
{
"code": null,
"e": 2151,
"s": 2058,
"text": "Here is the code that I used for extracting the documents and its explanations on each line,"
},
{
"code": null,
"e": 3099,
"s": 2151,
"text": "import requestsfrom bs4 import BeautifulSoup# Make a request to the websiter = requests.get('https://bola.kompas.com/')# Create an object to parse the HTML formatsoup = BeautifulSoup(r.content, 'html.parser')# Retrieve all popular news links (Fig. 1)link = []for i in soup.find('div', {'class':'most__wrap'}).find_all('a'): i['href'] = i['href'] + '?page=all' link.append(i['href'])# For each link, we retrieve paragraphs from it, combine each paragraph as one string, and save it to documents (Fig. 2)documents = []for i in link: # Make a request to the link r = requests.get(i) # Initialize BeautifulSoup object to parse the content soup = BeautifulSoup(r.content, 'html.parser') # Retrieve all paragraphs and combine it as one sen = [] for i in soup.find('div', {'class':'read__content'}).find_all('p'): sen.append(i.text) # Add the combined paragraphs to documents documents.append(' '.join(sen))"
},
{
"code": null,
"e": 3365,
"s": 3099,
"text": "Right after we extract the documents, we have to clean it, so our retrieval process becomes much easier. For each document, we have to remove all unnecessary words, numbers and punctuations, lowercase the word, and remove the doubled space. Here is the code for it,"
},
{
"code": null,
"e": 3952,
"s": 3365,
"text": "import redocuments_clean = []for d in documents: # Remove Unicode document_test = re.sub(r'[^\\x00-\\x7F]+', ' ', d) # Remove Mentions document_test = re.sub(r'@\\w+', '', document_test) # Lowercase the document document_test = document_test.lower() # Remove punctuations document_test = re.sub(r'[%s]' % re.escape(string.punctuation), ' ', document_test) # Lowercase the numbers document_test = re.sub(r'[0-9]', '', document_test) # Remove the doubled space document_test = re.sub(r'\\s{2,}', ' ', document_test) documents_clean.append(document_test)"
},
{
"code": null,
"e": 4154,
"s": 3952,
"text": "After each document is clean, it’s time to create a matrix. Thankfully, scikit-learn library has prepared for us the code of it, so we don’t have to implement it from scratch. The code looks like this,"
},
{
"code": null,
"e": 4530,
"s": 4154,
"text": "from sklearn.feature_extraction.text import TfidfVectorizer# Instantiate a TfidfVectorizer objectvectorizer = TfidfVectorizer()# It fits the data and transform it as a vectorX = vectorizer.fit_transform(docs)# Convert the X as transposed matrixX = X.T.toarray()# Create a DataFrame and set the vocabulary as the indexdf = pd.DataFrame(X, index=vectorizer.get_feature_names())"
},
{
"code": null,
"e": 4716,
"s": 4530,
"text": "The result (matrix) will become a representation of the documents. By using that, we can find the similarity between different documents based on the matrix. The matrix looks like this,"
},
{
"code": null,
"e": 4995,
"s": 4716,
"text": "The matrix above is called as Term-Document Matrix. It consists of rows that represent by each token (term) from all documents, and the columns consist of the identifier of the document. Inside of the cell is the number of frequency of each word that is weighted by some number."
},
{
"code": null,
"e": 5161,
"s": 4995,
"text": "We will use the column vector, which is a vector that represents each document to calculate the similarity with a given query. We can call this vector as embeddings."
},
{
"code": null,
"e": 5373,
"s": 5161,
"text": "For calculating the cell value, the code uses the TF-IDF method to do this. TF-IDF (Term Frequency — Inverse Document Frequency) is a frequency of a word that is weighted by IDF. Let me explain each one of them,"
},
{
"code": null,
"e": 5466,
"s": 5373,
"text": "Term Frequency (TF) is a frequency of term (t) on document (d). The formula looks like this,"
},
{
"code": null,
"e": 5680,
"s": 5466,
"text": "Beside of that, we can use a log with bases of 10 to calculate the TF, so the number becomes smaller, and the computation process becomes faster. Also, make sure to add one on it because we don’t want log 0 exist."
},
{
"code": null,
"e": 6009,
"s": 5680,
"text": "Then, there is the Inverse Document Frequency (IDF). This formula will be used for calculating the rarity of the word in all documents. It will be used as weights for the TF. If a word is frequent, then the IDF will be smaller. In opposite, if the word is less frequent, then the IDF will be larger. The formula looks like this,"
},
{
"code": null,
"e": 6292,
"s": 6009,
"text": "Recall the TF-IDF, we can see how does it affect the value on each cell. It will remove all the words that are frequently shown in documents but at the same time not important, such as and, or, even, actually, etc. Based on that, we use this as the value on each cell on our matrix."
},
{
"code": null,
"e": 6532,
"s": 6292,
"text": "After we create the matrix, we can prepare our query to find articles based on the highest similarity between the document and the query. To calculate the similarity, we can use the cosine similarity formula to do this. It looks like this,"
},
{
"code": null,
"e": 6818,
"s": 6532,
"text": "The formula calculates the dot product divided by the multiplication of the length on each vector. The value ranges from [1, 0], but in general, the cosine value ranges from [-1, 1]. Because there are no negative values on it, we can ignore the negative value because it never happens."
},
{
"code": null,
"e": 7158,
"s": 6818,
"text": "Now, we will implement the code to find similarities on documents based on a query. The first thing that we have to do is to transform the query as a vector on the matrix that we have. Then, we calculate the similarities between them. And finally, we retrieve all documents that have values above 0 in similarity. The code looks like this,"
},
{
"code": null,
"e": 7880,
"s": 7158,
"text": "def get_similar_articles(q, df): print(\"query:\", q) print(\"Berikut artikel dengan nilai cosine similarity tertinggi: \") # Convert the query become a vector q = [q] q_vec = vectorizer.transform(q).toarray().reshape(df.shape[0],) sim = {} # Calculate the similarity for i in range(10): sim[i] = np.dot(df.loc[:, i].values, q_vec) / np.linalg.norm(df.loc[:, i]) * np.linalg.norm(q_vec) # Sort the values sim_sorted = sorted(sim.items(), key=lambda x: x[1], reverse=True) # Print the articles and their similarity values for k, v in sim_sorted: if v != 0.0: print(\"Nilai Similaritas:\", v) print(docs[k]) print()# Add The Queryq1 = 'barcelona'# Call the functionget_similar_articles(q1, df)"
},
{
"code": null,
"e": 8013,
"s": 7880,
"text": "Suppose that we want to find articles that talk about Barcelona. If we run the code based on that, we will get the result like this,"
},
{
"code": null,
"e": 8897,
"s": 8013,
"text": "query: barcelonaBerikut artikel dengan nilai cosine similarity tertinggi:Nilai Similaritas: 0.4641990113096689 kompas com perombakan skuad yang dilakukan pelatih anyar barcelona ronald koeman memakan korban baru terkini ronald koeman dikabarkan akan mendepak bintang muda barcelona yang baru berusia tahun riqui puig menurut media spanyol rac koeman sudah meminta riqui puig mencari tim baru karena tidak masuk dalam rencananya di barcelona rumor itu semakin kuat karena puig....Nilai Similaritas: 0.4254860197361395kompas com pertandingan trofeo joan gamper mempertemukan barcelona dengan salah satu tim promosi liga spanyol elche laga barcelona vs elche usai digelar di camp nou pada minggu dini hari wib trofeo joan gamper merupakan laga tahunan yang diadakan oleh barca kali ini sudah memasuki edisi ke blaugrana julukan tuan rumah menang dengan skor gol kemenangan barcelona...."
},
{
"code": null,
"e": 9123,
"s": 8897,
"text": "That is how we can create a simple search engine using Python and its dependencies. It still very basic, but I hope you can learn something from here and can implement your own search engine based on what you need. Thank you."
}
] |
How to choose between `window.URL.createObjectURL()` and `window.webkitURL.createObjectURL()` based on browser?
|
To choose, you need to define a wrapper function −
function display ( file ) {
if ( window.webkitURL ) {
return window.webkitURL.createObjectURL( file );
} else if ( window.URL && window.URL.createObjectURL ) {
return window.URL.display( file );
} else {
return null;
}
}
After that set it for cross-browser −
var url = display( file );
|
[
{
"code": null,
"e": 1113,
"s": 1062,
"text": "To choose, you need to define a wrapper function −"
},
{
"code": null,
"e": 1361,
"s": 1113,
"text": "function display ( file ) {\n if ( window.webkitURL ) {\n return window.webkitURL.createObjectURL( file );\n } else if ( window.URL && window.URL.createObjectURL ) {\n return window.URL.display( file );\n } else {\n return null;\n }\n}"
},
{
"code": null,
"e": 1399,
"s": 1361,
"text": "After that set it for cross-browser −"
},
{
"code": null,
"e": 1426,
"s": 1399,
"text": "var url = display( file );"
}
] |
Types of Pop up boxes available in JavaScript
|
There are 3 types of pop up boxes available in JavaScript. These are −
1. Alert − The Window.alert() method displays an alert dialog with the optional specified content and an OK button.
For example, if you execute the following script, it'll open an alert box with the content: "This is an alert" with a confirmation button.
Live Demo
<script>
alert("This is a alert");
</script>
Note that the alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message.
2. Confirm − The Window.confirm() method displays a modal dialog with an optional message and two buttons: OK and Cancel.
For example, if you execute the following script, it'll open a confirmation box with the content: "Please confirm this action" with a confirmation button and cancellation button. This returns a boolean depending on the input provided by the user.
Live Demo
<script>
let bool = confirm("Please confirm this action");
console.log(bool);
</script>
If you click confirm, it'll return true. If you click cancel, it'll return false.
Note that Dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed.
3. Prompt − The Window.prompt() displays a dialog with an optional message prompting the user to input some text.
For example, if you execute the following script, it'll open a propmt box with the content: "Please enter your name" with a confirmation button and cancellation button. This returns a String provided by the user.
Live Demo
<script>
let name = prompt("Please enter your name");
console.log(name);
</script>
When you give it some input in the prompt, it'll log your name to the console.
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "There are 3 types of pop up boxes available in JavaScript. These are −"
},
{
"code": null,
"e": 1249,
"s": 1133,
"text": "1. Alert − The Window.alert() method displays an alert dialog with the optional specified content and an OK button."
},
{
"code": null,
"e": 1388,
"s": 1249,
"text": "For example, if you execute the following script, it'll open an alert box with the content: \"This is an alert\" with a confirmation button."
},
{
"code": null,
"e": 1399,
"s": 1388,
"text": " Live Demo"
},
{
"code": null,
"e": 1447,
"s": 1399,
"text": "<script>\n alert(\"This is a alert\");\n</script>"
},
{
"code": null,
"e": 1608,
"s": 1447,
"text": "Note that the alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message."
},
{
"code": null,
"e": 1730,
"s": 1608,
"text": "2. Confirm − The Window.confirm() method displays a modal dialog with an optional message and two buttons: OK and Cancel."
},
{
"code": null,
"e": 1977,
"s": 1730,
"text": "For example, if you execute the following script, it'll open a confirmation box with the content: \"Please confirm this action\" with a confirmation button and cancellation button. This returns a boolean depending on the input provided by the user."
},
{
"code": null,
"e": 1988,
"s": 1977,
"text": " Live Demo"
},
{
"code": null,
"e": 2082,
"s": 1988,
"text": "<script>\n let bool = confirm(\"Please confirm this action\");\n console.log(bool);\n</script>"
},
{
"code": null,
"e": 2164,
"s": 2082,
"text": "If you click confirm, it'll return true. If you click cancel, it'll return false."
},
{
"code": null,
"e": 2312,
"s": 2164,
"text": "Note that Dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed."
},
{
"code": null,
"e": 2426,
"s": 2312,
"text": "3. Prompt − The Window.prompt() displays a dialog with an optional message prompting the user to input some text."
},
{
"code": null,
"e": 2639,
"s": 2426,
"text": "For example, if you execute the following script, it'll open a propmt box with the content: \"Please enter your name\" with a confirmation button and cancellation button. This returns a String provided by the user."
},
{
"code": null,
"e": 2650,
"s": 2639,
"text": " Live Demo"
},
{
"code": null,
"e": 2739,
"s": 2650,
"text": "<script>\n let name = prompt(\"Please enter your name\");\n console.log(name);\n</script>"
},
{
"code": null,
"e": 2818,
"s": 2739,
"text": "When you give it some input in the prompt, it'll log your name to the console."
}
] |
Check if element exists in list of lists in Python
|
Lists can be nested, means the elements of a list are themselves lists. In this article we will see how to find out if a given element is present in the sublist which are themselves elements in the bigger list.
We first search if an element is present in the sublist and if the sublist is present in the list. If anyof this is true we can say that the element is present in the list.
Live Demo
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_element = -8
# Given list
print("Given List :\n", listA)
print("Element to Search: ",search_element)
# Using in
if any(search_element in sublist for sublist in listA):
print("Present")
else:
print("Not Present")
Running the above code gives us the following result −
('Given List :\n', [[-9, -1, 3], [11, -8], [-4, 434, 0]])
('Element to Search: ', -8)
Present
In this approach we make a simple search using the in operator. If the item is part of sublist which is also a part of the outer list, then we accept the element as present. We make two checks one to check the presence and another to check the absence.
Live Demo
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_element = -8
# Given list
print("Given List :\n", listA)
print("Element to Search: ",search_element)
# Using in
if search_element in (item for sublist in listA for item in sublist):
print("Present")
else:
print("Not Present")
search_element = 13
print("New Element to Search: ",search_element)
# Using in
if search_element in (item for sublist in listA for item in sublist):
print("Present")
else:
print("Not Present")
Running the above code gives us the following result −
Given List :
[[-9, -1, 3], [11, -8], [-4, 434, 0]]
Element to Search: -8
Present
New Element to Search: 13
Not Present
With the chain method from itertools module we can expand the lists of sublists and keep checking for the presence of an element using the in menthod.
Live Demo
from itertools import chain
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_element = -8
# Given list
print("Given List :\n", listA)
print("Element to Search: ",search_element)
# Using in
if search_element in chain(*listA):
print("Present")
else:
print("Not Present")
search_element = 13
print("New Element to Search: ",search_element)
# Using in
if search_element in chain(*listA):
print("Present")
else:
print("Not Present")
Running the above code gives us the following result −
Given List :
[[-9, -1, 3], [11, -8], [-4, 434, 0]]
Element to Search: -8
Present
New Element to Search: 13
Not Present
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "Lists can be nested, means the elements of a list are themselves lists. In this article we will see how to find out if a given element is present in the sublist which are themselves elements in the bigger list."
},
{
"code": null,
"e": 1446,
"s": 1273,
"text": "We first search if an element is present in the sublist and if the sublist is present in the list. If anyof this is true we can say that the element is present in the list."
},
{
"code": null,
"e": 1457,
"s": 1446,
"text": " Live Demo"
},
{
"code": null,
"e": 1728,
"s": 1457,
"text": "listA = [[-9, -1, 3], [11, -8],[-4,434,0]]\nsearch_element = -8\n\n# Given list\nprint(\"Given List :\\n\", listA)\n\nprint(\"Element to Search: \",search_element)\n\n# Using in\nif any(search_element in sublist for sublist in listA):\n print(\"Present\")\nelse:\n print(\"Not Present\")"
},
{
"code": null,
"e": 1783,
"s": 1728,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1877,
"s": 1783,
"text": "('Given List :\\n', [[-9, -1, 3], [11, -8], [-4, 434, 0]])\n('Element to Search: ', -8)\nPresent"
},
{
"code": null,
"e": 2130,
"s": 1877,
"text": "In this approach we make a simple search using the in operator. If the item is part of sublist which is also a part of the outer list, then we accept the element as present. We make two checks one to check the presence and another to check the absence."
},
{
"code": null,
"e": 2141,
"s": 2130,
"text": " Live Demo"
},
{
"code": null,
"e": 2627,
"s": 2141,
"text": "listA = [[-9, -1, 3], [11, -8],[-4,434,0]]\nsearch_element = -8\n\n# Given list\nprint(\"Given List :\\n\", listA)\n\nprint(\"Element to Search: \",search_element)\n\n# Using in\nif search_element in (item for sublist in listA for item in sublist):\n print(\"Present\")\nelse:\n print(\"Not Present\")\n\nsearch_element = 13\nprint(\"New Element to Search: \",search_element)\n\n# Using in\nif search_element in (item for sublist in listA for item in sublist):\n print(\"Present\")\nelse:\n print(\"Not Present\")"
},
{
"code": null,
"e": 2682,
"s": 2627,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2801,
"s": 2682,
"text": "Given List :\n[[-9, -1, 3], [11, -8], [-4, 434, 0]]\nElement to Search: -8\nPresent\nNew Element to Search: 13\nNot Present"
},
{
"code": null,
"e": 2952,
"s": 2801,
"text": "With the chain method from itertools module we can expand the lists of sublists and keep checking for the presence of an element using the in menthod."
},
{
"code": null,
"e": 2963,
"s": 2952,
"text": " Live Demo"
},
{
"code": null,
"e": 3410,
"s": 2963,
"text": "from itertools import chain\n\nlistA = [[-9, -1, 3], [11, -8],[-4,434,0]]\nsearch_element = -8\n\n# Given list\nprint(\"Given List :\\n\", listA)\n\nprint(\"Element to Search: \",search_element)\n\n# Using in\nif search_element in chain(*listA):\n print(\"Present\")\nelse:\n print(\"Not Present\")\n\nsearch_element = 13\nprint(\"New Element to Search: \",search_element)\n\n# Using in\nif search_element in chain(*listA):\n print(\"Present\")\nelse:\n print(\"Not Present\")"
},
{
"code": null,
"e": 3465,
"s": 3410,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3584,
"s": 3465,
"text": "Given List :\n[[-9, -1, 3], [11, -8], [-4, 434, 0]]\nElement to Search: -8\nPresent\nNew Element to Search: 13\nNot Present"
}
] |
Small input field with Bootstrap
|
Use the .input-sm class to set small input field in Bootstrap.
You can try to run the following code to implement .input-sm class:
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">
<h2>Candidate Profile</h2>
<form>
<div class="form-group">
<label for="sel2">What is your job profile?</label>
<select class="form-control input-lg" id="sel2">
<option>Programmer</option>
<option>Web Developer</option>
<option>DBA</option>
<option>Support Engineer</option>
</select>
</div>
<div class="form-group">
<label for="sel3">Educational Qualification</label>
<select class="form-control input-sm" id="sel3">
<option>Undergraduate</option>
<option>Graduate</option>
<option>Post-Graduate</option>
</select>
</div>
</form>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Use the .input-sm class to set small input field in Bootstrap."
},
{
"code": null,
"e": 1193,
"s": 1125,
"text": "You can try to run the following code to implement .input-sm class:"
},
{
"code": null,
"e": 1203,
"s": 1193,
"text": "Live Demo"
},
{
"code": null,
"e": 2611,
"s": 1203,
"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 <body>\n <div class = \"container\">\n <h2>Candidate Profile</h2>\n <form>\n <div class=\"form-group\">\n <label for=\"sel2\">What is your job profile?</label>\n <select class=\"form-control input-lg\" id=\"sel2\">\n <option>Programmer</option>\n <option>Web Developer</option>\n <option>DBA</option>\n <option>Support Engineer</option>\n </select>\n </div>\n <div class=\"form-group\">\n <label for=\"sel3\">Educational Qualification</label>\n <select class=\"form-control input-sm\" id=\"sel3\">\n <option>Undergraduate</option>\n <option>Graduate</option>\n <option>Post-Graduate</option>\n </select>\n </div>\n </form>\n </div>\n </body>\n</html>"
}
] |
Add elements of given arrays with given constraints - GeeksforGeeks
|
25 Jun, 2021
Given two integer arrays, add their elements into third array by satisfying following constraints – 1. Addition should be done starting from 0th index of both arrays. 2. Split the sum if it is a not a single digit number and store the digits in adjacent locations in output array. 3. Output array should accommodate any remaining digits of larger input array.
Examples:
Input:
a = [9, 2, 3, 7, 9, 6]
b = [3, 1, 4, 7, 8, 7, 6, 9]
Output:
[1, 2, 3, 7, 1, 4, 1, 7, 1, 3, 6, 9]
Input:
a = [9343, 2, 3, 7, 9, 6]
b = [34, 11, 4, 7, 8, 7, 6, 99]
Output:
[9, 3, 7, 7, 1, 3, 7, 1, 4, 1, 7, 1, 3, 6, 9, 9]
Input:
a = []
b = [11, 2, 3 ]
Output:
[1, 1, 2, 3 ]
Input:
a = [9, 8, 7, 6, 5, 4, 3, 2, 1]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
Difficulty Level: Rookie
The idea is very simple. We maintain an output array and run a loop from the 0th index of both arrays. For each iteration of loop, we consider next elements in both arrays and add them. If the sum is greater than 9, we push the individual digits of the sum to output array else we push the sum itself. Finally we push the remaining elements of larger input array to output array.
Below is the implementation of above idea:
C++
Java
C#
Javascript
// C++ program to add two arrays following given// constraints#include<bits/stdc++.h>using namespace std; // Function to push individual digits of a number// to output vector from left to rightvoid split(int num, vector<int> &out){ vector<int> arr; while (num) { arr.push_back(num%10); num = num/10; } // reverse the vector arr and append it to output vector out.insert(out.end(), arr.rbegin(), arr.rend());} // Function to add two arrays keeping given// constraintsvoid addArrays(int arr1[], int arr2[], int m, int n){ // create a vector to store output vector<int> out; // maintain a variable to store current index in // both arrays int i = 0; // loop till arr1 or arr2 runs out while (i < m && i < n) { // read next elements from both arrays and // add them int sum = arr1[i] + arr2[i]; // if sum is single digit number if (sum < 10) out.push_back(sum); else { // if sum is not a single digit number, push // individual digits to output vector split(sum, out); } // increment to next index i++; } // push remaining elements of first input array // (if any) to output vector while (i < m) split(arr1[i++], out); // push remaining elements of second input array // (if any) to output vector while (i < n) split(arr2[i++], out); // print the output vector for (int x : out) cout << x << " ";} // Driver codeint main(){ int arr1[] = {9343, 2, 3, 7, 9, 6}; int arr2[] = {34, 11, 4, 7, 8, 7, 6, 99}; int m = sizeof(arr1) / sizeof(arr1[0]); int n = sizeof(arr2) / sizeof(arr2[0]); addArrays(arr1, arr2, m, n); return 0;}
// Java program to add two arrays following given// constraintsimport java.util.Vector; class GFG{ // Function to push individual digits of a number // to output vector from left to right static void split(int num, Vector<Integer> out) { Vector<Integer> arr = new Vector<>(); while (num > 0) { arr.add(num % 10); num /= 10; } // reverse the vector arr and // append it to output vector for (int i = arr.size() - 1; i >= 0; i--) out.add(arr.elementAt(i)); } // Function to add two arrays keeping given // constraints static void addArrays(int[] arr1, int[] arr2, int m, int n) { // create a vector to store output Vector<Integer> out = new Vector<>(); // maintain a variable to store // current index in both arrays int i = 0; // loop till arr1 or arr2 runs out while (i < m && i < n) { // read next elements from both arrays // and add them int sum = arr1[i] + arr2[i]; // if sum is single digit number if (sum < 10) out.add(sum); else // if sum is not a single digit number, // push individual digits to output vector split(sum, out); // increment to next index i++; } // push remaining elements of first input array // (if any) to output vector while (i < m) split(arr1[i++], out); // push remaining elements of second input array // (if any) to output vector while (i < n) split(arr2[i++], out); // print the output vector for (int x : out) System.out.print(x + " "); } // Driver Code public static void main(String[] args) { int[] arr1 = { 9343, 2, 3, 7, 9, 6 }; int[] arr2 = { 34, 11, 4, 7, 8, 7, 6, 99 }; int m = arr1.length; int n = arr2.length; addArrays(arr1, arr2, m, n); }} // This code is contributed by// sanjeev2552
// C# program to add two arrays following given// constraintsusing System;using System.Collections.Generic; class GFG{ // Function to push individual digits of a number // to output vector from left to right static void split(int num, List<int> outs) { List<int> arr = new List<int>(); while (num > 0) { arr.Add(num % 10); num /= 10; } // reverse the vector arr and // append it to output vector for (int i = arr.Count - 1; i >= 0; i--) outs.Add(arr[i]); } // Function to add two arrays keeping given // constraints static void addArrays(int[] arr1, int[] arr2, int m, int n) { // create a vector to store output List<int> outs = new List<int>(); // maintain a variable to store // current index in both arrays int i = 0; // loop till arr1 or arr2 runs out while (i < m && i < n) { // read next elements from both arrays // and add them int sum = arr1[i] + arr2[i]; // if sum is single digit number if (sum < 10) outs.Add(sum); else // if sum is not a single digit number, // push individual digits to output vector split(sum, outs); // increment to next index i++; } // push remaining elements of first input array // (if any) to output vector while (i < m) split(arr1[i++], outs); // push remaining elements of second input array // (if any) to output vector while (i < n) split(arr2[i++], outs); // print the output vector foreach (int x in outs) Console.Write(x + " "); } // Driver Code public static void Main(String[] args) { int[] arr1 = { 9343, 2, 3, 7, 9, 6 }; int[] arr2 = { 34, 11, 4, 7, 8, 7, 6, 99 }; int m = arr1.Length; int n = arr2.Length; addArrays(arr1, arr2, m, n); }} // This code is contributed by PrinciRaj1992
<script> // Javascript program to add two arrays// following given constraints // Function to push individual digits// of a number to output vector from// left to rightfunction split(num, out){ let arr = []; while (num) { arr.push(num % 10); num = Math.floor(num / 10); } for(let i = arr.length - 1; i >= 0; i--) out.push(arr[i]);} // Function to add two arrays keeping given// constraintsfunction addArrays(arr1, arr2, m, n){ // Create a vector to store output let out = []; // Maintain a variable to store // current index in both arrays let i = 0; // Loop till arr1 or arr2 runs out while (i < m && i < n) { // Read next elements from both // arrays and add them let sum = arr1[i] + arr2[i]; // If sum is single digit number if (sum < 10) out.push(sum); else { // If sum is not a single digit // number, push individual digits // to output vector split(sum, out); } // Increment to next index i++; } // Push remaining elements of first // input array (if any) to output vector while (i < m) split(arr1[i++], out); // Push remaining elements of second // input array (if any) to output vector while (i < n) split(arr2[i++], out); // Print the output vector for(let x of out) document.write(x + " ");} // Driver codelet arr1 = [ 9343, 2, 3, 7, 9, 6 ];let arr2 = [ 34, 11, 4, 7, 8, 7, 6, 99 ]; let m = arr1.length;let n = arr2.length; addArrays(arr1, arr2, m, n); // This code is contributed by _saurabh_jaiswal </script>
Output:
9 3 7 7 1 3 7 1 4 1 7 1 3 6 9 9
Time complexity of above solution is O(m + n) as we traverses both arrays exactly once.
This article is contributed by Aditya Goel. 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.
sanjeev2552
princiraj1992
_saurabh_jaiswal
Arrays
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
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Queue | Set 1 (Introduction and Array Implementation)
Find the Missing Number
|
[
{
"code": null,
"e": 25060,
"s": 25032,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 25420,
"s": 25060,
"text": "Given two integer arrays, add their elements into third array by satisfying following constraints – 1. Addition should be done starting from 0th index of both arrays. 2. Split the sum if it is a not a single digit number and store the digits in adjacent locations in output array. 3. Output array should accommodate any remaining digits of larger input array."
},
{
"code": null,
"e": 25431,
"s": 25420,
"text": "Examples: "
},
{
"code": null,
"e": 25862,
"s": 25431,
"text": "Input: \na = [9, 2, 3, 7, 9, 6]\nb = [3, 1, 4, 7, 8, 7, 6, 9]\nOutput: \n[1, 2, 3, 7, 1, 4, 1, 7, 1, 3, 6, 9]\n\nInput: \na = [9343, 2, 3, 7, 9, 6]\nb = [34, 11, 4, 7, 8, 7, 6, 99]\nOutput: \n[9, 3, 7, 7, 1, 3, 7, 1, 4, 1, 7, 1, 3, 6, 9, 9]\n\nInput: \na = []\nb = [11, 2, 3 ]\nOutput: \n[1, 1, 2, 3 ]\n\nInput: \na = [9, 8, 7, 6, 5, 4, 3, 2, 1]\nb = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nOutput: \n[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]"
},
{
"code": null,
"e": 25887,
"s": 25862,
"text": "Difficulty Level: Rookie"
},
{
"code": null,
"e": 26267,
"s": 25887,
"text": "The idea is very simple. We maintain an output array and run a loop from the 0th index of both arrays. For each iteration of loop, we consider next elements in both arrays and add them. If the sum is greater than 9, we push the individual digits of the sum to output array else we push the sum itself. Finally we push the remaining elements of larger input array to output array."
},
{
"code": null,
"e": 26311,
"s": 26267,
"text": "Below is the implementation of above idea: "
},
{
"code": null,
"e": 26315,
"s": 26311,
"text": "C++"
},
{
"code": null,
"e": 26320,
"s": 26315,
"text": "Java"
},
{
"code": null,
"e": 26323,
"s": 26320,
"text": "C#"
},
{
"code": null,
"e": 26334,
"s": 26323,
"text": "Javascript"
},
{
"code": "// C++ program to add two arrays following given// constraints#include<bits/stdc++.h>using namespace std; // Function to push individual digits of a number// to output vector from left to rightvoid split(int num, vector<int> &out){ vector<int> arr; while (num) { arr.push_back(num%10); num = num/10; } // reverse the vector arr and append it to output vector out.insert(out.end(), arr.rbegin(), arr.rend());} // Function to add two arrays keeping given// constraintsvoid addArrays(int arr1[], int arr2[], int m, int n){ // create a vector to store output vector<int> out; // maintain a variable to store current index in // both arrays int i = 0; // loop till arr1 or arr2 runs out while (i < m && i < n) { // read next elements from both arrays and // add them int sum = arr1[i] + arr2[i]; // if sum is single digit number if (sum < 10) out.push_back(sum); else { // if sum is not a single digit number, push // individual digits to output vector split(sum, out); } // increment to next index i++; } // push remaining elements of first input array // (if any) to output vector while (i < m) split(arr1[i++], out); // push remaining elements of second input array // (if any) to output vector while (i < n) split(arr2[i++], out); // print the output vector for (int x : out) cout << x << \" \";} // Driver codeint main(){ int arr1[] = {9343, 2, 3, 7, 9, 6}; int arr2[] = {34, 11, 4, 7, 8, 7, 6, 99}; int m = sizeof(arr1) / sizeof(arr1[0]); int n = sizeof(arr2) / sizeof(arr2[0]); addArrays(arr1, arr2, m, n); return 0;}",
"e": 28099,
"s": 26334,
"text": null
},
{
"code": "// Java program to add two arrays following given// constraintsimport java.util.Vector; class GFG{ // Function to push individual digits of a number // to output vector from left to right static void split(int num, Vector<Integer> out) { Vector<Integer> arr = new Vector<>(); while (num > 0) { arr.add(num % 10); num /= 10; } // reverse the vector arr and // append it to output vector for (int i = arr.size() - 1; i >= 0; i--) out.add(arr.elementAt(i)); } // Function to add two arrays keeping given // constraints static void addArrays(int[] arr1, int[] arr2, int m, int n) { // create a vector to store output Vector<Integer> out = new Vector<>(); // maintain a variable to store // current index in both arrays int i = 0; // loop till arr1 or arr2 runs out while (i < m && i < n) { // read next elements from both arrays // and add them int sum = arr1[i] + arr2[i]; // if sum is single digit number if (sum < 10) out.add(sum); else // if sum is not a single digit number, // push individual digits to output vector split(sum, out); // increment to next index i++; } // push remaining elements of first input array // (if any) to output vector while (i < m) split(arr1[i++], out); // push remaining elements of second input array // (if any) to output vector while (i < n) split(arr2[i++], out); // print the output vector for (int x : out) System.out.print(x + \" \"); } // Driver Code public static void main(String[] args) { int[] arr1 = { 9343, 2, 3, 7, 9, 6 }; int[] arr2 = { 34, 11, 4, 7, 8, 7, 6, 99 }; int m = arr1.length; int n = arr2.length; addArrays(arr1, arr2, m, n); }} // This code is contributed by// sanjeev2552",
"e": 30230,
"s": 28099,
"text": null
},
{
"code": "// C# program to add two arrays following given// constraintsusing System;using System.Collections.Generic; class GFG{ // Function to push individual digits of a number // to output vector from left to right static void split(int num, List<int> outs) { List<int> arr = new List<int>(); while (num > 0) { arr.Add(num % 10); num /= 10; } // reverse the vector arr and // append it to output vector for (int i = arr.Count - 1; i >= 0; i--) outs.Add(arr[i]); } // Function to add two arrays keeping given // constraints static void addArrays(int[] arr1, int[] arr2, int m, int n) { // create a vector to store output List<int> outs = new List<int>(); // maintain a variable to store // current index in both arrays int i = 0; // loop till arr1 or arr2 runs out while (i < m && i < n) { // read next elements from both arrays // and add them int sum = arr1[i] + arr2[i]; // if sum is single digit number if (sum < 10) outs.Add(sum); else // if sum is not a single digit number, // push individual digits to output vector split(sum, outs); // increment to next index i++; } // push remaining elements of first input array // (if any) to output vector while (i < m) split(arr1[i++], outs); // push remaining elements of second input array // (if any) to output vector while (i < n) split(arr2[i++], outs); // print the output vector foreach (int x in outs) Console.Write(x + \" \"); } // Driver Code public static void Main(String[] args) { int[] arr1 = { 9343, 2, 3, 7, 9, 6 }; int[] arr2 = { 34, 11, 4, 7, 8, 7, 6, 99 }; int m = arr1.Length; int n = arr2.Length; addArrays(arr1, arr2, m, n); }} // This code is contributed by PrinciRaj1992",
"e": 32361,
"s": 30230,
"text": null
},
{
"code": "<script> // Javascript program to add two arrays// following given constraints // Function to push individual digits// of a number to output vector from// left to rightfunction split(num, out){ let arr = []; while (num) { arr.push(num % 10); num = Math.floor(num / 10); } for(let i = arr.length - 1; i >= 0; i--) out.push(arr[i]);} // Function to add two arrays keeping given// constraintsfunction addArrays(arr1, arr2, m, n){ // Create a vector to store output let out = []; // Maintain a variable to store // current index in both arrays let i = 0; // Loop till arr1 or arr2 runs out while (i < m && i < n) { // Read next elements from both // arrays and add them let sum = arr1[i] + arr2[i]; // If sum is single digit number if (sum < 10) out.push(sum); else { // If sum is not a single digit // number, push individual digits // to output vector split(sum, out); } // Increment to next index i++; } // Push remaining elements of first // input array (if any) to output vector while (i < m) split(arr1[i++], out); // Push remaining elements of second // input array (if any) to output vector while (i < n) split(arr2[i++], out); // Print the output vector for(let x of out) document.write(x + \" \");} // Driver codelet arr1 = [ 9343, 2, 3, 7, 9, 6 ];let arr2 = [ 34, 11, 4, 7, 8, 7, 6, 99 ]; let m = arr1.length;let n = arr2.length; addArrays(arr1, arr2, m, n); // This code is contributed by _saurabh_jaiswal </script>",
"e": 34056,
"s": 32361,
"text": null
},
{
"code": null,
"e": 34065,
"s": 34056,
"text": "Output: "
},
{
"code": null,
"e": 34097,
"s": 34065,
"text": "9 3 7 7 1 3 7 1 4 1 7 1 3 6 9 9"
},
{
"code": null,
"e": 34185,
"s": 34097,
"text": "Time complexity of above solution is O(m + n) as we traverses both arrays exactly once."
},
{
"code": null,
"e": 34605,
"s": 34185,
"text": "This article is contributed by Aditya Goel. 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": 34617,
"s": 34605,
"text": "sanjeev2552"
},
{
"code": null,
"e": 34631,
"s": 34617,
"text": "princiraj1992"
},
{
"code": null,
"e": 34648,
"s": 34631,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 34655,
"s": 34648,
"text": "Arrays"
},
{
"code": null,
"e": 34662,
"s": 34655,
"text": "Arrays"
},
{
"code": null,
"e": 34760,
"s": 34662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34769,
"s": 34760,
"text": "Comments"
},
{
"code": null,
"e": 34782,
"s": 34769,
"text": "Old Comments"
},
{
"code": null,
"e": 34830,
"s": 34782,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34874,
"s": 34830,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34906,
"s": 34874,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34929,
"s": 34906,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34943,
"s": 34929,
"text": "Linear Search"
},
{
"code": null,
"e": 35011,
"s": 34943,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35056,
"s": 35011,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 35077,
"s": 35056,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 35131,
"s": 35077,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
}
] |
Canvas API in Android Jetpack Compose - GeeksforGeeks
|
20 Dec, 2021
Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the data changes or is updated then the framework automatically recalls these functions and updates the view for you. Sometimes an app needs to draw some custom graphics on the screen and have precise control over what’s been drawn on the screen. In this article, we will learn the basics of Canvas API in jetpack compose and try to create a GeeksforGeeks logo using canvas API. Below is the image of how it will look finally,
Step 1: Create a New Project
To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Working with the MainActivity.kt file
Navigate to the app > java > your app’s package name and open the MainActivity.kt file.
Kotlin
@Composablefun Icon(modifier: Modifier = Modifier) { Canvas(modifier = modifier.size(100.dp), onDraw = { val canvasWidth = size.width val canvasHeight = size.height // we first draw the arc which // will be the curve of the logo drawArc( color = Color.White, // arc starts at 0 degree and ends startAngle = 0f, // set use center to false to draw the // arc without centered line // Tip: use center to true to draw the arc // with centered line and see the difference useCenter = false, // set the end angle of the arc sweepAngle = 300f, // set the width of the arc and // how the arc cap will be drawn // cap = StrokeCap.Round will draw // the arc with rounded end style = Stroke(width = 40f, cap = StrokeCap.Square) ) }) }
If you call this composable from setContent you will see something like this.
Kotlin
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { // CanvasApiTheme is Auto generated theme, // It will be appnameTheme in your case CanvasAPITheme { Icon() } } }}
Now we need to add a line in the center. We will use the function drawLine in the canvas scope. Add this code below the arc so that it will be on top of the arc
Note: Order in which shapes are written in canvas scope is the order in which they will be placed on each other.
Kotlin
// draw the center line of the logodrawLine( color = Color.White, // set the start point of the // line to the center of the canvas start = Offset(x = 0f, y = canvasHeight / 2), // set the end point of the // line to the center of the canvas end = Offset(x = canvasWidth, y = canvasHeight / 2), // set the width of the line strokeWidth = 40f )
Now if you run the app you will see complete G like this.
Our one side of the logo is complete, we just need to place two Icon composable in a row such that one is the mirror image of each other. MainActivity will now look like this. Refer to the comments for better understanding.
Kotlin
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CanvasAPITheme { // Create a box to and set contentAlignment // to Center to center the Icon Box( modifier = Modifier .fillMaxSize() .background(Color(0xFF308D46)), contentAlignment = Alignment.Center ) { // Create a row Row { // Place one Icon in the row but // rotate Y Axis by -180 degree // it will look like mirror image Icon(Modifier.graphicsLayer(rotationY = -180f)) // set some space between the icons Spacer(modifier = Modifier.width(20.dp)) // Original Icon without rotation Icon() } } } } }}
Now run the app to see the final result.
Output:
In this article, we used Arc and Line. Canvas also provides the option to draw other shapes like
drawRect to draw a rectangle.
drawImage to draw the bitmap.
drawRoundRect to draw a rounded rectangle.
drawCircle to draw a circle.
drawOval for oval.
drawPath for drawing path.
drawPoints to draw points given in the argument.
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Flexbox-Layout in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 27154,
"s": 26381,
"text": "Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the data changes or is updated then the framework automatically recalls these functions and updates the view for you. Sometimes an app needs to draw some custom graphics on the screen and have precise control over what’s been drawn on the screen. In this article, we will learn the basics of Canvas API in jetpack compose and try to create a GeeksforGeeks logo using canvas API. Below is the image of how it will look finally,"
},
{
"code": null,
"e": 27183,
"s": 27154,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27343,
"s": 27183,
"text": "To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose."
},
{
"code": null,
"e": 27389,
"s": 27343,
"text": "Step 2: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 27477,
"s": 27389,
"text": "Navigate to the app > java > your app’s package name and open the MainActivity.kt file."
},
{
"code": null,
"e": 27484,
"s": 27477,
"text": "Kotlin"
},
{
"code": "@Composablefun Icon(modifier: Modifier = Modifier) { Canvas(modifier = modifier.size(100.dp), onDraw = { val canvasWidth = size.width val canvasHeight = size.height // we first draw the arc which // will be the curve of the logo drawArc( color = Color.White, // arc starts at 0 degree and ends startAngle = 0f, // set use center to false to draw the // arc without centered line // Tip: use center to true to draw the arc // with centered line and see the difference useCenter = false, // set the end angle of the arc sweepAngle = 300f, // set the width of the arc and // how the arc cap will be drawn // cap = StrokeCap.Round will draw // the arc with rounded end style = Stroke(width = 40f, cap = StrokeCap.Square) ) }) }",
"e": 28433,
"s": 27484,
"text": null
},
{
"code": null,
"e": 28511,
"s": 28433,
"text": "If you call this composable from setContent you will see something like this."
},
{
"code": null,
"e": 28518,
"s": 28511,
"text": "Kotlin"
},
{
"code": "class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { // CanvasApiTheme is Auto generated theme, // It will be appnameTheme in your case CanvasAPITheme { Icon() } } }}",
"e": 28866,
"s": 28518,
"text": null
},
{
"code": null,
"e": 29027,
"s": 28866,
"text": "Now we need to add a line in the center. We will use the function drawLine in the canvas scope. Add this code below the arc so that it will be on top of the arc"
},
{
"code": null,
"e": 29140,
"s": 29027,
"text": "Note: Order in which shapes are written in canvas scope is the order in which they will be placed on each other."
},
{
"code": null,
"e": 29147,
"s": 29140,
"text": "Kotlin"
},
{
"code": "// draw the center line of the logodrawLine( color = Color.White, // set the start point of the // line to the center of the canvas start = Offset(x = 0f, y = canvasHeight / 2), // set the end point of the // line to the center of the canvas end = Offset(x = canvasWidth, y = canvasHeight / 2), // set the width of the line strokeWidth = 40f )",
"e": 29611,
"s": 29147,
"text": null
},
{
"code": null,
"e": 29669,
"s": 29611,
"text": "Now if you run the app you will see complete G like this."
},
{
"code": null,
"e": 29894,
"s": 29669,
"text": "Our one side of the logo is complete, we just need to place two Icon composable in a row such that one is the mirror image of each other. MainActivity will now look like this. Refer to the comments for better understanding."
},
{
"code": null,
"e": 29901,
"s": 29894,
"text": "Kotlin"
},
{
"code": "class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CanvasAPITheme { // Create a box to and set contentAlignment // to Center to center the Icon Box( modifier = Modifier .fillMaxSize() .background(Color(0xFF308D46)), contentAlignment = Alignment.Center ) { // Create a row Row { // Place one Icon in the row but // rotate Y Axis by -180 degree // it will look like mirror image Icon(Modifier.graphicsLayer(rotationY = -180f)) // set some space between the icons Spacer(modifier = Modifier.width(20.dp)) // Original Icon without rotation Icon() } } } } }}",
"e": 31035,
"s": 29901,
"text": null
},
{
"code": null,
"e": 31076,
"s": 31035,
"text": "Now run the app to see the final result."
},
{
"code": null,
"e": 31084,
"s": 31076,
"text": "Output:"
},
{
"code": null,
"e": 31181,
"s": 31084,
"text": "In this article, we used Arc and Line. Canvas also provides the option to draw other shapes like"
},
{
"code": null,
"e": 31211,
"s": 31181,
"text": "drawRect to draw a rectangle."
},
{
"code": null,
"e": 31241,
"s": 31211,
"text": "drawImage to draw the bitmap."
},
{
"code": null,
"e": 31284,
"s": 31241,
"text": "drawRoundRect to draw a rounded rectangle."
},
{
"code": null,
"e": 31313,
"s": 31284,
"text": "drawCircle to draw a circle."
},
{
"code": null,
"e": 31332,
"s": 31313,
"text": "drawOval for oval."
},
{
"code": null,
"e": 31359,
"s": 31332,
"text": "drawPath for drawing path."
},
{
"code": null,
"e": 31408,
"s": 31359,
"text": "drawPoints to draw points given in the argument."
},
{
"code": null,
"e": 31424,
"s": 31408,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 31432,
"s": 31424,
"text": "Android"
},
{
"code": null,
"e": 31439,
"s": 31432,
"text": "Kotlin"
},
{
"code": null,
"e": 31447,
"s": 31439,
"text": "Android"
},
{
"code": null,
"e": 31545,
"s": 31447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31583,
"s": 31545,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31622,
"s": 31583,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31672,
"s": 31622,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 31723,
"s": 31672,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 31749,
"s": 31723,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 31768,
"s": 31749,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 31781,
"s": 31768,
"text": "Kotlin Array"
},
{
"code": null,
"e": 31823,
"s": 31781,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31863,
"s": 31823,
"text": "How to Get Current Location in Android?"
}
] |
How to Calculate Percentiles in R? - GeeksforGeeks
|
19 Dec, 2021
In this article, we will discuss how to calculate percentiles in the R programming language.
Percentiles are measures of central tendency, which depict that out of the total data about certain percent data lies below it. In R, we can use quantile() function to get the job done.
Syntax: quantile( data, probs)
Parameter:
data: data whose percentiles are to be calculated
probs: percentile value
To calculate the percentile we simply pass the data and the value of the required percentile.
R
x<-c(2,13,5,36,12,50) res<-quantile(x,probs=0.5) res
Output:
50%
12.5
We can calculate multiple percentiles at once. For that, we have to pass the vector of percentiles instead of a single value to probs parameter.
R
x<-c(2,13,5,36,12,50) res<-quantile(x,probs=c(0.5,0.75)) res
Output:
50% 75%
12.50 30.25
Sometimes requirement asks for calculating percentiles for a dataframe column in that case the entire process remains same only you have to pass the column name in place of data along with the percentile value to be calculated.
R
df<-data.frame(x=c(2,13,5,36,12,50),y=c('a','b','c','c','c','b')) res<-quantile(df$x,probs=c(0.35,0.7)) res
Output:
35% 70%
10.25 24.50
We can also find percentiles of several dataframe columns at once. This can also be applied to find the percentiles of all numeric columns of dataframe. For this we use apply() function, within this we will pass the dataframe with just numeric columns and the quantile function that has to be applied on all columns.
Syntax: apply( dataframe, function)
R
df<-data.frame(x=c(2,13,5,36,12,50),y=c('a','b','c','c','c','b'),z=c(2.1,6,3.8,4.8,2.2,1.1)) sub_df<-df[,c('x','z')] res<-apply(sub_df, 2, function(x) quantile(x,probs=0.5)) res
Output:
x z
12.5 3.0
We can also group values together and find the percentile with respect to each group. For this, we use groupby() function, and then within summarize() we will apply the quantile function.
R
library(dplyr) df<-data.frame(x=c(2,13,5,36,12,50), y=c('a','b','c','c','c','b')) df %>% group_by(y) %>% summarize(res=quantile(x,probs=0.5))
Output:
A tibble: 3 x 2
y res
<chr> <dbl>
a 2
b 31.5
c 12
Visualizing percentiles can make it better to understand.
R
df<-data.frame(x=c(2,13,5,36,12,50),y=c('a','b','c','c','c','b'),z=c(2.1,6,3.8,4.8,2.2,1.1)) n<-length(df$x) plot((1:n-1)/(n-1), sort(df$x.Length), type='h', xlab = "Percentile", ylab = "Value")
Output:
Picked
R-Mathematics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 26691,
"s": 26597,
"text": "In this article, we will discuss how to calculate percentiles in the R programming language. "
},
{
"code": null,
"e": 26877,
"s": 26691,
"text": "Percentiles are measures of central tendency, which depict that out of the total data about certain percent data lies below it. In R, we can use quantile() function to get the job done."
},
{
"code": null,
"e": 26908,
"s": 26877,
"text": "Syntax: quantile( data, probs)"
},
{
"code": null,
"e": 26920,
"s": 26908,
"text": "Parameter: "
},
{
"code": null,
"e": 26970,
"s": 26920,
"text": "data: data whose percentiles are to be calculated"
},
{
"code": null,
"e": 26994,
"s": 26970,
"text": "probs: percentile value"
},
{
"code": null,
"e": 27088,
"s": 26994,
"text": "To calculate the percentile we simply pass the data and the value of the required percentile."
},
{
"code": null,
"e": 27090,
"s": 27088,
"text": "R"
},
{
"code": "x<-c(2,13,5,36,12,50) res<-quantile(x,probs=0.5) res",
"e": 27145,
"s": 27090,
"text": null
},
{
"code": null,
"e": 27153,
"s": 27145,
"text": "Output:"
},
{
"code": null,
"e": 27165,
"s": 27153,
"text": " 50% \n12.5"
},
{
"code": null,
"e": 27310,
"s": 27165,
"text": "We can calculate multiple percentiles at once. For that, we have to pass the vector of percentiles instead of a single value to probs parameter."
},
{
"code": null,
"e": 27312,
"s": 27310,
"text": "R"
},
{
"code": "x<-c(2,13,5,36,12,50) res<-quantile(x,probs=c(0.5,0.75)) res",
"e": 27375,
"s": 27312,
"text": null
},
{
"code": null,
"e": 27383,
"s": 27375,
"text": "Output:"
},
{
"code": null,
"e": 27409,
"s": 27383,
"text": " 50% 75% \n12.50 30.25 "
},
{
"code": null,
"e": 27637,
"s": 27409,
"text": "Sometimes requirement asks for calculating percentiles for a dataframe column in that case the entire process remains same only you have to pass the column name in place of data along with the percentile value to be calculated."
},
{
"code": null,
"e": 27639,
"s": 27637,
"text": "R"
},
{
"code": "df<-data.frame(x=c(2,13,5,36,12,50),y=c('a','b','c','c','c','b')) res<-quantile(df$x,probs=c(0.35,0.7)) res",
"e": 27749,
"s": 27639,
"text": null
},
{
"code": null,
"e": 27757,
"s": 27749,
"text": "Output:"
},
{
"code": null,
"e": 27783,
"s": 27757,
"text": " 35% 70% \n10.25 24.50 "
},
{
"code": null,
"e": 28100,
"s": 27783,
"text": "We can also find percentiles of several dataframe columns at once. This can also be applied to find the percentiles of all numeric columns of dataframe. For this we use apply() function, within this we will pass the dataframe with just numeric columns and the quantile function that has to be applied on all columns."
},
{
"code": null,
"e": 28136,
"s": 28100,
"text": "Syntax: apply( dataframe, function)"
},
{
"code": null,
"e": 28138,
"s": 28136,
"text": "R"
},
{
"code": "df<-data.frame(x=c(2,13,5,36,12,50),y=c('a','b','c','c','c','b'),z=c(2.1,6,3.8,4.8,2.2,1.1)) sub_df<-df[,c('x','z')] res<-apply(sub_df, 2, function(x) quantile(x,probs=0.5)) res",
"e": 28319,
"s": 28138,
"text": null
},
{
"code": null,
"e": 28327,
"s": 28319,
"text": "Output:"
},
{
"code": null,
"e": 28350,
"s": 28327,
"text": " x z \n12.5 3.0 "
},
{
"code": null,
"e": 28538,
"s": 28350,
"text": "We can also group values together and find the percentile with respect to each group. For this, we use groupby() function, and then within summarize() we will apply the quantile function."
},
{
"code": null,
"e": 28540,
"s": 28538,
"text": "R"
},
{
"code": "library(dplyr) df<-data.frame(x=c(2,13,5,36,12,50), y=c('a','b','c','c','c','b')) df %>% group_by(y) %>% summarize(res=quantile(x,probs=0.5))",
"e": 28701,
"s": 28540,
"text": null
},
{
"code": null,
"e": 28709,
"s": 28701,
"text": "Output:"
},
{
"code": null,
"e": 28784,
"s": 28709,
"text": "A tibble: 3 x 2\ny res\n<chr> <dbl>\na 2 \nb 31.5\nc 12 "
},
{
"code": null,
"e": 28843,
"s": 28784,
"text": "Visualizing percentiles can make it better to understand. "
},
{
"code": null,
"e": 28845,
"s": 28843,
"text": "R"
},
{
"code": "df<-data.frame(x=c(2,13,5,36,12,50),y=c('a','b','c','c','c','b'),z=c(2.1,6,3.8,4.8,2.2,1.1)) n<-length(df$x) plot((1:n-1)/(n-1), sort(df$x.Length), type='h', xlab = \"Percentile\", ylab = \"Value\")",
"e": 29047,
"s": 28845,
"text": null
},
{
"code": null,
"e": 29055,
"s": 29047,
"text": "Output:"
},
{
"code": null,
"e": 29062,
"s": 29055,
"text": "Picked"
},
{
"code": null,
"e": 29076,
"s": 29062,
"text": "R-Mathematics"
},
{
"code": null,
"e": 29087,
"s": 29076,
"text": "R Language"
},
{
"code": null,
"e": 29185,
"s": 29087,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29237,
"s": 29185,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29272,
"s": 29237,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29330,
"s": 29272,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29368,
"s": 29330,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29411,
"s": 29368,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29460,
"s": 29411,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29477,
"s": 29460,
"text": "R - if statement"
},
{
"code": null,
"e": 29527,
"s": 29477,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29564,
"s": 29527,
"text": "How to import an Excel File into R ?"
}
] |
Kth Smallest Factor | Practice | GeeksforGeeks
|
GIven two positive integers N and K. You have to find the Kth smallest factor of N. A factor of N is a positive integer which divides N. Output the Kth smallest factor of N if it exists otherwise print -1.
Example 1:
Input : N = 4 , K = 2
Output: 2
Explanation:
All factors of 4 are 1,2 and 4. Out of
these 2 is the 2nd smallest.
Example 2:
Input : N = 4 , K = 3
Output: 4
Explanation:
All factors of 4 are 1,2 and 4. Out of
these 4 is the 3rd smallest.
Your Task:
You don't need to read input or print anything. Your task is to complete the function kThSmallestFactor() which takes 2 Integers N and K as input and returns the answer.
Expected Time Complexity: O(sqrt(N))
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 106
1 <= K <= 106
0
bndas250220004 days ago
this can't be solved with O(1) space complexity.
0
mayank180919992 weeks ago
int kThSmallestFactor(int N , int K) {
// code here
set<int>s;
for(int i=1;i<=sqrt(N);i++){
if(N%i==0){
s.insert(i);
s.insert(N/i);
}
}
if(s.size()<K){
return -1;
}
int count=0,ans;
for(auto it:s){
if(count!=K){
count++;
ans=it;
}else{
break;
}
}
return ans;
}
0
shalini21sirothiya1 month ago
//c++
int kThSmallestFactor(int N , int K) { // code here set<int>s; for(int i=1;i<=sqrt(N);i++){ if(N%i==0){ s.insert(i); s.insert(N/i); } } int counter=0,temp=0; if(s.size()<K) return -1; for(auto i:s){ if(counter!=K){ counter++; temp=i; } else{ break; } } return temp; }
0
hritikpatani1 month ago
int kThSmallestFactor(int N , int K) { set<int> s; for(int i=1;i<=sqrt(N);i++){ if(N%i == 0){ s.insert(i); s.insert(N/i); } } if(s.size() < K) return -1; int counter=0,temp=0; for(auto i : s){ if(counter != K){ counter++; temp = i; } else break; } return temp; }
+1
darshansol1083 months ago
class Solution { static int kThSmallestFactor(int n , int k) { // code here // System.out.println(n+k); for(int i=1;i<=n;i++){ if(n%i == 0){ k--; if(k==0) return i; } } return -1; }};
0
lokeshsingh7695
This comment was deleted.
0
deepanshukohli634 months ago
TIME TAKEN -: 0.4/60.6
def kThSmallestFactor(self, N , K): # code here l=[] c=0 for i in range(1,int(pow(N,1/2))+1): if N%i==0: if N/i==i: l.append(i) c=c+1 else: l.append(i) l.append(int(N/i)) c=c+2 l.sort() if K>c: return -1 else: return l[K-1]
0
sanskargargee20a14724 months ago
Time = 0.1 / 12.8
Time Complexity O(root N)
Space Complexity O( root N)
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
// } Driver Code Endsclass Solution { public: int kThSmallestFactor(int N , int K) { // code here vector <int> ans; ans.push_back(1); // Square Root of N loop to find the factor upto root N for(int i=2 ; i*i <= N ; i++){ if(N%i == 0) ans.push_back(i); } int m=ans.size(); int last = ans[m - 1]; // Imp check if last*last == N then don't push back another factor to avoid redundancy
if(last*last == N){ m=m-1; // m is reduced by 1 } // Now adding the seconf factor of N from ans vector for(int i=m-1 ; i>=0 ; i--){ ans.push_back(N/ans[i]); } if(K>ans.size()){ return -1; } return ans[K-1]; }};
// { Driver Code Starts.int main() { int t; cin >> t; while (t--) { int N,K; cin>>N>>K;
Solution ob; cout << ob.kThSmallestFactor(N,K) << endl; } return 0;} // } Driver Code Ends
+1
subhranshubehera99sb4 months ago
Java code with 100% accuracy and total time taken 3.8/48.7
class Solution {
static int kThSmallestFactor(int N , int K) {
// code here
int c=0;
if(K==1) {
return 1;
} else if(N<K) {
return -1;
}
for(int i=1;i<=N;i++) {
if(N%i==0){
c++;
}
if(c==K){
return i;
} else if(c>K) {
return -1;
}
}
return -1;
}
}
+1
aloksinghbais024 months ago
C++ solution having time complexity as O(sqrt(N)) and space complexity as O(2*sqrt(N)) is as follows :-
Execution Time :- 0.1 / 12.8 sec
int kThSmallestFactor(int N , int K) { vector<int> sf,lf; for(int i=1; i<=sqrt(N); i++){ if(N % i == 0){ if(N/i != i) sf.push_back(i), lf.push_back(N/i); else sf.push_back(i); } } reverse(lf.begin(),lf.end()); vector<int> fac; for(auto x: sf) fac.push_back(x); for(auto x: lf) fac.push_back(x); if(K <= fac.size()) return fac[K-1]; return -1; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 444,
"s": 238,
"text": "GIven two positive integers N and K. You have to find the Kth smallest factor of N. A factor of N is a positive integer which divides N. Output the Kth smallest factor of N if it exists otherwise print -1."
},
{
"code": null,
"e": 457,
"s": 446,
"text": "Example 1:"
},
{
"code": null,
"e": 570,
"s": 457,
"text": "Input : N = 4 , K = 2\nOutput: 2\nExplanation:\nAll factors of 4 are 1,2 and 4. Out of\nthese 2 is the 2nd smallest."
},
{
"code": null,
"e": 581,
"s": 570,
"text": "Example 2:"
},
{
"code": null,
"e": 694,
"s": 581,
"text": "Input : N = 4 , K = 3\nOutput: 4\nExplanation:\nAll factors of 4 are 1,2 and 4. Out of\nthese 4 is the 3rd smallest."
},
{
"code": null,
"e": 877,
"s": 696,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function kThSmallestFactor() which takes 2 Integers N and K as input and returns the answer."
},
{
"code": null,
"e": 947,
"s": 879,
"text": "Expected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 990,
"s": 949,
"text": "Constraints:\n1 <= N <= 106\n1 <= K <= 106"
},
{
"code": null,
"e": 992,
"s": 990,
"text": "0"
},
{
"code": null,
"e": 1016,
"s": 992,
"text": "bndas250220004 days ago"
},
{
"code": null,
"e": 1066,
"s": 1016,
"text": "this can't be solved with O(1) space complexity. "
},
{
"code": null,
"e": 1068,
"s": 1066,
"text": "0"
},
{
"code": null,
"e": 1094,
"s": 1068,
"text": "mayank180919992 weeks ago"
},
{
"code": null,
"e": 1587,
"s": 1094,
"text": " int kThSmallestFactor(int N , int K) {\n // code here\n set<int>s;\n for(int i=1;i<=sqrt(N);i++){\n if(N%i==0){\n s.insert(i);\n s.insert(N/i);\n }\n }\n if(s.size()<K){\n return -1;\n }\n int count=0,ans;\n for(auto it:s){\n if(count!=K){\n count++;\n ans=it;\n }else{\n break;\n }\n }\n return ans;\n }"
},
{
"code": null,
"e": 1589,
"s": 1587,
"text": "0"
},
{
"code": null,
"e": 1619,
"s": 1589,
"text": "shalini21sirothiya1 month ago"
},
{
"code": null,
"e": 1625,
"s": 1619,
"text": "//c++"
},
{
"code": null,
"e": 2073,
"s": 1625,
"text": "int kThSmallestFactor(int N , int K) { // code here set<int>s; for(int i=1;i<=sqrt(N);i++){ if(N%i==0){ s.insert(i); s.insert(N/i); } } int counter=0,temp=0; if(s.size()<K) return -1; for(auto i:s){ if(counter!=K){ counter++; temp=i; } else{ break; } } return temp; }"
},
{
"code": null,
"e": 2075,
"s": 2073,
"text": "0"
},
{
"code": null,
"e": 2099,
"s": 2075,
"text": "hritikpatani1 month ago"
},
{
"code": null,
"e": 2543,
"s": 2099,
"text": " int kThSmallestFactor(int N , int K) { set<int> s; for(int i=1;i<=sqrt(N);i++){ if(N%i == 0){ s.insert(i); s.insert(N/i); } } if(s.size() < K) return -1; int counter=0,temp=0; for(auto i : s){ if(counter != K){ counter++; temp = i; } else break; } return temp; }"
},
{
"code": null,
"e": 2546,
"s": 2543,
"text": "+1"
},
{
"code": null,
"e": 2572,
"s": 2546,
"text": "darshansol1083 months ago"
},
{
"code": null,
"e": 2903,
"s": 2572,
"text": "class Solution { static int kThSmallestFactor(int n , int k) { // code here // System.out.println(n+k); for(int i=1;i<=n;i++){ if(n%i == 0){ k--; if(k==0) return i; } } return -1; }};"
},
{
"code": null,
"e": 2905,
"s": 2903,
"text": "0"
},
{
"code": null,
"e": 2921,
"s": 2905,
"text": "lokeshsingh7695"
},
{
"code": null,
"e": 2947,
"s": 2921,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2949,
"s": 2947,
"text": "0"
},
{
"code": null,
"e": 2978,
"s": 2949,
"text": "deepanshukohli634 months ago"
},
{
"code": null,
"e": 3001,
"s": 2978,
"text": "TIME TAKEN -: 0.4/60.6"
},
{
"code": null,
"e": 3415,
"s": 3001,
"text": "def kThSmallestFactor(self, N , K): # code here l=[] c=0 for i in range(1,int(pow(N,1/2))+1): if N%i==0: if N/i==i: l.append(i) c=c+1 else: l.append(i) l.append(int(N/i)) c=c+2 l.sort() if K>c: return -1 else: return l[K-1]"
},
{
"code": null,
"e": 3417,
"s": 3415,
"text": "0"
},
{
"code": null,
"e": 3450,
"s": 3417,
"text": "sanskargargee20a14724 months ago"
},
{
"code": null,
"e": 3468,
"s": 3450,
"text": "Time = 0.1 / 12.8"
},
{
"code": null,
"e": 3494,
"s": 3468,
"text": "Time Complexity O(root N)"
},
{
"code": null,
"e": 3522,
"s": 3494,
"text": "Space Complexity O( root N)"
},
{
"code": null,
"e": 3594,
"s": 3526,
"text": "// { Driver Code Starts#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 4123,
"s": 3596,
"text": "// } Driver Code Endsclass Solution { public: int kThSmallestFactor(int N , int K) { // code here vector <int> ans; ans.push_back(1); // Square Root of N loop to find the factor upto root N for(int i=2 ; i*i <= N ; i++){ if(N%i == 0) ans.push_back(i); } int m=ans.size(); int last = ans[m - 1]; // Imp check if last*last == N then don't push back another factor to avoid redundancy"
},
{
"code": null,
"e": 4479,
"s": 4123,
"text": " if(last*last == N){ m=m-1; // m is reduced by 1 } // Now adding the seconf factor of N from ans vector for(int i=m-1 ; i>=0 ; i--){ ans.push_back(N/ans[i]); } if(K>ans.size()){ return -1; } return ans[K-1]; }};"
},
{
"code": null,
"e": 4592,
"s": 4479,
"text": "// { Driver Code Starts.int main() { int t; cin >> t; while (t--) { int N,K; cin>>N>>K;"
},
{
"code": null,
"e": 4701,
"s": 4592,
"text": " Solution ob; cout << ob.kThSmallestFactor(N,K) << endl; } return 0;} // } Driver Code Ends"
},
{
"code": null,
"e": 4704,
"s": 4701,
"text": "+1"
},
{
"code": null,
"e": 4737,
"s": 4704,
"text": "subhranshubehera99sb4 months ago"
},
{
"code": null,
"e": 4796,
"s": 4737,
"text": "Java code with 100% accuracy and total time taken 3.8/48.7"
},
{
"code": null,
"e": 5236,
"s": 4798,
"text": "class Solution {\n static int kThSmallestFactor(int N , int K) {\n // code here\n int c=0;\n if(K==1) {\n return 1;\n } else if(N<K) {\n return -1;\n }\n for(int i=1;i<=N;i++) {\n if(N%i==0){\n c++;\n }\n if(c==K){\n return i;\n } else if(c>K) {\n return -1;\n }\n }\n \n return -1;\n }\n}"
},
{
"code": null,
"e": 5239,
"s": 5236,
"text": "+1"
},
{
"code": null,
"e": 5267,
"s": 5239,
"text": "aloksinghbais024 months ago"
},
{
"code": null,
"e": 5371,
"s": 5267,
"text": "C++ solution having time complexity as O(sqrt(N)) and space complexity as O(2*sqrt(N)) is as follows :-"
},
{
"code": null,
"e": 5406,
"s": 5373,
"text": "Execution Time :- 0.1 / 12.8 sec"
},
{
"code": null,
"e": 5871,
"s": 5408,
"text": "int kThSmallestFactor(int N , int K) { vector<int> sf,lf; for(int i=1; i<=sqrt(N); i++){ if(N % i == 0){ if(N/i != i) sf.push_back(i), lf.push_back(N/i); else sf.push_back(i); } } reverse(lf.begin(),lf.end()); vector<int> fac; for(auto x: sf) fac.push_back(x); for(auto x: lf) fac.push_back(x); if(K <= fac.size()) return fac[K-1]; return -1; }"
},
{
"code": null,
"e": 6017,
"s": 5871,
"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": 6053,
"s": 6017,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6063,
"s": 6053,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6073,
"s": 6063,
"text": "\nContest\n"
},
{
"code": null,
"e": 6136,
"s": 6073,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6284,
"s": 6136,
"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": 6492,
"s": 6284,
"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": 6598,
"s": 6492,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to display Y-axis labels with more decimal places in R?
|
To display Y-axis labels with more decimal places, we would need to round the values of the vector or column for which we want to create the plot to the appropriate number of decimal places.
After that axis function will be used for creating the graph. Before doing all this, the graph of original values should be created without axes.
Check out the below example to understand how it works.
Following snippet creates a sample data frame −
x<-rnorm(10)
x
The following dataframe is created −
[1] -0.3002845 -0.6121883 1.9147725 -2.1135920 0.6575177 0.3540003
[7] -0.4564178 1.3474739 -0.6195008 -0.7050753
To display Y-axis labels with more decimal places in R, add the following code to the above snippet −
x<-rnorm(10)
plot(x)
If you execute all the above given snippets as a single program, it generates the following output −
To display Y-axis labels with more decimal places in R, add the following code to the above snippet −
x<-rnorm(10)
plot(x,axes=FALSE,frame.plot=TRUE)
If you execute all the above given snippets as a single program, it generates the following output −
To display Y-axis labels with more decimal places in R, add the following code to the above snippet −
x<-rnorm(10)
plot(x,axes=FALSE,frame.plot=TRUE)
Labels<-round(x,3)
axis(2,at=Labels,labels=Labels)
If you execute all the above given snippets as a single program, it generates the following output −
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "To display Y-axis labels with more decimal places, we would need to round the values of the vector or column for which we want to create the plot to the appropriate number of decimal places."
},
{
"code": null,
"e": 1399,
"s": 1253,
"text": "After that axis function will be used for creating the graph. Before doing all this, the graph of original values should be created without axes."
},
{
"code": null,
"e": 1455,
"s": 1399,
"text": "Check out the below example to understand how it works."
},
{
"code": null,
"e": 1503,
"s": 1455,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1518,
"s": 1503,
"text": "x<-rnorm(10)\nx"
},
{
"code": null,
"e": 1555,
"s": 1518,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 1669,
"s": 1555,
"text": "[1] -0.3002845 -0.6121883 1.9147725 -2.1135920 0.6575177 0.3540003\n[7] -0.4564178 1.3474739 -0.6195008 -0.7050753"
},
{
"code": null,
"e": 1771,
"s": 1669,
"text": "To display Y-axis labels with more decimal places in R, add the following code to the above snippet −"
},
{
"code": null,
"e": 1792,
"s": 1771,
"text": "x<-rnorm(10)\nplot(x)"
},
{
"code": null,
"e": 1893,
"s": 1792,
"text": "If you execute all the above given snippets as a single program, it generates the following output −"
},
{
"code": null,
"e": 1995,
"s": 1893,
"text": "To display Y-axis labels with more decimal places in R, add the following code to the above snippet −"
},
{
"code": null,
"e": 2043,
"s": 1995,
"text": "x<-rnorm(10)\nplot(x,axes=FALSE,frame.plot=TRUE)"
},
{
"code": null,
"e": 2144,
"s": 2043,
"text": "If you execute all the above given snippets as a single program, it generates the following output −"
},
{
"code": null,
"e": 2246,
"s": 2144,
"text": "To display Y-axis labels with more decimal places in R, add the following code to the above snippet −"
},
{
"code": null,
"e": 2345,
"s": 2246,
"text": "x<-rnorm(10)\nplot(x,axes=FALSE,frame.plot=TRUE)\nLabels<-round(x,3)\naxis(2,at=Labels,labels=Labels)"
},
{
"code": null,
"e": 2446,
"s": 2345,
"text": "If you execute all the above given snippets as a single program, it generates the following output −"
}
] |
Java program to find the 2nd largest number in an array
|
To find the second largest element of the given array, first of all, sort the array.
Compare the first two elements of the array
If the first element is greater than the second swap them.
Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.
Repeat this till the end of the array.
After sorting an array print the second element from the end of the array.
Live Demo
public class ThirdLargestNumberInAnArray {
public static void main(String args[]){
int temp, size;
int array[] = {10, 20, 25, 63, 96, 57};
size = array.length;
for(int i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(array[i]>array[j]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("Third second largest number is:: "+array[size-2]);
}
}
Third second largest number is:: 63
You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the second element from the end of the array.
Live Demo
import java.util.Arrays;
public class LargestNumberSample {
public static void main(String args[]){
int array[] = {10, 20, 25, 63, 96, 57};
int size = array.length;
Arrays.sort(array);
System.out.println("sorted Array ::"+Arrays.toString(array));
int res = array[size-2];
System.out.println("2nd largest element is ::"+res);
}
}
sorted Array ::[10, 20, 25, 57, 63, 96]
2nd largest element is ::63
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To find the second largest element of the given array, first of all, sort the array."
},
{
"code": null,
"e": 1191,
"s": 1147,
"text": "Compare the first two elements of the array"
},
{
"code": null,
"e": 1250,
"s": 1191,
"text": "If the first element is greater than the second swap them."
},
{
"code": null,
"e": 1342,
"s": 1250,
"text": "Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them."
},
{
"code": null,
"e": 1381,
"s": 1342,
"text": "Repeat this till the end of the array."
},
{
"code": null,
"e": 1456,
"s": 1381,
"text": "After sorting an array print the second element from the end of the array."
},
{
"code": null,
"e": 1466,
"s": 1456,
"text": "Live Demo"
},
{
"code": null,
"e": 1977,
"s": 1466,
"text": "public class ThirdLargestNumberInAnArray {\n public static void main(String args[]){\n int temp, size;\n int array[] = {10, 20, 25, 63, 96, 57};\n size = array.length;\n\n for(int i = 0; i<size; i++ ){\n for(int j = i+1; j<size; j++){\n\n if(array[i]>array[j]){\n temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n }\n }\n System.out.println(\"Third second largest number is:: \"+array[size-2]);\n }\n}"
},
{
"code": null,
"e": 2013,
"s": 1977,
"text": "Third second largest number is:: 63"
},
{
"code": null,
"e": 2173,
"s": 2013,
"text": "You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the second element from the end of the array."
},
{
"code": null,
"e": 2183,
"s": 2173,
"text": "Live Demo"
},
{
"code": null,
"e": 2554,
"s": 2183,
"text": "import java.util.Arrays;\npublic class LargestNumberSample {\n public static void main(String args[]){\n int array[] = {10, 20, 25, 63, 96, 57};\n int size = array.length;\n Arrays.sort(array);\n System.out.println(\"sorted Array ::\"+Arrays.toString(array));\n int res = array[size-2];\n System.out.println(\"2nd largest element is ::\"+res);\n }\n}"
},
{
"code": null,
"e": 2622,
"s": 2554,
"text": "sorted Array ::[10, 20, 25, 57, 63, 96]\n2nd largest element is ::63"
}
] |
How to switch axes in Matplotlib?
|
To switch axes in matplotlib, we can create a figure and add two subplots using subplots() method. Plot curves, extract x and y data, and set these data in a second plotted curve.
Create x and y data points using numpy.
Create x and y data points using numpy.
Create a figure and add a set of two subplots.
Create a figure and add a set of two subplots.
Set the title of the plot on both the axes.
Set the title of the plot on both the axes.
Plot x and y data points using plot() method.
Plot x and y data points using plot() method.
Extract the x and y data points using get_xdata and get_ydata.
Extract the x and y data points using get_xdata and get_ydata.
To switch the axes of the plot, set x_data and y_data of the axis 1 curve to axis 2 curve.
To switch the axes of the plot, set x_data and y_data of the axis 1 curve to axis 2 curve.
Adjust the padding between and around the subplots.
Adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 50)
y = np.sin(x)
f, axes = plt.subplots(2)
axes[0].set_title("First plot on axis")
curve, = axes[0].plot(x, y, c='r')
newx = curve.get_xdata()
newy = curve.get_ydata()
axes[1].set_title("Switch of first plot")
curve2, = axes[1].plot(x, y, c='r')
curve2.set_xdata(newy)
curve2.set_ydata(newx)
plt.show()
|
[
{
"code": null,
"e": 1242,
"s": 1062,
"text": "To switch axes in matplotlib, we can create a figure and add two subplots using subplots() method. Plot curves, extract x and y data, and set these data in a second plotted curve."
},
{
"code": null,
"e": 1282,
"s": 1242,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1322,
"s": 1282,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1369,
"s": 1322,
"text": "Create a figure and add a set of two subplots."
},
{
"code": null,
"e": 1416,
"s": 1369,
"text": "Create a figure and add a set of two subplots."
},
{
"code": null,
"e": 1460,
"s": 1416,
"text": "Set the title of the plot on both the axes."
},
{
"code": null,
"e": 1504,
"s": 1460,
"text": "Set the title of the plot on both the axes."
},
{
"code": null,
"e": 1550,
"s": 1504,
"text": "Plot x and y data points using plot() method."
},
{
"code": null,
"e": 1596,
"s": 1550,
"text": "Plot x and y data points using plot() method."
},
{
"code": null,
"e": 1659,
"s": 1596,
"text": "Extract the x and y data points using get_xdata and get_ydata."
},
{
"code": null,
"e": 1722,
"s": 1659,
"text": "Extract the x and y data points using get_xdata and get_ydata."
},
{
"code": null,
"e": 1813,
"s": 1722,
"text": "To switch the axes of the plot, set x_data and y_data of the axis 1 curve to axis 2 curve."
},
{
"code": null,
"e": 1904,
"s": 1813,
"text": "To switch the axes of the plot, set x_data and y_data of the axis 1 curve to axis 2 curve."
},
{
"code": null,
"e": 1956,
"s": 1904,
"text": "Adjust the padding between and around the subplots."
},
{
"code": null,
"e": 2008,
"s": 1956,
"text": "Adjust the padding between and around the subplots."
},
{
"code": null,
"e": 2050,
"s": 2008,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2092,
"s": 2050,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2562,
"s": 2092,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-2, 2, 50)\ny = np.sin(x)\nf, axes = plt.subplots(2)\naxes[0].set_title(\"First plot on axis\")\ncurve, = axes[0].plot(x, y, c='r')\nnewx = curve.get_xdata()\nnewy = curve.get_ydata()\naxes[1].set_title(\"Switch of first plot\")\ncurve2, = axes[1].plot(x, y, c='r')\ncurve2.set_xdata(newy)\ncurve2.set_ydata(newx)\nplt.show()"
}
] |
Illustration of Central Limit Theorem Using Monte-Carlo Simulation | by Benjamin Obi Tayo Ph.D. | Towards Data Science
|
The Central Limit Theorem (CLT) is one of the most important theorems in statistics and data science. The CLT states that the sample mean of a probability distribution sample is a random variable with a mean value given by population mean and standard deviation given by population standard deviation divided by square root of N, where N is the sample size.
We can illustrate the central limit theorem using the uniform distribution. Any probability distribution such as normal, Poisson, Binomial would work as well.
Lets consider a uniform distribution defined in the range [a, b]. The probability distribution function, mean, and standard deviation are obtained from Wolfram Mathematica Website.
a) Population mean
For a uniform distribution, the population mean is given by
b) Population standard deviation
For a uniform distribution, the population standard deviation is given by
The Central Limit Theorem states that the mean of any sample with size N is a random variable with mean value of
and standard deviation given by
Let us now illustrate our calculation by considering a uniform distribution with a = 0, b = 100. We shall illustrate the Central Limit Theorem by considering the population (N →Infinity) and two samples, one with N = 100, and the other with N = 1000.
a) Population Mean
Using the equations above, the population mean for a uniform distribution with a = 0, and b = 100 is
b) Population Standard Deviation
Similarly, the population standard deviation of a uniform distribution with a = 0 and b = 100 is
c) Sample 1 with N = 100
d) Sample 2 with N = 1000
For Monte-Carlo simulations, we generate a very large population of size 10,000.
a) Population Mean
pop_mean <- mean(runif(10000,0,100))
Output is 50.0 which agrees with our analytical results.
b) Population Standard Deviation
pop_sd <- sd(runif(10000,0,100))
Output is 28.9 which agrees with out analytical results.
c) Monte-Carlo Code for two Samples with N = 100 and N = 1000
library(tidyverse)a <-0b <-100mean_function <-function(x)mean(runif(x,a,b))B <-10000sample_1 <-replicate(B, {mean_function(100)})sample_2 <-replicate(B, {mean_function(1000)})
Outputs from Monte-Carlo Simulation
mean(sample_1)
yields 50.0 which is consistent with our analytical results.
sd(sample_1)
yields 2.83 which is consistent with our analytical results (2.89).
mean(sample_2)
yields 50.0 which is consistent with our analytical results.
sd(sample_2)
yields 0.888 which is consistent with our analytical results (0.914).
d) Generate Probability Distributions of the Mean for N = 100 and N = 1000.
X <- data.frame(sample_size=rep(c("N=100","N=1000"), times=c(B,B)),mean=c(sample_1,sample_2))X%>%ggplot(aes(mean,color=sample_size))+ geom_density(aes(mean,fill=sample_size),alpha=0.2)+ theme_bw()
The figure shows that the sample mean is a random variable that is normally distributed with a mean value equal to the population mean, and a standard deviation that is given by the population standard deviation divided by the square root of the sample size. Since the sample standard deviation (uncertainty) is inversely proportional to the sample size, the precision of the calculated mean value decreases with larger sample sizes.
We’ve shown that the sample mean of any probability distribution is a random variable with mean value equal to the population mean and standard deviation of the mean given by:
Based on this equation, we can observe that as the sample size N → Infinity, the uncertainty or standard deviation of the mean goes to zero. This means that the larger the size of our dataset, the better, as larger samples lead to smaller variance error.
In summary, we’ve discussed how the central limit theorem can be proved using Monte-Carlo simulation. The central limit theorem is one of the most important theorems in statistics and data science, so as a practicing data science, familiarity with the mathematical foundations of the central limit theorem is very important.
|
[
{
"code": null,
"e": 404,
"s": 46,
"text": "The Central Limit Theorem (CLT) is one of the most important theorems in statistics and data science. The CLT states that the sample mean of a probability distribution sample is a random variable with a mean value given by population mean and standard deviation given by population standard deviation divided by square root of N, where N is the sample size."
},
{
"code": null,
"e": 563,
"s": 404,
"text": "We can illustrate the central limit theorem using the uniform distribution. Any probability distribution such as normal, Poisson, Binomial would work as well."
},
{
"code": null,
"e": 744,
"s": 563,
"text": "Lets consider a uniform distribution defined in the range [a, b]. The probability distribution function, mean, and standard deviation are obtained from Wolfram Mathematica Website."
},
{
"code": null,
"e": 763,
"s": 744,
"text": "a) Population mean"
},
{
"code": null,
"e": 823,
"s": 763,
"text": "For a uniform distribution, the population mean is given by"
},
{
"code": null,
"e": 856,
"s": 823,
"text": "b) Population standard deviation"
},
{
"code": null,
"e": 930,
"s": 856,
"text": "For a uniform distribution, the population standard deviation is given by"
},
{
"code": null,
"e": 1043,
"s": 930,
"text": "The Central Limit Theorem states that the mean of any sample with size N is a random variable with mean value of"
},
{
"code": null,
"e": 1075,
"s": 1043,
"text": "and standard deviation given by"
},
{
"code": null,
"e": 1326,
"s": 1075,
"text": "Let us now illustrate our calculation by considering a uniform distribution with a = 0, b = 100. We shall illustrate the Central Limit Theorem by considering the population (N →Infinity) and two samples, one with N = 100, and the other with N = 1000."
},
{
"code": null,
"e": 1345,
"s": 1326,
"text": "a) Population Mean"
},
{
"code": null,
"e": 1446,
"s": 1345,
"text": "Using the equations above, the population mean for a uniform distribution with a = 0, and b = 100 is"
},
{
"code": null,
"e": 1479,
"s": 1446,
"text": "b) Population Standard Deviation"
},
{
"code": null,
"e": 1576,
"s": 1479,
"text": "Similarly, the population standard deviation of a uniform distribution with a = 0 and b = 100 is"
},
{
"code": null,
"e": 1601,
"s": 1576,
"text": "c) Sample 1 with N = 100"
},
{
"code": null,
"e": 1627,
"s": 1601,
"text": "d) Sample 2 with N = 1000"
},
{
"code": null,
"e": 1708,
"s": 1627,
"text": "For Monte-Carlo simulations, we generate a very large population of size 10,000."
},
{
"code": null,
"e": 1727,
"s": 1708,
"text": "a) Population Mean"
},
{
"code": null,
"e": 1764,
"s": 1727,
"text": "pop_mean <- mean(runif(10000,0,100))"
},
{
"code": null,
"e": 1821,
"s": 1764,
"text": "Output is 50.0 which agrees with our analytical results."
},
{
"code": null,
"e": 1854,
"s": 1821,
"text": "b) Population Standard Deviation"
},
{
"code": null,
"e": 1887,
"s": 1854,
"text": "pop_sd <- sd(runif(10000,0,100))"
},
{
"code": null,
"e": 1944,
"s": 1887,
"text": "Output is 28.9 which agrees with out analytical results."
},
{
"code": null,
"e": 2006,
"s": 1944,
"text": "c) Monte-Carlo Code for two Samples with N = 100 and N = 1000"
},
{
"code": null,
"e": 2182,
"s": 2006,
"text": "library(tidyverse)a <-0b <-100mean_function <-function(x)mean(runif(x,a,b))B <-10000sample_1 <-replicate(B, {mean_function(100)})sample_2 <-replicate(B, {mean_function(1000)})"
},
{
"code": null,
"e": 2218,
"s": 2182,
"text": "Outputs from Monte-Carlo Simulation"
},
{
"code": null,
"e": 2233,
"s": 2218,
"text": "mean(sample_1)"
},
{
"code": null,
"e": 2294,
"s": 2233,
"text": "yields 50.0 which is consistent with our analytical results."
},
{
"code": null,
"e": 2307,
"s": 2294,
"text": "sd(sample_1)"
},
{
"code": null,
"e": 2375,
"s": 2307,
"text": "yields 2.83 which is consistent with our analytical results (2.89)."
},
{
"code": null,
"e": 2390,
"s": 2375,
"text": "mean(sample_2)"
},
{
"code": null,
"e": 2451,
"s": 2390,
"text": "yields 50.0 which is consistent with our analytical results."
},
{
"code": null,
"e": 2464,
"s": 2451,
"text": "sd(sample_2)"
},
{
"code": null,
"e": 2534,
"s": 2464,
"text": "yields 0.888 which is consistent with our analytical results (0.914)."
},
{
"code": null,
"e": 2610,
"s": 2534,
"text": "d) Generate Probability Distributions of the Mean for N = 100 and N = 1000."
},
{
"code": null,
"e": 2828,
"s": 2610,
"text": "X <- data.frame(sample_size=rep(c(\"N=100\",\"N=1000\"), times=c(B,B)),mean=c(sample_1,sample_2))X%>%ggplot(aes(mean,color=sample_size))+ geom_density(aes(mean,fill=sample_size),alpha=0.2)+ theme_bw()"
},
{
"code": null,
"e": 3262,
"s": 2828,
"text": "The figure shows that the sample mean is a random variable that is normally distributed with a mean value equal to the population mean, and a standard deviation that is given by the population standard deviation divided by the square root of the sample size. Since the sample standard deviation (uncertainty) is inversely proportional to the sample size, the precision of the calculated mean value decreases with larger sample sizes."
},
{
"code": null,
"e": 3438,
"s": 3262,
"text": "We’ve shown that the sample mean of any probability distribution is a random variable with mean value equal to the population mean and standard deviation of the mean given by:"
},
{
"code": null,
"e": 3693,
"s": 3438,
"text": "Based on this equation, we can observe that as the sample size N → Infinity, the uncertainty or standard deviation of the mean goes to zero. This means that the larger the size of our dataset, the better, as larger samples lead to smaller variance error."
}
] |
How to extract initial, last, or middle characters from a string in R?
|
In Text analysis, we might want to extract characters from a single string or from a vector of strings. This extraction might be required to create a new string with some specific words required for further analysis. We can do this with the help of str_sub function of stringr package.
Consider the below string −
> x1<-"Removing harmful things from the road is an act of charity"
Loading the stringr package −
> library(stringr)
> str_sub(x1,1,8)
[1] "Removing"
> str_sub(x1,1,23)
[1] "Removing harmful things"
> str_sub(x1,29,37)
[1] " the road"
> str_sub(x1,30,37)
[1] "the road"
> str_sub(x1,-58,-51)
[1] "Removing"
> str_sub(x1,-58,-1)
[1] "Removing harmful things from the road is an act of charity"
> str_sub(x1,-7,-1)
[1] "charity"
> str_sub(x1,-14,-1)
[1] "act of charity"
> str_sub(x1,-17,-1)
[1] "an act of charity"
Let’s have a look at extraction of number of characters for a vector of strings −
> x1<-c("Removing", "harmful", "things", "from", "the", "road", "is", "an", "act", "of", "charity")
> str_sub(x1,1,2)
[1] "Re" "ha" "th" "fr" "th" "ro" "is" "an" "ac" "of" "ch"
> str_sub(x1,1,3)
[1] "Rem" "har" "thi" "fro" "the" "roa" "is" "an" "act" "of" "cha"
> str_sub(x1,1,10)
[1] "Removing" "harmful" "things" "from" "the" "road"
[7] "is" "an" "act" "of" "charity"
> str_sub(x1,-7,-2)
[1] "emovin" "harmfu" "thing" "fro" "th" "roa" "i" "a"
[9] "ac" "o" "charit"
> str_sub(x1,-7,-1)
[1] "emoving" "harmful" "things" "from" "the" "road" "is"
[8] "an" "act" "of" "charity"
> str_sub(x1,-10,-1)
[1] "Removing" "harmful" "things" "from" "the" "road"
[7] "is" "an" "act" "of" "charity"
|
[
{
"code": null,
"e": 1348,
"s": 1062,
"text": "In Text analysis, we might want to extract characters from a single string or from a vector of strings. This extraction might be required to create a new string with some specific words required for further analysis. We can do this with the help of str_sub function of stringr package."
},
{
"code": null,
"e": 1376,
"s": 1348,
"text": "Consider the below string −"
},
{
"code": null,
"e": 1443,
"s": 1376,
"text": "> x1<-\"Removing harmful things from the road is an act of charity\""
},
{
"code": null,
"e": 1473,
"s": 1443,
"text": "Loading the stringr package −"
},
{
"code": null,
"e": 1889,
"s": 1473,
"text": "> library(stringr)\n> str_sub(x1,1,8)\n[1] \"Removing\"\n> str_sub(x1,1,23)\n[1] \"Removing harmful things\"\n> str_sub(x1,29,37)\n[1] \" the road\"\n> str_sub(x1,30,37)\n[1] \"the road\"\n> str_sub(x1,-58,-51)\n[1] \"Removing\"\n> str_sub(x1,-58,-1)\n[1] \"Removing harmful things from the road is an act of charity\"\n> str_sub(x1,-7,-1)\n[1] \"charity\"\n> str_sub(x1,-14,-1)\n[1] \"act of charity\"\n> str_sub(x1,-17,-1)\n[1] \"an act of charity\""
},
{
"code": null,
"e": 1971,
"s": 1889,
"text": "Let’s have a look at extraction of number of characters for a vector of strings −"
},
{
"code": null,
"e": 2679,
"s": 1971,
"text": "> x1<-c(\"Removing\", \"harmful\", \"things\", \"from\", \"the\", \"road\", \"is\", \"an\", \"act\", \"of\", \"charity\")\n> str_sub(x1,1,2)\n[1] \"Re\" \"ha\" \"th\" \"fr\" \"th\" \"ro\" \"is\" \"an\" \"ac\" \"of\" \"ch\"\n> str_sub(x1,1,3)\n[1] \"Rem\" \"har\" \"thi\" \"fro\" \"the\" \"roa\" \"is\" \"an\" \"act\" \"of\" \"cha\"\n> str_sub(x1,1,10)\n[1] \"Removing\" \"harmful\" \"things\" \"from\" \"the\" \"road\"\n[7] \"is\" \"an\" \"act\" \"of\" \"charity\"\n> str_sub(x1,-7,-2)\n[1] \"emovin\" \"harmfu\" \"thing\" \"fro\" \"th\" \"roa\" \"i\" \"a\"\n[9] \"ac\" \"o\" \"charit\"\n> str_sub(x1,-7,-1)\n[1] \"emoving\" \"harmful\" \"things\" \"from\" \"the\" \"road\" \"is\"\n[8] \"an\" \"act\" \"of\" \"charity\"\n> str_sub(x1,-10,-1)\n[1] \"Removing\" \"harmful\" \"things\" \"from\" \"the\" \"road\"\n[7] \"is\" \"an\" \"act\" \"of\" \"charity\""
}
] |
How to get the sum of a specific column of a dataframe in Pandas Python?
|
Sometimes, it may be required to get the sum of a specific column. This is where the ‘sum’ function can be used.
The column whose sum needs to be computed can be passed as a value to the sum function. The index of the column can also be passed to find the sum.
Let us see a demonstration of the same −
Live Demo
import pandas as pd
my_data = {'Name':pd.Series(['Tom','Jane','Vin','Eve','Will']),'Age':pd.Series([45, 67, 89, 12, 23]),'value':pd.Series([8.79,23.24,31.98,78.56,90.20])
}
print("The dataframe is :")
my_df = pd.DataFrame(my_data)
print(my_df)
print("The sum of 'age' column is :")
print(my_df.sum(1))
The dataframe is :
Name Age value
0 Tom 45 8.79
1 Jane 67 23.24
2 Vin 89 31.98
3 Eve 12 78.56
4 Will 23 90.20
The sum of 'age' column is :
0 53.79
1 90.24
2 120.98
3 90.56
4 113.20
dtype: float64
The required libraries are imported, and given alias names for ease of use.
The required libraries are imported, and given alias names for ease of use.
Dictionary of series consisting of key and value is created, wherein a value is actually a series data structure.
Dictionary of series consisting of key and value is created, wherein a value is actually a series data structure.
This dictionary is later passed as a parameter to the ‘Dataframe’ function present in the ‘pandas’ library
This dictionary is later passed as a parameter to the ‘Dataframe’ function present in the ‘pandas’ library
The dataframe is printed on the console.
The dataframe is printed on the console.
We are looking at computing the sum of the ‘Age’ column.
We are looking at computing the sum of the ‘Age’ column.
The name of the column whose sum needs to be computed is passed as a parameter to the ‘sum’ function.
The name of the column whose sum needs to be computed is passed as a parameter to the ‘sum’ function.
The sum is printed on the console.
The sum is printed on the console.
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "Sometimes, it may be required to get the sum of a specific column. This is where the ‘sum’ function can be used."
},
{
"code": null,
"e": 1323,
"s": 1175,
"text": "The column whose sum needs to be computed can be passed as a value to the sum function. The index of the column can also be passed to find the sum."
},
{
"code": null,
"e": 1364,
"s": 1323,
"text": "Let us see a demonstration of the same −"
},
{
"code": null,
"e": 1375,
"s": 1364,
"text": " Live Demo"
},
{
"code": null,
"e": 1677,
"s": 1375,
"text": "import pandas as pd\nmy_data = {'Name':pd.Series(['Tom','Jane','Vin','Eve','Will']),'Age':pd.Series([45, 67, 89, 12, 23]),'value':pd.Series([8.79,23.24,31.98,78.56,90.20])\n}\nprint(\"The dataframe is :\")\nmy_df = pd.DataFrame(my_data)\nprint(my_df)\nprint(\"The sum of 'age' column is :\")\nprint(my_df.sum(1))"
},
{
"code": null,
"e": 1911,
"s": 1677,
"text": "The dataframe is :\n Name Age value\n0 Tom 45 8.79\n1 Jane 67 23.24\n2 Vin 89 31.98\n3 Eve 12 78.56\n4 Will 23 90.20\nThe sum of 'age' column is :\n0 53.79\n1 90.24\n2 120.98\n3 90.56\n4 113.20\ndtype: float64"
},
{
"code": null,
"e": 1987,
"s": 1911,
"text": "The required libraries are imported, and given alias names for ease of use."
},
{
"code": null,
"e": 2063,
"s": 1987,
"text": "The required libraries are imported, and given alias names for ease of use."
},
{
"code": null,
"e": 2177,
"s": 2063,
"text": "Dictionary of series consisting of key and value is created, wherein a value is actually a series data structure."
},
{
"code": null,
"e": 2291,
"s": 2177,
"text": "Dictionary of series consisting of key and value is created, wherein a value is actually a series data structure."
},
{
"code": null,
"e": 2398,
"s": 2291,
"text": "This dictionary is later passed as a parameter to the ‘Dataframe’ function present in the ‘pandas’ library"
},
{
"code": null,
"e": 2505,
"s": 2398,
"text": "This dictionary is later passed as a parameter to the ‘Dataframe’ function present in the ‘pandas’ library"
},
{
"code": null,
"e": 2546,
"s": 2505,
"text": "The dataframe is printed on the console."
},
{
"code": null,
"e": 2587,
"s": 2546,
"text": "The dataframe is printed on the console."
},
{
"code": null,
"e": 2644,
"s": 2587,
"text": "We are looking at computing the sum of the ‘Age’ column."
},
{
"code": null,
"e": 2701,
"s": 2644,
"text": "We are looking at computing the sum of the ‘Age’ column."
},
{
"code": null,
"e": 2803,
"s": 2701,
"text": "The name of the column whose sum needs to be computed is passed as a parameter to the ‘sum’ function."
},
{
"code": null,
"e": 2905,
"s": 2803,
"text": "The name of the column whose sum needs to be computed is passed as a parameter to the ‘sum’ function."
},
{
"code": null,
"e": 2940,
"s": 2905,
"text": "The sum is printed on the console."
},
{
"code": null,
"e": 2975,
"s": 2940,
"text": "The sum is printed on the console."
}
] |
How can I import modules for a Python Azure Function?
|
As of writing this, Python support for Azure Functions is experimental. So right now there is no way to directly get a module from a package manager to be installed on your instance. You'll need to bring your own modules with code. No modules are available by default on Azure Functions. You can add them by uploading it via the portal UX or kudu (which is handy for lots of files).
If you don't mind using virtualenv, there is an alternative.
Create your python script on Azure Functions.
Create your python script on Azure Functions.
Open a Kudu console and cd to your script location.
Open a Kudu console and cd to your script location.
Create a virtualenv in this folder (python -m virtualenv myvenv)
Create a virtualenv in this folder (python -m virtualenv myvenv)
Load this venv (cd myvenv/Scripts and call activate.bat). Now your shell should be prefixed by (myvenv).
Load this venv (cd myvenv/Scripts and call activate.bat). Now your shell should be prefixed by (myvenv).
Update pip (python -m pip install -U pip)
Update pip (python -m pip install -U pip)
Install your dependencies using pip. (python -m pip install django)
Install your dependencies using pip. (python -m pip install django)
Now wherever you need to import scripts, append the sys.path variable with this env. For example,
import sys, os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), 'myvenv/Lib/site-packages')))
|
[
{
"code": null,
"e": 1445,
"s": 1062,
"text": "As of writing this, Python support for Azure Functions is experimental. So right now there is no way to directly get a module from a package manager to be installed on your instance. You'll need to bring your own modules with code. No modules are available by default on Azure Functions. You can add them by uploading it via the portal UX or kudu (which is handy for lots of files)."
},
{
"code": null,
"e": 1506,
"s": 1445,
"text": "If you don't mind using virtualenv, there is an alternative."
},
{
"code": null,
"e": 1552,
"s": 1506,
"text": "Create your python script on Azure Functions."
},
{
"code": null,
"e": 1598,
"s": 1552,
"text": "Create your python script on Azure Functions."
},
{
"code": null,
"e": 1650,
"s": 1598,
"text": "Open a Kudu console and cd to your script location."
},
{
"code": null,
"e": 1702,
"s": 1650,
"text": "Open a Kudu console and cd to your script location."
},
{
"code": null,
"e": 1767,
"s": 1702,
"text": "Create a virtualenv in this folder (python -m virtualenv myvenv)"
},
{
"code": null,
"e": 1832,
"s": 1767,
"text": "Create a virtualenv in this folder (python -m virtualenv myvenv)"
},
{
"code": null,
"e": 1937,
"s": 1832,
"text": "Load this venv (cd myvenv/Scripts and call activate.bat). Now your shell should be prefixed by (myvenv)."
},
{
"code": null,
"e": 2042,
"s": 1937,
"text": "Load this venv (cd myvenv/Scripts and call activate.bat). Now your shell should be prefixed by (myvenv)."
},
{
"code": null,
"e": 2084,
"s": 2042,
"text": "Update pip (python -m pip install -U pip)"
},
{
"code": null,
"e": 2126,
"s": 2084,
"text": "Update pip (python -m pip install -U pip)"
},
{
"code": null,
"e": 2194,
"s": 2126,
"text": "Install your dependencies using pip. (python -m pip install django)"
},
{
"code": null,
"e": 2262,
"s": 2194,
"text": "Install your dependencies using pip. (python -m pip install django)"
},
{
"code": null,
"e": 2360,
"s": 2262,
"text": "Now wherever you need to import scripts, append the sys.path variable with this env. For example,"
},
{
"code": null,
"e": 2484,
"s": 2360,
"text": "import sys, os.path\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), 'myvenv/Lib/site-packages')))"
}
] |
Mahotas - Haralick features - GeeksforGeeks
|
30 Jun, 2021
In this article we will see how we can get the haralick features of image in mahotas. Haralick texture features are calculated from a Gray Level Co-occurrence Matrix, (GLCM), a matrix that counts the co-occurrence of neighboring gray levels in the image. The GLCM is a square matrix that has the dimension of the number of gray levels N in the region of interest (ROI). For this we are going to use the fluorescent microscopy image from a nuclear segmentation benchmark. We can get the image with the help of command given below
mahotas.demos.nuclear_image()
Below is the nuclear_image
In order to do this we will use mahotas.features.haralick method
Syntax : mahotas.features.haralick(img)Argument : It takes image object as argumentReturn : It returns numpy.ndarray
Note : The input of the this should should be the filtered image or loaded as greyIn order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this
image = image[:, :, 0]
Example 1 :
Python3
# importing various librariesimport mahotasimport mahotas.demosimport mahotas as mhimport numpy as npfrom pylab import imshow, show # loading nuclear imagenuclear = mahotas.demos.nuclear_image() # filtering imagenuclear = nuclear[:, :, 0] # adding gaussian filternuclear = mahotas.gaussian_filter(nuclear, 4) # setting thresholdthreshed = (nuclear > nuclear.mean()) # making is labeled imagelabeled, n = mahotas.label(threshed) # showing imageprint("Labelled Image")imshow(labeled)show() # getting haralick featuresh_feature = mahotas.features.haralick(labelled) # showing the featureprint("Haralick Features")imshow(h_feature)show()
Output :
Example 2 :
Python3
# importing required librariesimport numpy as npimport mahotasfrom pylab import imshow, show # loading imageimg = mahotas.imread('dog_image.png') # filtering the imageimg = img[:, :, 0] # setting gaussian filtergaussian = mahotas.gaussian_filter(img, 15) # setting threshold valuegaussian = (gaussian > gaussian.mean()) # making is labelled imagelabeled, n = mahotas.label(gaussian) # showing imageprint("Labelled Image")imshow(labelled)show() # getting haralick featuresh_feature = mahotas.features.haralick(labelled) # showing the featureprint("Haralick Features")imshow(h_feature)show()
Output :
arorakashish0911
simranarora5sos
Python-Mahotas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25843,
"s": 25815,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26373,
"s": 25843,
"text": "In this article we will see how we can get the haralick features of image in mahotas. Haralick texture features are calculated from a Gray Level Co-occurrence Matrix, (GLCM), a matrix that counts the co-occurrence of neighboring gray levels in the image. The GLCM is a square matrix that has the dimension of the number of gray levels N in the region of interest (ROI). For this we are going to use the fluorescent microscopy image from a nuclear segmentation benchmark. We can get the image with the help of command given below "
},
{
"code": null,
"e": 26403,
"s": 26373,
"text": "mahotas.demos.nuclear_image()"
},
{
"code": null,
"e": 26432,
"s": 26403,
"text": "Below is the nuclear_image "
},
{
"code": null,
"e": 26499,
"s": 26432,
"text": "In order to do this we will use mahotas.features.haralick method "
},
{
"code": null,
"e": 26618,
"s": 26499,
"text": "Syntax : mahotas.features.haralick(img)Argument : It takes image object as argumentReturn : It returns numpy.ndarray "
},
{
"code": null,
"e": 26857,
"s": 26618,
"text": "Note : The input of the this should should be the filtered image or loaded as greyIn order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this "
},
{
"code": null,
"e": 26880,
"s": 26857,
"text": "image = image[:, :, 0]"
},
{
"code": null,
"e": 26894,
"s": 26880,
"text": "Example 1 : "
},
{
"code": null,
"e": 26902,
"s": 26894,
"text": "Python3"
},
{
"code": "# importing various librariesimport mahotasimport mahotas.demosimport mahotas as mhimport numpy as npfrom pylab import imshow, show # loading nuclear imagenuclear = mahotas.demos.nuclear_image() # filtering imagenuclear = nuclear[:, :, 0] # adding gaussian filternuclear = mahotas.gaussian_filter(nuclear, 4) # setting thresholdthreshed = (nuclear > nuclear.mean()) # making is labeled imagelabeled, n = mahotas.label(threshed) # showing imageprint(\"Labelled Image\")imshow(labeled)show() # getting haralick featuresh_feature = mahotas.features.haralick(labelled) # showing the featureprint(\"Haralick Features\")imshow(h_feature)show()",
"e": 27536,
"s": 26902,
"text": null
},
{
"code": null,
"e": 27547,
"s": 27536,
"text": "Output : "
},
{
"code": null,
"e": 27561,
"s": 27547,
"text": "Example 2 : "
},
{
"code": null,
"e": 27569,
"s": 27561,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy as npimport mahotasfrom pylab import imshow, show # loading imageimg = mahotas.imread('dog_image.png') # filtering the imageimg = img[:, :, 0] # setting gaussian filtergaussian = mahotas.gaussian_filter(img, 15) # setting threshold valuegaussian = (gaussian > gaussian.mean()) # making is labelled imagelabeled, n = mahotas.label(gaussian) # showing imageprint(\"Labelled Image\")imshow(labelled)show() # getting haralick featuresh_feature = mahotas.features.haralick(labelled) # showing the featureprint(\"Haralick Features\")imshow(h_feature)show()",
"e": 28169,
"s": 27569,
"text": null
},
{
"code": null,
"e": 28180,
"s": 28169,
"text": "Output : "
},
{
"code": null,
"e": 28199,
"s": 28182,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28215,
"s": 28199,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28230,
"s": 28215,
"text": "Python-Mahotas"
},
{
"code": null,
"e": 28237,
"s": 28230,
"text": "Python"
},
{
"code": null,
"e": 28335,
"s": 28237,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28353,
"s": 28335,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28385,
"s": 28353,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28407,
"s": 28385,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28449,
"s": 28407,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28475,
"s": 28449,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28504,
"s": 28475,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28541,
"s": 28504,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28583,
"s": 28541,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28619,
"s": 28583,
"text": "Convert integer to string in Python"
}
] |
Tensorflow.js tf.matMul() Function - GeeksforGeeks
|
18 May, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
The tf.matMul() function is used to compute the dot product of two matrices, A * B.
Syntax:
tf.matMul (a, b, transposeA?, transposeB?)
Parameters: This function accepts a parameter which is illustrated below:
a: This is the first matrix in dot product operation.
b: This is the second matrix in dot product operation.
transposeA: This is optional and if it is set to true, then a is transposed before multiplication.
transposeB: This is optional and if it is set to true, then b is transposed before multiplication.
Return Value: It returns the dot product of two matrices.
Below are the examples that illustrates the use of tf.matMul() function.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a tensor of some elementslet geek1 = tf.tensor2d([2, 1], [1, 2]);let geek2 = tf.tensor2d([11, 12, 13, 14], [2, 2]); // Calling the .avgPool3d() function over// the above tensor as its parameter and // printing the result.geek1.matMul(geek2).print();
Output:
Tensor
[[35, 38],]
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a tensor of some elementslet geek1 = tf.tensor2d([2, 1], [1, 2]);let geek2 = tf.tensor2d([61, 62, 63, 64], [2, 2]); // Calling the .avgPool3d() function over// the above tensor as its parameter and // printing the result.tf.matMul(geek1, geek2).print();
Output:
Tensor
[[185, 188],]
Reference:https://js.tensorflow.org/api/latest/#matMul
Picked
Tensorflow
Tensorflow.js
JavaScript
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?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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": 26545,
"s": 26517,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 26711,
"s": 26545,
"text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment."
},
{
"code": null,
"e": 26795,
"s": 26711,
"text": "The tf.matMul() function is used to compute the dot product of two matrices, A * B."
},
{
"code": null,
"e": 26803,
"s": 26795,
"text": "Syntax:"
},
{
"code": null,
"e": 26846,
"s": 26803,
"text": "tf.matMul (a, b, transposeA?, transposeB?)"
},
{
"code": null,
"e": 26920,
"s": 26846,
"text": "Parameters: This function accepts a parameter which is illustrated below:"
},
{
"code": null,
"e": 26974,
"s": 26920,
"text": "a: This is the first matrix in dot product operation."
},
{
"code": null,
"e": 27029,
"s": 26974,
"text": "b: This is the second matrix in dot product operation."
},
{
"code": null,
"e": 27128,
"s": 27029,
"text": "transposeA: This is optional and if it is set to true, then a is transposed before multiplication."
},
{
"code": null,
"e": 27227,
"s": 27128,
"text": "transposeB: This is optional and if it is set to true, then b is transposed before multiplication."
},
{
"code": null,
"e": 27285,
"s": 27227,
"text": "Return Value: It returns the dot product of two matrices."
},
{
"code": null,
"e": 27358,
"s": 27285,
"text": "Below are the examples that illustrates the use of tf.matMul() function."
},
{
"code": null,
"e": 27369,
"s": 27358,
"text": "Example 1:"
},
{
"code": null,
"e": 27380,
"s": 27369,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a tensor of some elementslet geek1 = tf.tensor2d([2, 1], [1, 2]);let geek2 = tf.tensor2d([11, 12, 13, 14], [2, 2]); // Calling the .avgPool3d() function over// the above tensor as its parameter and // printing the result.geek1.matMul(geek2).print();",
"e": 27725,
"s": 27380,
"text": null
},
{
"code": null,
"e": 27733,
"s": 27725,
"text": "Output:"
},
{
"code": null,
"e": 27757,
"s": 27733,
"text": "Tensor\n [[35, 38],]"
},
{
"code": null,
"e": 27768,
"s": 27757,
"text": "Example 2:"
},
{
"code": null,
"e": 27779,
"s": 27768,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a tensor of some elementslet geek1 = tf.tensor2d([2, 1], [1, 2]);let geek2 = tf.tensor2d([61, 62, 63, 64], [2, 2]); // Calling the .avgPool3d() function over// the above tensor as its parameter and // printing the result.tf.matMul(geek1, geek2).print();",
"e": 28128,
"s": 27779,
"text": null
},
{
"code": null,
"e": 28136,
"s": 28128,
"text": "Output:"
},
{
"code": null,
"e": 28162,
"s": 28136,
"text": "Tensor\n [[185, 188],]"
},
{
"code": null,
"e": 28217,
"s": 28162,
"text": "Reference:https://js.tensorflow.org/api/latest/#matMul"
},
{
"code": null,
"e": 28224,
"s": 28217,
"text": "Picked"
},
{
"code": null,
"e": 28235,
"s": 28224,
"text": "Tensorflow"
},
{
"code": null,
"e": 28249,
"s": 28235,
"text": "Tensorflow.js"
},
{
"code": null,
"e": 28260,
"s": 28249,
"text": "JavaScript"
},
{
"code": null,
"e": 28277,
"s": 28260,
"text": "Web Technologies"
},
{
"code": null,
"e": 28375,
"s": 28277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28415,
"s": 28375,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28476,
"s": 28415,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28517,
"s": 28476,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28539,
"s": 28517,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28593,
"s": 28539,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28633,
"s": 28593,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28666,
"s": 28633,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28709,
"s": 28666,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28759,
"s": 28709,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Difference between #define and const in Arduino
|
If you've done sufficient Arduino programming, you'd have seen that there are two ways of defining constants.
One way is to use #define, like
#define const_name 3
The other way is to use the const keyword, like
const int var_name = 3;
#define is like a placeholder. The Arduino compiler replaces all mentions of this constant with its value at the compile time. This means that the values defined using #define don't take up any program space.
Variables defined using const, on the other hand, are just normal variables, whose values can't be changed. They take up program memory space, and have a type (which is advantageous in many situations).
In general, it is preferred to use const over #define, for defining constants.
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "If you've done sufficient Arduino programming, you'd have seen that there are two ways of defining constants."
},
{
"code": null,
"e": 1204,
"s": 1172,
"text": "One way is to use #define, like"
},
{
"code": null,
"e": 1225,
"s": 1204,
"text": "#define const_name 3"
},
{
"code": null,
"e": 1273,
"s": 1225,
"text": "The other way is to use the const keyword, like"
},
{
"code": null,
"e": 1298,
"s": 1273,
"text": "const int var_name = 3;\n"
},
{
"code": null,
"e": 1507,
"s": 1298,
"text": "#define is like a placeholder. The Arduino compiler replaces all mentions of this constant with its value at the compile time. This means that the values defined using #define don't take up any program space."
},
{
"code": null,
"e": 1710,
"s": 1507,
"text": "Variables defined using const, on the other hand, are just normal variables, whose values can't be changed. They take up program memory space, and have a type (which is advantageous in many situations)."
},
{
"code": null,
"e": 1789,
"s": 1710,
"text": "In general, it is preferred to use const over #define, for defining constants."
}
] |
How to get the class of a element which has fired an event using JavaScript/JQuery? - GeeksforGeeks
|
22 May, 2020
Given an HTML document and some event is fired, the task is to get the class of the element that has fired the event. Here are 2 approaches discussed.
Approach 1:
In this article we only use click event, However the approach can be applied to any event
onCLick() event is used in this approach.
This this.getAttribute(‘class’) method returns the class of the element on which event occurred. When user clicks on any element then this click event fires and we detect the class of element.
Use onCLick = function(this.getAttribute(‘class’)) to get the class name of the particular element.
Example:This example implements the above approach.
<!DOCTYPE html><html> <head> <title> Getting the class of the element that fired an event using JavaScript. </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } #gfg { color: green; font-size: 20px; font-weight: bold; } </style> </head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <p> Click on the DIV box or button to get Class of the element that fired click event. </p> <div class="DIV" id="div" onClick="GFG_click(this.getAttribute('class'));"> This is Div box. </div> <br /> <button class="button" id="button" onClick="GFG_click(this.getAttribute('class'));"> Button </button> <p id="gfg"></p> <script> var el_down = document.getElementById("gfg"); function GFG_click(className) { // This function is called, when the // click event occurs on any element. // get the classname of element. el_down.innerHTML = "Class = " + className; } </script> </body></html>
Output:
Approach 2:
onCLick() event is used in this approach.
This $(this).attr(‘class’) method returns the class of the element on which event occurred. Whichever element has fired the event we can detect its class.
Use onCLick = function($(this).attr(‘class’)) to get the class name of the element which has fired the event.
Example: This example implements the above approach.
<!DOCTYPE html><html> <head> <title> Getting the class of the element that fired an event using JavaScript. </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } #gfg { color: green; font-size: 20px; font-weight: bold; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> </head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <p> Click on the DIV box or button to get Class of the element that fired click event. </p> <div class="DIV" id="div" onClick="GFG_click($(this).attr('class'));"> This is Div box. </div> <br /> <button class="button" id="button" onClick="GFG_click($(this).attr('class'));"> Button </button> <p id="gfg"></p> <script> var el_down = document.getElementById("gfg"); function GFG_click(className) { // This function is called, when the // Click event occurs on any element. // Get the class Name. el_down.innerHTML = "Class = " + className; } </script> </body></html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
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 ?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
|
[
{
"code": null,
"e": 26666,
"s": 26638,
"text": "\n22 May, 2020"
},
{
"code": null,
"e": 26817,
"s": 26666,
"text": "Given an HTML document and some event is fired, the task is to get the class of the element that has fired the event. Here are 2 approaches discussed."
},
{
"code": null,
"e": 26829,
"s": 26817,
"text": "Approach 1:"
},
{
"code": null,
"e": 26919,
"s": 26829,
"text": "In this article we only use click event, However the approach can be applied to any event"
},
{
"code": null,
"e": 26961,
"s": 26919,
"text": "onCLick() event is used in this approach."
},
{
"code": null,
"e": 27154,
"s": 26961,
"text": "This this.getAttribute(‘class’) method returns the class of the element on which event occurred. When user clicks on any element then this click event fires and we detect the class of element."
},
{
"code": null,
"e": 27254,
"s": 27154,
"text": "Use onCLick = function(this.getAttribute(‘class’)) to get the class name of the particular element."
},
{
"code": null,
"e": 27306,
"s": 27254,
"text": "Example:This example implements the above approach."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Getting the class of the element that fired an event using JavaScript. </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } #gfg { color: green; font-size: 20px; font-weight: bold; } </style> </head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> Click on the DIV box or button to get Class of the element that fired click event. </p> <div class=\"DIV\" id=\"div\" onClick=\"GFG_click(this.getAttribute('class'));\"> This is Div box. </div> <br /> <button class=\"button\" id=\"button\" onClick=\"GFG_click(this.getAttribute('class'));\"> Button </button> <p id=\"gfg\"></p> <script> var el_down = document.getElementById(\"gfg\"); function GFG_click(className) { // This function is called, when the // click event occurs on any element. // get the classname of element. el_down.innerHTML = \"Class = \" + className; } </script> </body></html>",
"e": 28765,
"s": 27306,
"text": null
},
{
"code": null,
"e": 28773,
"s": 28765,
"text": "Output:"
},
{
"code": null,
"e": 28785,
"s": 28773,
"text": "Approach 2:"
},
{
"code": null,
"e": 28827,
"s": 28785,
"text": "onCLick() event is used in this approach."
},
{
"code": null,
"e": 28982,
"s": 28827,
"text": "This $(this).attr(‘class’) method returns the class of the element on which event occurred. Whichever element has fired the event we can detect its class."
},
{
"code": null,
"e": 29092,
"s": 28982,
"text": "Use onCLick = function($(this).attr(‘class’)) to get the class name of the element which has fired the event."
},
{
"code": null,
"e": 29145,
"s": 29092,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Getting the class of the element that fired an event using JavaScript. </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } #gfg { color: green; font-size: 20px; font-weight: bold; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> </head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> Click on the DIV box or button to get Class of the element that fired click event. </p> <div class=\"DIV\" id=\"div\" onClick=\"GFG_click($(this).attr('class'));\"> This is Div box. </div> <br /> <button class=\"button\" id=\"button\" onClick=\"GFG_click($(this).attr('class'));\"> Button </button> <p id=\"gfg\"></p> <script> var el_down = document.getElementById(\"gfg\"); function GFG_click(className) { // This function is called, when the // Click event occurs on any element. // Get the class Name. el_down.innerHTML = \"Class = \" + className; } </script> </body></html>",
"e": 30672,
"s": 29145,
"text": null
},
{
"code": null,
"e": 30680,
"s": 30672,
"text": "Output:"
},
{
"code": null,
"e": 30689,
"s": 30680,
"text": "CSS-Misc"
},
{
"code": null,
"e": 30699,
"s": 30689,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30715,
"s": 30699,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30719,
"s": 30715,
"text": "CSS"
},
{
"code": null,
"e": 30724,
"s": 30719,
"text": "HTML"
},
{
"code": null,
"e": 30735,
"s": 30724,
"text": "JavaScript"
},
{
"code": null,
"e": 30742,
"s": 30735,
"text": "JQuery"
},
{
"code": null,
"e": 30759,
"s": 30742,
"text": "Web Technologies"
},
{
"code": null,
"e": 30786,
"s": 30759,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30791,
"s": 30786,
"text": "HTML"
},
{
"code": null,
"e": 30889,
"s": 30791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30937,
"s": 30889,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30992,
"s": 30937,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 31029,
"s": 30992,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31093,
"s": 31029,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 31132,
"s": 31093,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 31180,
"s": 31132,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31240,
"s": 31180,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31293,
"s": 31240,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 31354,
"s": 31293,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Line Splicing in C/C++ - GeeksforGeeks
|
13 Apr, 2021
While writing a program, sometimes we give comment about the working of the code in the comment section with the help of single/double comment line. But we had never thought that if at the end of this comment line if we use \(backslash) character then what will happen?The answer of the above question is line Splicing. Lines terminated by a \ are spliced together with the next line very early in the process of translation. §2.2 Phases of translation. Actually whenever at the end of the comment line if we use \(backslash) character then it merges the immediate next line with current line which makes the new line also as a comment for the compiler. To avoid this issue multi-line comment can be used.
C
// C program to illustrate the concept of Line splicing.#include <stdio.h>int main(){ // Line Splicing\ printf("Hello GFG\n"); printf("welcome\n"); /* Example 2 - both of the below lines will be printed*/ \ printf("Hello\t"); printf("World"); return (0);}
welcome
Hello World
Explanation: In the above program as we can see when we use the \(backslash) character at the end of comment line. Then the next line of code is treated as comment in the program and the output is welcome. When we use multiline comment this issue get solved and both of the below lines of multiline comment will be printed.This article is contributed by Bishal Kumar Dubey. 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.
souvikr
codergirl321
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
fork() in C
Substring in C++
std::string class in C++
TCP Server-Client implementation in C
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 25775,
"s": 25747,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 26482,
"s": 25775,
"text": "While writing a program, sometimes we give comment about the working of the code in the comment section with the help of single/double comment line. But we had never thought that if at the end of this comment line if we use \\(backslash) character then what will happen?The answer of the above question is line Splicing. Lines terminated by a \\ are spliced together with the next line very early in the process of translation. §2.2 Phases of translation. Actually whenever at the end of the comment line if we use \\(backslash) character then it merges the immediate next line with current line which makes the new line also as a comment for the compiler. To avoid this issue multi-line comment can be used. "
},
{
"code": null,
"e": 26484,
"s": 26482,
"text": "C"
},
{
"code": "// C program to illustrate the concept of Line splicing.#include <stdio.h>int main(){ // Line Splicing\\ printf(\"Hello GFG\\n\"); printf(\"welcome\\n\"); /* Example 2 - both of the below lines will be printed*/ \\ printf(\"Hello\\t\"); printf(\"World\"); return (0);}",
"e": 26761,
"s": 26484,
"text": null
},
{
"code": null,
"e": 26769,
"s": 26761,
"text": "welcome"
},
{
"code": null,
"e": 26781,
"s": 26769,
"text": "Hello World"
},
{
"code": null,
"e": 27535,
"s": 26781,
"text": "Explanation: In the above program as we can see when we use the \\(backslash) character at the end of comment line. Then the next line of code is treated as comment in the program and the output is welcome. When we use multiline comment this issue get solved and both of the below lines of multiline comment will be printed.This article is contributed by Bishal Kumar Dubey. 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": 27543,
"s": 27535,
"text": "souvikr"
},
{
"code": null,
"e": 27556,
"s": 27543,
"text": "codergirl321"
},
{
"code": null,
"e": 27567,
"s": 27556,
"text": "C Language"
},
{
"code": null,
"e": 27571,
"s": 27567,
"text": "C++"
},
{
"code": null,
"e": 27575,
"s": 27571,
"text": "CPP"
},
{
"code": null,
"e": 27673,
"s": 27575,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27695,
"s": 27673,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27707,
"s": 27695,
"text": "fork() in C"
},
{
"code": null,
"e": 27724,
"s": 27707,
"text": "Substring in C++"
},
{
"code": null,
"e": 27749,
"s": 27724,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27787,
"s": 27749,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27805,
"s": 27787,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27824,
"s": 27805,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27870,
"s": 27824,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27913,
"s": 27870,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
How to normalize features in TensorFlow | by Chris Rawles | Towards Data Science
|
TL;DRWhen using tf.estimator, use the normalizer_fn argument in tf.feature_column.numeric_feature to normalize using the same parameters (mean, std, etc.) for training, evaluation, and serving.
def zscore(col): mean = 3.04 std = 1.2 return (col — mean)/stdfeature_name = ‘total_bedrooms’normalized_feature = tf.feature_column.numeric_column( feature_name, normalizer_fn=zscore)
Neural network activations generally like their inputs to be normalized. Normalizing inputs to nodes in a network helps prevent the so-called vanishing (and exploding) gradients. Batch normalization is the most comprehensive approach for normalization, but it incurs an extra cost and may be overkill for your problem. Thus you may just want to normalize your inputs.
There are two approaches to normalizing inputs when using the tf.estimator API (which is the easiest way to build a TensorFlow model): inside the input_fn and while creating a feature_column. I will show you an example to perform the ladder, then I will show you to train multiple models using ML Engine.
Check out this notebook for a full working example.
Normalizing inside the input_fn allows for more flexibility (you can also perform feature engineering here), but I find using the normalizer_fn with tf.feature_column.numeric_column to be more elegant. Here is a basic example:
def zscore(col): mean = 3.04 std = 1.2 return (col — mean)/stdfeature_name = ‘total_bedrooms’normalized_feature = tf.feature_column.numeric_column( feature_name, normalizer_fn=zscore)
Below, I will show an end-to-end example, to get the normalization parameters, then normalize all numeric columns in my dataset.
You should compute the normalization parameters ahead of time on the training set. In this case, I’m using Pandas to get the mean and standard deviation for each numeric column:
Alternatively, TensorFlow Transform provides a scalable approach for normalizing inputs and is particularly suitable for larger datasets. Check out an example here.
After running the above, we return parameters for each columns:
{‘households’: {‘mean’: 501.34073416222617, ‘std’: 382.81658748493305},‘housing_median_age’: {‘mean’: 28.5441089402013, ‘std’: 12.610144469735635},‘median_income’: {‘mean’: 3.8814239564831365, ‘std’: 1.9061255708184284},‘population’: {‘mean’: 1428.941163410302, ‘std’: 1150.5106244960523},‘total_bedrooms’: {‘mean’: 539.6057578448787, ‘std’: 418.76075045523334},‘total_rooms’: {‘mean’: 2642.2929988158676, ‘std’: 2162.649970020439}}
Now you can create the feature columns, using the training means and standard deviations computed above.
NUMERIC_FEATURES = [‘housing_median_age’, ‘total_rooms’, ‘total_bedrooms’, ‘population’, ‘households’, ‘median_income’]feature_columns = create_feature_cols(NUMERIC_FEATURES, use_normalization=True)
And finally you can build the estimator using the feature columns:
model = tf.estimator.DNNRegressor(hidden_units=[10,4], model_dir = outdir, feature_columns = feature_columns)
Normalization is a hyperparameter, and in practice, it would be useful to evaluate different normalization schemes. For example you may want to try training a model just normalizing your features and comparing it to also normalizing inputs to hidden layers using batch normalization.
You can fire off multiple experiments in parallel using Cloud ML Engine. This will be particularly valuable for larger datasets, where you want to leverage the cloud to scale model training. To train with ML Engine, you need to package up the model code, creating task.py and model.py model files. See the repo for an example.
It’s best practice to test the model package locally first to ensure there are no syntactic or semantic errors:
OUTPUT_DIR=’trained_model’export PYTHONPATH=${PYTHONPATH}:${PWD}/model_codepython -m trainer.task — outdir $OUTPUT_DIR — normalize_input 1
After, you can submit a job to ML Engine using `gcloud ml-engine jobs submit training`:
JOBNAME=my_ml_job_$(date -u +%y%m%d_%H%M%S)REGION=’us-central1'BUCKET=’gs://crawles-sandbox’OUTPUT_DIR=$BUCKET/’housing_trained_model’PACKAGE_PATH=$PWD/model_code/trainergcloud ml-engine jobs submit training $JOBNAME \ -- package-path=$PACKAGE_PATH \ -- module-name=trainer.task \ -- region=$REGION \ --staging-bucket=$BUCKET\ -- scale-tier=BASIC \ -- runtime-version=1.8 \ -- \ -- outdir=$OUTPUT_DIR\ -- normalize_input=0
In my case, I trained with and without computing the z-score for the features:
As expected, normalizing the inputs improves the final model performance.
That’s it! If you found this post helpful, please give it a clap so others can find it.
Additional Resources
Normalize using input_fn
Batch Normalization using tf.keras
Standard score (z-score)
Repo with code from this post
|
[
{
"code": null,
"e": 366,
"s": 172,
"text": "TL;DRWhen using tf.estimator, use the normalizer_fn argument in tf.feature_column.numeric_feature to normalize using the same parameters (mean, std, etc.) for training, evaluation, and serving."
},
{
"code": null,
"e": 555,
"s": 366,
"text": "def zscore(col): mean = 3.04 std = 1.2 return (col — mean)/stdfeature_name = ‘total_bedrooms’normalized_feature = tf.feature_column.numeric_column( feature_name, normalizer_fn=zscore)"
},
{
"code": null,
"e": 923,
"s": 555,
"text": "Neural network activations generally like their inputs to be normalized. Normalizing inputs to nodes in a network helps prevent the so-called vanishing (and exploding) gradients. Batch normalization is the most comprehensive approach for normalization, but it incurs an extra cost and may be overkill for your problem. Thus you may just want to normalize your inputs."
},
{
"code": null,
"e": 1228,
"s": 923,
"text": "There are two approaches to normalizing inputs when using the tf.estimator API (which is the easiest way to build a TensorFlow model): inside the input_fn and while creating a feature_column. I will show you an example to perform the ladder, then I will show you to train multiple models using ML Engine."
},
{
"code": null,
"e": 1280,
"s": 1228,
"text": "Check out this notebook for a full working example."
},
{
"code": null,
"e": 1507,
"s": 1280,
"text": "Normalizing inside the input_fn allows for more flexibility (you can also perform feature engineering here), but I find using the normalizer_fn with tf.feature_column.numeric_column to be more elegant. Here is a basic example:"
},
{
"code": null,
"e": 1696,
"s": 1507,
"text": "def zscore(col): mean = 3.04 std = 1.2 return (col — mean)/stdfeature_name = ‘total_bedrooms’normalized_feature = tf.feature_column.numeric_column( feature_name, normalizer_fn=zscore)"
},
{
"code": null,
"e": 1825,
"s": 1696,
"text": "Below, I will show an end-to-end example, to get the normalization parameters, then normalize all numeric columns in my dataset."
},
{
"code": null,
"e": 2003,
"s": 1825,
"text": "You should compute the normalization parameters ahead of time on the training set. In this case, I’m using Pandas to get the mean and standard deviation for each numeric column:"
},
{
"code": null,
"e": 2168,
"s": 2003,
"text": "Alternatively, TensorFlow Transform provides a scalable approach for normalizing inputs and is particularly suitable for larger datasets. Check out an example here."
},
{
"code": null,
"e": 2232,
"s": 2168,
"text": "After running the above, we return parameters for each columns:"
},
{
"code": null,
"e": 2665,
"s": 2232,
"text": "{‘households’: {‘mean’: 501.34073416222617, ‘std’: 382.81658748493305},‘housing_median_age’: {‘mean’: 28.5441089402013, ‘std’: 12.610144469735635},‘median_income’: {‘mean’: 3.8814239564831365, ‘std’: 1.9061255708184284},‘population’: {‘mean’: 1428.941163410302, ‘std’: 1150.5106244960523},‘total_bedrooms’: {‘mean’: 539.6057578448787, ‘std’: 418.76075045523334},‘total_rooms’: {‘mean’: 2642.2929988158676, ‘std’: 2162.649970020439}}"
},
{
"code": null,
"e": 2770,
"s": 2665,
"text": "Now you can create the feature columns, using the training means and standard deviations computed above."
},
{
"code": null,
"e": 2969,
"s": 2770,
"text": "NUMERIC_FEATURES = [‘housing_median_age’, ‘total_rooms’, ‘total_bedrooms’, ‘population’, ‘households’, ‘median_income’]feature_columns = create_feature_cols(NUMERIC_FEATURES, use_normalization=True)"
},
{
"code": null,
"e": 3036,
"s": 2969,
"text": "And finally you can build the estimator using the feature columns:"
},
{
"code": null,
"e": 3213,
"s": 3036,
"text": "model = tf.estimator.DNNRegressor(hidden_units=[10,4], model_dir = outdir, feature_columns = feature_columns)"
},
{
"code": null,
"e": 3497,
"s": 3213,
"text": "Normalization is a hyperparameter, and in practice, it would be useful to evaluate different normalization schemes. For example you may want to try training a model just normalizing your features and comparing it to also normalizing inputs to hidden layers using batch normalization."
},
{
"code": null,
"e": 3824,
"s": 3497,
"text": "You can fire off multiple experiments in parallel using Cloud ML Engine. This will be particularly valuable for larger datasets, where you want to leverage the cloud to scale model training. To train with ML Engine, you need to package up the model code, creating task.py and model.py model files. See the repo for an example."
},
{
"code": null,
"e": 3936,
"s": 3824,
"text": "It’s best practice to test the model package locally first to ensure there are no syntactic or semantic errors:"
},
{
"code": null,
"e": 4075,
"s": 3936,
"text": "OUTPUT_DIR=’trained_model’export PYTHONPATH=${PYTHONPATH}:${PWD}/model_codepython -m trainer.task — outdir $OUTPUT_DIR — normalize_input 1"
},
{
"code": null,
"e": 4163,
"s": 4075,
"text": "After, you can submit a job to ML Engine using `gcloud ml-engine jobs submit training`:"
},
{
"code": null,
"e": 4595,
"s": 4163,
"text": "JOBNAME=my_ml_job_$(date -u +%y%m%d_%H%M%S)REGION=’us-central1'BUCKET=’gs://crawles-sandbox’OUTPUT_DIR=$BUCKET/’housing_trained_model’PACKAGE_PATH=$PWD/model_code/trainergcloud ml-engine jobs submit training $JOBNAME \\ -- package-path=$PACKAGE_PATH \\ -- module-name=trainer.task \\ -- region=$REGION \\ --staging-bucket=$BUCKET\\ -- scale-tier=BASIC \\ -- runtime-version=1.8 \\ -- \\ -- outdir=$OUTPUT_DIR\\ -- normalize_input=0"
},
{
"code": null,
"e": 4674,
"s": 4595,
"text": "In my case, I trained with and without computing the z-score for the features:"
},
{
"code": null,
"e": 4748,
"s": 4674,
"text": "As expected, normalizing the inputs improves the final model performance."
},
{
"code": null,
"e": 4836,
"s": 4748,
"text": "That’s it! If you found this post helpful, please give it a clap so others can find it."
},
{
"code": null,
"e": 4857,
"s": 4836,
"text": "Additional Resources"
},
{
"code": null,
"e": 4882,
"s": 4857,
"text": "Normalize using input_fn"
},
{
"code": null,
"e": 4917,
"s": 4882,
"text": "Batch Normalization using tf.keras"
},
{
"code": null,
"e": 4942,
"s": 4917,
"text": "Standard score (z-score)"
}
] |
PHP Interview Questions
|
Dear readers, these PHP Programming Language Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of PHP Programming Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
Common uses of PHP −
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user.
You add, delete, modify elements within your database thru PHP.
You add, delete, modify elements within your database thru PHP.
Access cookies variables and set cookies.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
It can encrypt data.
All PHP code must be included inside one of the three special markup tags ate are recognised by the PHP Parser.
<?php PHP code goes here ?>
<? PHP code goes here ?>
<script language="php"> PHP code goes here </script>
Most common tag is the <?php...?>
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's functionality. The php.ini file is read each time PHP is initialized.in other words, whenever httpd is restarted for the module version or with each script execution for the CGI version. If your change isn.t showing up, remember to stop and restart httpd. If it still isn.t showing up, use phpinfo() to check the path to php.ini.
The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as 'escaping to PHP.'
Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters). PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row.one whitespace character is the same as many such characters.
No, PHP is partially case sensitive.
Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Variables can, but do not need, to be declared before assignment.
Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters.
Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters.
Variables used before they are assigned have default values.
Variables used before they are assigned have default values.
PHP does a good job of automatically converting types from one to another when necessary.
PHP does a good job of automatically converting types from one to another when necessary.
PHP variables are Perl-like.
PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables −
Integers − are whole numbers, without a decimal point, like 4195.
Integers − are whole numbers, without a decimal point, like 4195.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like 'PHP supports string operations.'
Strings − are sequences of characters, like 'PHP supports string operations.'
Arrays − are named and indexed collections of other values.
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
Resources − are special variables that hold references to resources external to PHP (such as database connections).
Resources − are special variables that hold references to resources external to PHP (such as database connections).
Rules for naming a variable are following −
Variable names must begin with a letter or underscore character.
Variable names must begin with a letter or underscore character.
A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc
A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc
Here are the rules for determine the "truth" of any value not already of the Boolean type −
If the value is a number, it is false if exactly equal to zero and true otherwise.
If the value is a number, it is false if exactly equal to zero and true otherwise.
If the value is a string, it is false if the string is empty (has zero characters) or is the string "0", and is true otherwise.
If the value is a string, it is false if the string is empty (has zero characters) or is the string "0", and is true otherwise.
Values of type NULL are always false.
Values of type NULL are always false.
If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
Don't use double as Booleans.
Don't use double as Booleans.
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this −
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed −
$my_var = null;
A variable that has been assigned NULL has the following properties:
It evaluates to FALSE in a Boolean context.
It returns FALSE when tested with IsSet() function.
To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $.
As indicated by the name, this function will return the value of the constant. This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function.
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign.
There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign.
Constants cannot be defined by simple assignment, they may only be defined using the define() function.
Constants cannot be defined by simple assignment, they may only be defined using the define() function.
Constants may be defined and accessed anywhere without regard to variable scoping rules.
Constants may be defined and accessed anywhere without regard to variable scoping rules.
Once the Constants have been set, may not be redefined or undefined.
Once the Constants have been set, may not be redefined or undefined.
PHP provides a large number of predefined constants to any script which it runs known as magic constants.
_LINE_ − The current line number of the file.
_FILE_ − The full path and filename of the file. If used inside an include,the name of the included file is returned. Since PHP 4.0.2, _FILE_ always contains an absolute path whereas in older versions it contained relative path under some circumstances.
_FUNCTION_ − The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
_CLASS_ − The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
_METHOD_ − The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
break terminates the for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.
continue causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
foreach (array as value)
{
code to be executed;
}
Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.
To concatenate two string variables together, use the dot (.) operator −
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce following result −
Hello World 1234
The strlen() function is used to find the length of a string. Let's find the length of our string "Hello world!" −
<?php
echo strlen("Hello world!");
?>
This will produce following result −
12
The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.
Let's see if we can find the string "world" in our string −
<?php
echo strpos("Hello world!","world");
?>
This will produce following result −
6
PHP provides a function getenv() to access the value of all the environment variables.
One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system.
The PHP rand() function is used to generate a random number. This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifiies the seed number as its argument.
The PHP default variable $_PHP_SELF is used for the PHP script name and when you click "submit" button then same PHP script will be called.
The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading. The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.
The HTTP header will be different from the actual header where we send Content-Type as text/html\n\n. In this case content type will be application/octet-stream and actual file name will be concatenated alongwith it. For example,if you want make a FileName file downloadable from a given link then its syntax will be as follows.
#!/usr/bin/perl
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";
# Actual File Content
open( FILE, "<FileName" );
while(read(FILE, $buffer, 100) )
{
print("$buffer");
}
The PHP provides $_GET associative array to access all the sent information using GET method.
The PHP provides $_POST associative array to access all the sent information using POST method.
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
array() − Creates an array.
sort() − Sorts an array.
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce following result −
My $variable will not print!\n
My name will print
To concatenate two string variables together, use the dot (.) operator.
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce following result −
Hello World 1234
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
There are two PHP functions which can be used to included one PHP file into another PHP file.
The include() Function
The include() Function
The require() Function
The require() Function
If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script whereas include() function generates a warning but the script will continue execution.
The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate. "r" mode opens the file for reading only and places the file pointer at the beginning of the file.
Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.
File's existence can be confirmed using file_exist() function which takes file name as an argument.
Yes! You can set a parameter to have a default value if the function's caller doesn't pass it.
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables.
You can use isset() function to check if a cookie is set or not.
To delete a cookie you should call setcookie() with the name argument only.
A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
Make use of isset() function to check if session variable is already set or not.
Here is the example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
A PHP session can be destroyed by session_destroy() function.
PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
This is a global PHP variable. This variable is an associate double dimension array and keeps all the information related to uploaded file.
Using $_FILES['file']['tmp_name'] − it provides access to the uploaded file in the temporary directory on the web server.
Using $_FILES['file']['name'] − it provides the actual name of the uploaded file.
Using $_FILES['file']['size'] − it provides the size in bytes of the uploaded file.
Using $_FILES['file']['type'] − it provides the MIME type of the uploaded file.
Using $_FILES['file']['error'] − it provides the error code associated with this file upload.
$GLOBALS − Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables.
$_SERVER − This is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these. See next section for a complete list of all the SERVER variables.
$_COOKIE − An associative array of variables passed to the current script via HTTP cookies.
$_SESSION − An associative array containing session variables available to the current script.
$_PHP_SELF − A string containing PHP script file name in which it is called.
$php_errormsg − $php_errormsg is a variable containing the text of the last error message generated by PHP.
ereg() − The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.
eregi() − The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive.
The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.
preg_match() - The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
Using getMessage() method of Exception class which returns the message of exception.
Using getCode() method of Exception class which returns the code of exception.
Using getFile() method of Exception class which returns source filename.
Using getLine() method of Exception class which returns source line.
Using getTrace() method of Exception class which returns array of the backtrace.
Using getTraceAsString() method of Exception class which returns formated string of trace.
PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.
The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().
The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.
PHP provides mysql_connect function to open a database connection.
connection mysql_connect(server,user,passwd,new_link,client_flag);
PHP uses mysql_query function to create a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.
bool mysql_query( sql, connection );
Its simplest function mysql_close PHP provides to close a database connection. This function takes connection resource returned by mysql_connect function. It returns TRUE on success or FALSE on failure.
bool mysql_close ( resource $link_identifier );
If a resource is not specified then last opend database is closed.
PHP 5's new SimpleXML module makes parsing an XML document, well, simple. It turns an XML document into an object that provides structured access to the XML. To create a SimpleXML object from an XML document stored in a string, pass the string to simplexml_load_string( ). It returns a SimpleXML object.
Yes!
PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.
Like a constructor function you can define a destructor function using function __destruct(). You can release all the resourceses with-in a destructor.
The variable $this is a special variable and it refers to the same object ie. itself.
Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only. Following example shows how to set title and prices for the three books by calling member functions.
$physics−>setTitle( "Physics for High School" );
$chemistry−>setTitle( "Advanced Chemistry" );
$maths−>setTitle( "Algebra" );
$physics−>setPrice( 10 );
$chemistry−>setPrice( 15 );
$maths−>setPrice( 7 );
Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.
Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeltons which are implemented by developers.
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3230,
"s": 2757,
"text": "Dear readers, these PHP Programming Language Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of PHP Programming Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −"
},
{
"code": null,
"e": 3461,
"s": 3230,
"text": "PHP is a recursive acronym for \"PHP: Hypertext Preprocessor\". PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites."
},
{
"code": null,
"e": 3482,
"s": 3461,
"text": "Common uses of PHP −"
},
{
"code": null,
"e": 3591,
"s": 3482,
"text": "PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them."
},
{
"code": null,
"e": 3700,
"s": 3591,
"text": "PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them."
},
{
"code": null,
"e": 3827,
"s": 3700,
"text": "PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user."
},
{
"code": null,
"e": 3954,
"s": 3827,
"text": "PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user."
},
{
"code": null,
"e": 4018,
"s": 3954,
"text": "You add, delete, modify elements within your database thru PHP."
},
{
"code": null,
"e": 4082,
"s": 4018,
"text": "You add, delete, modify elements within your database thru PHP."
},
{
"code": null,
"e": 4124,
"s": 4082,
"text": "Access cookies variables and set cookies."
},
{
"code": null,
"e": 4166,
"s": 4124,
"text": "Access cookies variables and set cookies."
},
{
"code": null,
"e": 4238,
"s": 4166,
"text": "Using PHP, you can restrict users to access some pages of your website."
},
{
"code": null,
"e": 4310,
"s": 4238,
"text": "Using PHP, you can restrict users to access some pages of your website."
},
{
"code": null,
"e": 4331,
"s": 4310,
"text": "It can encrypt data."
},
{
"code": null,
"e": 4352,
"s": 4331,
"text": "It can encrypt data."
},
{
"code": null,
"e": 4464,
"s": 4352,
"text": "All PHP code must be included inside one of the three special markup tags ate are recognised by the PHP Parser."
},
{
"code": null,
"e": 4607,
"s": 4464,
"text": "<?php PHP code goes here ?>\n<? PHP code goes here ?>\n<script language=\"php\"> PHP code goes here </script>\nMost common tag is the <?php...?>"
},
{
"code": null,
"e": 5026,
"s": 4607,
"text": "The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's functionality. The php.ini file is read each time PHP is initialized.in other words, whenever httpd is restarted for the module version or with each script execution for the CGI version. If your change isn.t showing up, remember to stop and restart httpd. If it still isn.t showing up, use phpinfo() to check the path to php.ini."
},
{
"code": null,
"e": 5178,
"s": 5026,
"text": "The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as 'escaping to PHP.'"
},
{
"code": null,
"e": 5498,
"s": 5178,
"text": "Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters). PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row.one whitespace character is the same as many such characters."
},
{
"code": null,
"e": 5535,
"s": 5498,
"text": "No, PHP is partially case sensitive."
},
{
"code": null,
"e": 5602,
"s": 5535,
"text": "Here are the most important things to know about variables in PHP."
},
{
"code": null,
"e": 5667,
"s": 5602,
"text": "All variables in PHP are denoted with a leading dollar sign ($)."
},
{
"code": null,
"e": 5732,
"s": 5667,
"text": "All variables in PHP are denoted with a leading dollar sign ($)."
},
{
"code": null,
"e": 5800,
"s": 5732,
"text": "The value of a variable is the value of its most recent assignment."
},
{
"code": null,
"e": 5868,
"s": 5800,
"text": "The value of a variable is the value of its most recent assignment."
},
{
"code": null,
"e": 6001,
"s": 5868,
"text": "Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right."
},
{
"code": null,
"e": 6134,
"s": 6001,
"text": "Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right."
},
{
"code": null,
"e": 6201,
"s": 6134,
"text": "Variables can, but do not need, to be declared before assignment. "
},
{
"code": null,
"e": 6268,
"s": 6201,
"text": "Variables can, but do not need, to be declared before assignment. "
},
{
"code": null,
"e": 6420,
"s": 6268,
"text": "Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters."
},
{
"code": null,
"e": 6572,
"s": 6420,
"text": "Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters."
},
{
"code": null,
"e": 6633,
"s": 6572,
"text": "Variables used before they are assigned have default values."
},
{
"code": null,
"e": 6694,
"s": 6633,
"text": "Variables used before they are assigned have default values."
},
{
"code": null,
"e": 6784,
"s": 6694,
"text": "PHP does a good job of automatically converting types from one to another when necessary."
},
{
"code": null,
"e": 6874,
"s": 6784,
"text": "PHP does a good job of automatically converting types from one to another when necessary."
},
{
"code": null,
"e": 6903,
"s": 6874,
"text": "PHP variables are Perl-like."
},
{
"code": null,
"e": 6932,
"s": 6903,
"text": "PHP variables are Perl-like."
},
{
"code": null,
"e": 7010,
"s": 6932,
"text": "PHP has a total of eight data types which we use to construct our variables −"
},
{
"code": null,
"e": 7076,
"s": 7010,
"text": "Integers − are whole numbers, without a decimal point, like 4195."
},
{
"code": null,
"e": 7142,
"s": 7076,
"text": "Integers − are whole numbers, without a decimal point, like 4195."
},
{
"code": null,
"e": 7202,
"s": 7142,
"text": "Doubles − are floating-point numbers, like 3.14159 or 49.1."
},
{
"code": null,
"e": 7262,
"s": 7202,
"text": "Doubles − are floating-point numbers, like 3.14159 or 49.1."
},
{
"code": null,
"e": 7325,
"s": 7262,
"text": "Booleans − have only two possible values either true or false."
},
{
"code": null,
"e": 7388,
"s": 7325,
"text": "Booleans − have only two possible values either true or false."
},
{
"code": null,
"e": 7444,
"s": 7388,
"text": "NULL − is a special type that only has one value: NULL."
},
{
"code": null,
"e": 7500,
"s": 7444,
"text": "NULL − is a special type that only has one value: NULL."
},
{
"code": null,
"e": 7578,
"s": 7500,
"text": "Strings − are sequences of characters, like 'PHP supports string operations.'"
},
{
"code": null,
"e": 7656,
"s": 7578,
"text": "Strings − are sequences of characters, like 'PHP supports string operations.'"
},
{
"code": null,
"e": 7716,
"s": 7656,
"text": "Arrays − are named and indexed collections of other values."
},
{
"code": null,
"e": 7776,
"s": 7716,
"text": "Arrays − are named and indexed collections of other values."
},
{
"code": null,
"e": 7925,
"s": 7776,
"text": "Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class."
},
{
"code": null,
"e": 8074,
"s": 7925,
"text": "Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class."
},
{
"code": null,
"e": 8190,
"s": 8074,
"text": "Resources − are special variables that hold references to resources external to PHP (such as database connections)."
},
{
"code": null,
"e": 8306,
"s": 8190,
"text": "Resources − are special variables that hold references to resources external to PHP (such as database connections)."
},
{
"code": null,
"e": 8350,
"s": 8306,
"text": "Rules for naming a variable are following −"
},
{
"code": null,
"e": 8415,
"s": 8350,
"text": "Variable names must begin with a letter or underscore character."
},
{
"code": null,
"e": 8480,
"s": 8415,
"text": "Variable names must begin with a letter or underscore character."
},
{
"code": null,
"e": 8604,
"s": 8480,
"text": "A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc"
},
{
"code": null,
"e": 8728,
"s": 8604,
"text": "A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc"
},
{
"code": null,
"e": 8820,
"s": 8728,
"text": "Here are the rules for determine the \"truth\" of any value not already of the Boolean type −"
},
{
"code": null,
"e": 8903,
"s": 8820,
"text": "If the value is a number, it is false if exactly equal to zero and true otherwise."
},
{
"code": null,
"e": 8986,
"s": 8903,
"text": "If the value is a number, it is false if exactly equal to zero and true otherwise."
},
{
"code": null,
"e": 9114,
"s": 8986,
"text": "If the value is a string, it is false if the string is empty (has zero characters) or is the string \"0\", and is true otherwise."
},
{
"code": null,
"e": 9242,
"s": 9114,
"text": "If the value is a string, it is false if the string is empty (has zero characters) or is the string \"0\", and is true otherwise."
},
{
"code": null,
"e": 9280,
"s": 9242,
"text": "Values of type NULL are always false."
},
{
"code": null,
"e": 9318,
"s": 9280,
"text": "Values of type NULL are always false."
},
{
"code": null,
"e": 9511,
"s": 9318,
"text": "If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value."
},
{
"code": null,
"e": 9704,
"s": 9511,
"text": "If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value."
},
{
"code": null,
"e": 9839,
"s": 9704,
"text": "Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful)."
},
{
"code": null,
"e": 9974,
"s": 9839,
"text": "Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful)."
},
{
"code": null,
"e": 10004,
"s": 9974,
"text": "Don't use double as Booleans."
},
{
"code": null,
"e": 10034,
"s": 10004,
"text": "Don't use double as Booleans."
},
{
"code": null,
"e": 10152,
"s": 10034,
"text": "NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this −"
},
{
"code": null,
"e": 10168,
"s": 10152,
"text": "$my_var = NULL;"
},
{
"code": null,
"e": 10297,
"s": 10168,
"text": "The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed −"
},
{
"code": null,
"e": 10313,
"s": 10297,
"text": "$my_var = null;"
},
{
"code": null,
"e": 10382,
"s": 10313,
"text": "A variable that has been assigned NULL has the following properties:"
},
{
"code": null,
"e": 10426,
"s": 10382,
"text": "It evaluates to FALSE in a Boolean context."
},
{
"code": null,
"e": 10478,
"s": 10426,
"text": "It returns FALSE when tested with IsSet() function."
},
{
"code": null,
"e": 10682,
"s": 10478,
"text": "To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $."
},
{
"code": null,
"e": 10912,
"s": 10682,
"text": "As indicated by the name, this function will return the value of the constant. This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function."
},
{
"code": null,
"e": 11019,
"s": 10912,
"text": "<?php\ndefine(\"MINSIZE\", 50);\necho MINSIZE;\necho constant(\"MINSIZE\"); // same thing as the previous line\n?>"
},
{
"code": null,
"e": 11104,
"s": 11019,
"text": "Only scalar data (boolean, integer, float and string) can be contained in constants."
},
{
"code": null,
"e": 11220,
"s": 11104,
"text": "There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign."
},
{
"code": null,
"e": 11336,
"s": 11220,
"text": "There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign."
},
{
"code": null,
"e": 11440,
"s": 11336,
"text": "Constants cannot be defined by simple assignment, they may only be defined using the define() function."
},
{
"code": null,
"e": 11544,
"s": 11440,
"text": "Constants cannot be defined by simple assignment, they may only be defined using the define() function."
},
{
"code": null,
"e": 11633,
"s": 11544,
"text": "Constants may be defined and accessed anywhere without regard to variable scoping rules."
},
{
"code": null,
"e": 11722,
"s": 11633,
"text": "Constants may be defined and accessed anywhere without regard to variable scoping rules."
},
{
"code": null,
"e": 11791,
"s": 11722,
"text": "Once the Constants have been set, may not be redefined or undefined."
},
{
"code": null,
"e": 11860,
"s": 11791,
"text": "Once the Constants have been set, may not be redefined or undefined."
},
{
"code": null,
"e": 11966,
"s": 11860,
"text": "PHP provides a large number of predefined constants to any script which it runs known as magic constants."
},
{
"code": null,
"e": 12012,
"s": 11966,
"text": "_LINE_ − The current line number of the file."
},
{
"code": null,
"e": 12266,
"s": 12012,
"text": "_FILE_ − The full path and filename of the file. If used inside an include,the name of the included file is returned. Since PHP 4.0.2, _FILE_ always contains an absolute path whereas in older versions it contained relative path under some circumstances."
},
{
"code": null,
"e": 12449,
"s": 12266,
"text": "_FUNCTION_ − The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased."
},
{
"code": null,
"e": 12623,
"s": 12449,
"text": "_CLASS_ − The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased."
},
{
"code": null,
"e": 12743,
"s": 12623,
"text": "_METHOD_ − The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive)."
},
{
"code": null,
"e": 12880,
"s": 12743,
"text": "break terminates the for loop or switch statement and transfers execution to the statement immediately following the for loop or switch."
},
{
"code": null,
"e": 12998,
"s": 12880,
"text": "continue causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 13218,
"s": 12998,
"text": "The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed."
},
{
"code": null,
"e": 13272,
"s": 13218,
"text": "foreach (array as value)\n{\n code to be executed;\n}"
},
{
"code": null,
"e": 13369,
"s": 13272,
"text": "Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion."
},
{
"code": null,
"e": 13523,
"s": 13369,
"text": "Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order."
},
{
"code": null,
"e": 13635,
"s": 13523,
"text": "Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices."
},
{
"code": null,
"e": 13708,
"s": 13635,
"text": "To concatenate two string variables together, use the dot (.) operator −"
},
{
"code": null,
"e": 13790,
"s": 13708,
"text": "<?php\n$string1=\"Hello World\";\n$string2=\"1234\";\necho $string1 . \" \" . $string2;\n?>"
},
{
"code": null,
"e": 13827,
"s": 13790,
"text": "This will produce following result −"
},
{
"code": null,
"e": 13844,
"s": 13827,
"text": "Hello World 1234"
},
{
"code": null,
"e": 13959,
"s": 13844,
"text": "The strlen() function is used to find the length of a string. Let's find the length of our string \"Hello world!\" −"
},
{
"code": null,
"e": 13997,
"s": 13959,
"text": "<?php\necho strlen(\"Hello world!\");\n?>"
},
{
"code": null,
"e": 14034,
"s": 13997,
"text": "This will produce following result −"
},
{
"code": null,
"e": 14037,
"s": 14034,
"text": "12"
},
{
"code": null,
"e": 14318,
"s": 14037,
"text": "The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.\nLet's see if we can find the string \"world\" in our string −"
},
{
"code": null,
"e": 14364,
"s": 14318,
"text": "<?php\necho strpos(\"Hello world!\",\"world\");\n?>"
},
{
"code": null,
"e": 14401,
"s": 14364,
"text": "This will produce following result −"
},
{
"code": null,
"e": 14403,
"s": 14401,
"text": "6"
},
{
"code": null,
"e": 14491,
"s": 14403,
"text": "PHP provides a function getenv() to access the value of all the environment variables. "
},
{
"code": null,
"e": 14612,
"s": 14491,
"text": "One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system."
},
{
"code": null,
"e": 14926,
"s": 14612,
"text": "The PHP rand() function is used to generate a random number. This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifiies the seed number as its argument."
},
{
"code": null,
"e": 15066,
"s": 14926,
"text": "The PHP default variable $_PHP_SELF is used for the PHP script name and when you click \"submit\" button then same PHP script will be called."
},
{
"code": null,
"e": 15485,
"s": 15066,
"text": "The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading. The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code."
},
{
"code": null,
"e": 15814,
"s": 15485,
"text": "The HTTP header will be different from the actual header where we send Content-Type as text/html\\n\\n. In this case content type will be application/octet-stream and actual file name will be concatenated alongwith it. For example,if you want make a FileName file downloadable from a given link then its syntax will be as follows."
},
{
"code": null,
"e": 16091,
"s": 15814,
"text": "#!/usr/bin/perl\n# HTTP Header\nprint \"Content-Type:application/octet-stream; name=\\\"FileName\\\"\\r\\n\";\nprint \"Content-Disposition: attachment; filename=\\\"FileName\\\"\\r\\n\\n\";\n# Actual File Content\nopen( FILE, \"<FileName\" );\nwhile(read(FILE, $buffer, 100) )\n{\n print(\"$buffer\");\n}"
},
{
"code": null,
"e": 16185,
"s": 16091,
"text": "The PHP provides $_GET associative array to access all the sent information using GET method."
},
{
"code": null,
"e": 16281,
"s": 16185,
"text": "The PHP provides $_POST associative array to access all the sent information using POST method."
},
{
"code": null,
"e": 16550,
"s": 16281,
"text": "The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods."
},
{
"code": null,
"e": 16578,
"s": 16550,
"text": "array() − Creates an array."
},
{
"code": null,
"e": 16603,
"s": 16578,
"text": "sort() − Sorts an array."
},
{
"code": null,
"e": 16784,
"s": 16603,
"text": "Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences."
},
{
"code": null,
"e": 16959,
"s": 16784,
"text": "<?php\n$variable = \"name\";\n$literally = 'My $variable will not print!\\\\n';\nprint($literally);\nprint \"<br />\";\n$literally = \"My $variable will print!\\\\n\";\nprint($literally);\n?>"
},
{
"code": null,
"e": 16996,
"s": 16959,
"text": "This will produce following result −"
},
{
"code": null,
"e": 17046,
"s": 16996,
"text": "My $variable will not print!\\n\nMy name will print"
},
{
"code": null,
"e": 17118,
"s": 17046,
"text": "To concatenate two string variables together, use the dot (.) operator."
},
{
"code": null,
"e": 17200,
"s": 17118,
"text": "<?php\n$string1=\"Hello World\";\n$string2=\"1234\";\necho $string1 . \" \" . $string2;\n?>"
},
{
"code": null,
"e": 17237,
"s": 17200,
"text": "This will produce following result −"
},
{
"code": null,
"e": 17254,
"s": 17237,
"text": "Hello World 1234"
},
{
"code": null,
"e": 17523,
"s": 17254,
"text": "The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods."
},
{
"code": null,
"e": 17617,
"s": 17523,
"text": "There are two PHP functions which can be used to included one PHP file into another PHP file."
},
{
"code": null,
"e": 17640,
"s": 17617,
"text": "The include() Function"
},
{
"code": null,
"e": 17663,
"s": 17640,
"text": "The include() Function"
},
{
"code": null,
"e": 17686,
"s": 17663,
"text": "The require() Function"
},
{
"code": null,
"e": 17709,
"s": 17686,
"text": "The require() Function"
},
{
"code": null,
"e": 17928,
"s": 17709,
"text": "If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script whereas include() function generates a warning but the script will continue execution."
},
{
"code": null,
"e": 18165,
"s": 17928,
"text": "The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate. \"r\" mode opens the file for reading only and places the file pointer at the beginning of the file."
},
{
"code": null,
"e": 18373,
"s": 18165,
"text": "Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes."
},
{
"code": null,
"e": 18530,
"s": 18373,
"text": "The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes."
},
{
"code": null,
"e": 18630,
"s": 18530,
"text": "File's existence can be confirmed using file_exist() function which takes file name as an argument."
},
{
"code": null,
"e": 18725,
"s": 18630,
"text": "Yes! You can set a parameter to have a default value if the function's caller doesn't pass it."
},
{
"code": null,
"e": 18917,
"s": 18725,
"text": "PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately."
},
{
"code": null,
"e": 18973,
"s": 18917,
"text": "setcookie(name, value, expire, path, domain, security);"
},
{
"code": null,
"e": 19086,
"s": 18973,
"text": "PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables."
},
{
"code": null,
"e": 19151,
"s": 19086,
"text": "You can use isset() function to check if a cookie is set or not."
},
{
"code": null,
"e": 19227,
"s": 19151,
"text": "To delete a cookie you should call setcookie() with the name argument only."
},
{
"code": null,
"e": 19493,
"s": 19227,
"text": "A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page."
},
{
"code": null,
"e": 19625,
"s": 19493,
"text": "Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session."
},
{
"code": null,
"e": 19706,
"s": 19625,
"text": "Make use of isset() function to check if session variable is already set or not."
},
{
"code": null,
"e": 19755,
"s": 19706,
"text": "Here is the example to unset a single variable −"
},
{
"code": null,
"e": 19796,
"s": 19755,
"text": "<?php\n unset($_SESSION['counter']);\n?>"
},
{
"code": null,
"e": 19859,
"s": 19796,
"text": "A PHP session can be destroyed by session_destroy() function. "
},
{
"code": null,
"e": 20111,
"s": 19859,
"text": "PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters."
},
{
"code": null,
"e": 20162,
"s": 20111,
"text": "mail( to, subject, message, headers, parameters );"
},
{
"code": null,
"e": 20303,
"s": 20162,
"text": "This is a global PHP variable. This variable is an associate double dimension array and keeps all the information related to uploaded file. "
},
{
"code": null,
"e": 20425,
"s": 20303,
"text": "Using $_FILES['file']['tmp_name'] − it provides access to the uploaded file in the temporary directory on the web server."
},
{
"code": null,
"e": 20507,
"s": 20425,
"text": "Using $_FILES['file']['name'] − it provides the actual name of the uploaded file."
},
{
"code": null,
"e": 20591,
"s": 20507,
"text": "Using $_FILES['file']['size'] − it provides the size in bytes of the uploaded file."
},
{
"code": null,
"e": 20671,
"s": 20591,
"text": "Using $_FILES['file']['type'] − it provides the MIME type of the uploaded file."
},
{
"code": null,
"e": 20765,
"s": 20671,
"text": "Using $_FILES['file']['error'] − it provides the error code associated with this file upload."
},
{
"code": null,
"e": 20945,
"s": 20765,
"text": "$GLOBALS − Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables."
},
{
"code": null,
"e": 21236,
"s": 20945,
"text": "$_SERVER − This is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these. See next section for a complete list of all the SERVER variables."
},
{
"code": null,
"e": 21329,
"s": 21236,
"text": "$_COOKIE − An associative array of variables passed to the current script via HTTP cookies."
},
{
"code": null,
"e": 21424,
"s": 21329,
"text": "$_SESSION − An associative array containing session variables available to the current script."
},
{
"code": null,
"e": 21501,
"s": 21424,
"text": "$_PHP_SELF − A string containing PHP script file name in which it is called."
},
{
"code": null,
"e": 21609,
"s": 21501,
"text": "$php_errormsg − $php_errormsg is a variable containing the text of the last error message generated by PHP."
},
{
"code": null,
"e": 21772,
"s": 21609,
"text": "ereg() − The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise."
},
{
"code": null,
"e": 21921,
"s": 21772,
"text": "eregi() − The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive."
},
{
"code": null,
"e": 22063,
"s": 21921,
"text": "The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string."
},
{
"code": null,
"e": 22188,
"s": 22063,
"text": "preg_match() - The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise."
},
{
"code": null,
"e": 22323,
"s": 22188,
"text": "The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern."
},
{
"code": null,
"e": 22408,
"s": 22323,
"text": "Using getMessage() method of Exception class which returns the message of exception."
},
{
"code": null,
"e": 22487,
"s": 22408,
"text": "Using getCode() method of Exception class which returns the code of exception."
},
{
"code": null,
"e": 22560,
"s": 22487,
"text": "Using getFile() method of Exception class which returns source filename."
},
{
"code": null,
"e": 22629,
"s": 22560,
"text": "Using getLine() method of Exception class which returns source line."
},
{
"code": null,
"e": 22710,
"s": 22629,
"text": "Using getTrace() method of Exception class which returns array of the backtrace."
},
{
"code": null,
"e": 22801,
"s": 22710,
"text": "Using getTraceAsString() method of Exception class which returns formated string of trace."
},
{
"code": null,
"e": 22949,
"s": 22801,
"text": "PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer."
},
{
"code": null,
"e": 23164,
"s": 22949,
"text": "The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time()."
},
{
"code": null,
"e": 23364,
"s": 23164,
"text": "The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it."
},
{
"code": null,
"e": 23431,
"s": 23364,
"text": "PHP provides mysql_connect function to open a database connection."
},
{
"code": null,
"e": 23498,
"s": 23431,
"text": "connection mysql_connect(server,user,passwd,new_link,client_flag);"
},
{
"code": null,
"e": 23640,
"s": 23498,
"text": "PHP uses mysql_query function to create a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 23677,
"s": 23640,
"text": "bool mysql_query( sql, connection );"
},
{
"code": null,
"e": 23880,
"s": 23677,
"text": "Its simplest function mysql_close PHP provides to close a database connection. This function takes connection resource returned by mysql_connect function. It returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 23928,
"s": 23880,
"text": "bool mysql_close ( resource $link_identifier );"
},
{
"code": null,
"e": 23995,
"s": 23928,
"text": "If a resource is not specified then last opend database is closed."
},
{
"code": null,
"e": 24299,
"s": 23995,
"text": "PHP 5's new SimpleXML module makes parsing an XML document, well, simple. It turns an XML document into an object that provides structured access to the XML. To create a SimpleXML object from an XML document stored in a string, pass the string to simplexml_load_string( ). It returns a SimpleXML object."
},
{
"code": null,
"e": 24304,
"s": 24299,
"text": "Yes!"
},
{
"code": null,
"e": 24456,
"s": 24304,
"text": "PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function."
},
{
"code": null,
"e": 24608,
"s": 24456,
"text": "Like a constructor function you can define a destructor function using function __destruct(). You can release all the resourceses with-in a destructor."
},
{
"code": null,
"e": 24694,
"s": 24608,
"text": "The variable $this is a special variable and it refers to the same object ie. itself."
},
{
"code": null,
"e": 24859,
"s": 24694,
"text": "Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator."
},
{
"code": null,
"e": 24925,
"s": 24859,
"text": "$physics = new Books;\n$maths = new Books;\n$chemistry = new Books;"
},
{
"code": null,
"e": 25205,
"s": 24925,
"text": "After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only. Following example shows how to set title and prices for the three books by calling member functions."
},
{
"code": null,
"e": 25408,
"s": 25205,
"text": "$physics−>setTitle( \"Physics for High School\" );\n$chemistry−>setTitle( \"Advanced Chemistry\" );\n$maths−>setTitle( \"Algebra\" );\n$physics−>setPrice( 10 );\n$chemistry−>setPrice( 15 );\n$maths−>setPrice( 7 );"
},
{
"code": null,
"e": 25595,
"s": 25408,
"text": "Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class."
},
{
"code": null,
"e": 25835,
"s": 25595,
"text": "Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeltons which are implemented by developers."
},
{
"code": null,
"e": 26036,
"s": 25835,
"text": "PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended."
},
{
"code": null,
"e": 26323,
"s": 26036,
"text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong."
},
{
"code": null,
"e": 26653,
"s": 26323,
"text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)"
},
{
"code": null,
"e": 26686,
"s": 26653,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 26702,
"s": 26686,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 26735,
"s": 26702,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 26746,
"s": 26735,
"text": " Syed Raza"
},
{
"code": null,
"e": 26781,
"s": 26746,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 26798,
"s": 26781,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 26831,
"s": 26798,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 26846,
"s": 26831,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 26881,
"s": 26846,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 26893,
"s": 26881,
"text": " Azaz Patel"
},
{
"code": null,
"e": 26928,
"s": 26893,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 26956,
"s": 26928,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 26963,
"s": 26956,
"text": " Print"
},
{
"code": null,
"e": 26974,
"s": 26963,
"text": " Add Notes"
}
] |
How to create BMI Calculator Web App using Python and PyWebIO ? - GeeksforGeeks
|
30 Apr, 2021
In this article, we are going to create a BMI calculator using the PyWebIO module. This is a python module mostly used to create simple and interactive interfaces on the web using Python programming. It can be installed using the below command:
pip install pywebio
Before creating a calculator let’s take a brief understanding of BMI, The Body Mass Index (BMI) is the value obtained from dividing the weight of a person in Kg by its height square. The SI unit of BMI is kg/m2. Body Mass Index is directly proportional to the mass of an individual and inversely proportional to the square of the height of the individual.
Formula:
BMI = Mass of person / (height)2
where,
Mass in Kilograms(Kg), height in meters(m)
Now, we create a Calculator of BMI using Python and a very interesting library PyWebIO.
Import the required modules. For using the python library PyWebIO we have to import some important modules from this library:
Python
# importing modulesfrom pywebio.input import *from pywebio.output import *
As we can see in the above python program that we first import the required modules from the PyWebIO library. Then we create a class calculation in which we create BMIcalculator() method classifies a person based on the BMI passed as paramete
Python
# classify and compute BMIclass calculation: # defining method def BMIcalculator(self, Height, Mass): # compute BMI BMI = (Mass)/(Height*Height) # classify for t1, t2 in [(16, 'severely underweight'), (18.5, 'underweight'), (25, 'normal'), (30, 'overweight'), (35, 'moderately obese'), (float('inf'), 'severely obese')]: if BMI <= t1: put_text('Your BMI is', BMI, 'and the person is :', t2) break
After that from the user we take two inputs as for calculation we need height, mass, and then we calculate the result BMI by using the BMI formula and pass them as parameters in BMIcalculator() which computes BMI and classifies the weight category as per as result of BMI.
Python
# height inputHeight = input("Please enter height in meters(m)", type=FLOAT) # Mass inputMass = input("Please enter Mass/Weight in Kilograms(Kg)", type=FLOAT) obj = calculation()obj.BMIcalculator(Height, Mass)
Below is the complete program:
Python
# importing modulesfrom pywebio.input import *from pywebio.output import * # classify personclass calculation: # defining method def BMIcalculator(Height, Mass): for t1, t2 in [(16, 'severely underweight'), (18.5, 'underweight'), (25, 'normal'), (30, 'overweight'), (35, 'moderately obese'), (float('inf'), 'severely obese')]: if BMI <= t1: put_text('Your BMI is', BMI, 'and the person is :', t2) break # classify and compute BMIclass calculation: # defining method def BMIcalculator(self, Height, Mass): # compute BMI BMI = (Mass)/(Height*Height) # classify for t1, t2 in [(16, 'severely underweight'), (18.5, 'underweight'), (25, 'normal'), (30, 'overweight'), (35, 'moderately obese'), (float('inf'), 'severely obese')]: if BMI <= t1: put_text('Your BMI is', BMI, 'and the person is :', t2) break # height inputHeight = input("Please enter height in meters(m)", type=FLOAT) # Mass inputMass = input("Please enter Mass/Weight in Kilograms(Kg)", type=FLOAT) obj = calculation()obj.BMIcalculator(Height, Mass)
Output:
As in the output we take Height (1.7 m) and Mass (60 Kg) at the time of input, and we can see in the output the calculated BMI and their type.
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 24563,
"s": 24318,
"text": "In this article, we are going to create a BMI calculator using the PyWebIO module. This is a python module mostly used to create simple and interactive interfaces on the web using Python programming. It can be installed using the below command:"
},
{
"code": null,
"e": 24583,
"s": 24563,
"text": "pip install pywebio"
},
{
"code": null,
"e": 24939,
"s": 24583,
"text": "Before creating a calculator let’s take a brief understanding of BMI, The Body Mass Index (BMI) is the value obtained from dividing the weight of a person in Kg by its height square. The SI unit of BMI is kg/m2. Body Mass Index is directly proportional to the mass of an individual and inversely proportional to the square of the height of the individual."
},
{
"code": null,
"e": 24948,
"s": 24939,
"text": "Formula:"
},
{
"code": null,
"e": 25033,
"s": 24948,
"text": "BMI = Mass of person / (height)2 \nwhere,\nMass in Kilograms(Kg), height in meters(m)"
},
{
"code": null,
"e": 25121,
"s": 25033,
"text": "Now, we create a Calculator of BMI using Python and a very interesting library PyWebIO."
},
{
"code": null,
"e": 25247,
"s": 25121,
"text": "Import the required modules. For using the python library PyWebIO we have to import some important modules from this library:"
},
{
"code": null,
"e": 25254,
"s": 25247,
"text": "Python"
},
{
"code": "# importing modulesfrom pywebio.input import *from pywebio.output import *",
"e": 25329,
"s": 25254,
"text": null
},
{
"code": null,
"e": 25572,
"s": 25329,
"text": "As we can see in the above python program that we first import the required modules from the PyWebIO library. Then we create a class calculation in which we create BMIcalculator() method classifies a person based on the BMI passed as paramete"
},
{
"code": null,
"e": 25579,
"s": 25572,
"text": "Python"
},
{
"code": "# classify and compute BMIclass calculation: # defining method def BMIcalculator(self, Height, Mass): # compute BMI BMI = (Mass)/(Height*Height) # classify for t1, t2 in [(16, 'severely underweight'), (18.5, 'underweight'), (25, 'normal'), (30, 'overweight'), (35, 'moderately obese'), (float('inf'), 'severely obese')]: if BMI <= t1: put_text('Your BMI is', BMI, 'and the person is :', t2) break",
"e": 26177,
"s": 25579,
"text": null
},
{
"code": null,
"e": 26450,
"s": 26177,
"text": "After that from the user we take two inputs as for calculation we need height, mass, and then we calculate the result BMI by using the BMI formula and pass them as parameters in BMIcalculator() which computes BMI and classifies the weight category as per as result of BMI."
},
{
"code": null,
"e": 26457,
"s": 26450,
"text": "Python"
},
{
"code": "# height inputHeight = input(\"Please enter height in meters(m)\", type=FLOAT) # Mass inputMass = input(\"Please enter Mass/Weight in Kilograms(Kg)\", type=FLOAT) obj = calculation()obj.BMIcalculator(Height, Mass)",
"e": 26669,
"s": 26457,
"text": null
},
{
"code": null,
"e": 26700,
"s": 26669,
"text": "Below is the complete program:"
},
{
"code": null,
"e": 26707,
"s": 26700,
"text": "Python"
},
{
"code": "# importing modulesfrom pywebio.input import *from pywebio.output import * # classify personclass calculation: # defining method def BMIcalculator(Height, Mass): for t1, t2 in [(16, 'severely underweight'), (18.5, 'underweight'), (25, 'normal'), (30, 'overweight'), (35, 'moderately obese'), (float('inf'), 'severely obese')]: if BMI <= t1: put_text('Your BMI is', BMI, 'and the person is :', t2) break # classify and compute BMIclass calculation: # defining method def BMIcalculator(self, Height, Mass): # compute BMI BMI = (Mass)/(Height*Height) # classify for t1, t2 in [(16, 'severely underweight'), (18.5, 'underweight'), (25, 'normal'), (30, 'overweight'), (35, 'moderately obese'), (float('inf'), 'severely obese')]: if BMI <= t1: put_text('Your BMI is', BMI, 'and the person is :', t2) break # height inputHeight = input(\"Please enter height in meters(m)\", type=FLOAT) # Mass inputMass = input(\"Please enter Mass/Weight in Kilograms(Kg)\", type=FLOAT) obj = calculation()obj.BMIcalculator(Height, Mass)",
"e": 28063,
"s": 26707,
"text": null
},
{
"code": null,
"e": 28071,
"s": 28063,
"text": "Output:"
},
{
"code": null,
"e": 28214,
"s": 28071,
"text": "As in the output we take Height (1.7 m) and Mass (60 Kg) at the time of input, and we can see in the output the calculated BMI and their type."
},
{
"code": null,
"e": 28229,
"s": 28214,
"text": "python-modules"
},
{
"code": null,
"e": 28236,
"s": 28229,
"text": "Python"
},
{
"code": null,
"e": 28334,
"s": 28236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28366,
"s": 28334,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28422,
"s": 28366,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28464,
"s": 28422,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28519,
"s": 28464,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28561,
"s": 28519,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28583,
"s": 28561,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28622,
"s": 28583,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28653,
"s": 28622,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28682,
"s": 28653,
"text": "Create a directory in Python"
}
] |
Angular 6 - Animations
|
Animations add a lot of interaction between the html elements. Animation was also available with Angular2. The difference with Angular 6 is that animation is no more a part of the @angular/core library, but is a separate package that needs to be imported in app.module.ts.
To start with, we need to import the library as follows −
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
The BrowserAnimationsModule needs to be added to the import array in app.module.ts as shown below −
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In app.component.html, we have added the html elements, which are to be animated.
<div>
<button (click) = "animate()">Click Me</button>
<div [@myanimation] = "state" class = "rotate">
<img src = "assets/images/img.png" width = "100" height = "100">
</div>
</div>
For the main div, we have added a button and a div with an image. There is a click event for which the animate function is called. And for the div, the @myanimation directive is added and given the value as state.
Let us now see the app.component.ts where the animation is defined.
import { Component } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
styles:[`
div{
margin: 0 auto;
text-align: center;
width:200px;
}
.rotate{
width:100px;
height:100px;
border:solid 1px red;
}
`],
animations: [
trigger('myanimation',[
state('smaller',style({
transform : 'translateY(100px)'
})),
state('larger',style({
transform : 'translateY(0px)'
})),
transition('smaller <=> larger',animate('300ms ease-in'))
])
]
})
export class AppComponent {
state: string = "smaller";
animate() {
this.state= this.state == 'larger' ? 'smaller' : 'larger';
}
}
We have to import the animation function that is to be used in the .ts file as shown above.
import { trigger, state, style, transition, animate } from '@angular/animations';
Here we have imported trigger, state, style, transition, and animate from @angular/animations.
Now, we will add the animations property to the @Component () decorator −
animations: [
trigger('myanimation',[
state('smaller',style({
transform : 'translateY(100px)'
})),
state('larger',style({
transform : 'translateY(0px)'
})),
transition('smaller <=> larger',animate('300ms ease-in'))
])
]
Trigger defines the start of the animation. The first param to it is the name of the animation to be given to the html tag to which the animation needs to be applied. The second param are the functions we have imported - state, transition, etc.
The state function involves the animation steps, which the element will transition between. Right now we have defined two states, smaller and larger. For smaller state, we have given the style transform:translateY(100px) and transform:translateY(100px).
Transition function adds animation to the html element. The first argument takes the states, i.e., start and end; the second argument accepts the animate function. The animate function allows you to define the length, delay, and easing of a transition.
Let us now see the .html file to see how the transition function works
<div>
<button (click) = "animate()">Click Me</button>
<div [@myanimation] = "state" class="rotate">
<img src = "assets/images/img.png" width = "100" height = "100">
</div>
</div>
There is a style property added in the @component directive, which centrally aligns the div. Let us consider the following example to understand the same −
styles:[`
div{
margin: 0 auto;
text-align: center;
width:200px;
}
.rotate{
width:100px;
height:100px;
border:solid 1px red;
}
`],
Here, a special character [``] is used to add styles to the html element, if any. For the div, we have given the animation name defined in the app.component.ts file.
On the click of a button it calls the animate function, which is defined in the app.component.ts file as follows −
export class AppComponent {
state: string = "smaller";
animate() {
this.state= this.state == �larger�? 'smaller' : 'larger';
}
}
The state variable is defined and is given the default value as smaller. The animate function changes the state on click. If the state is larger, it will convert to smaller; and if smaller, it will convert to larger.
This is how the output in the browser (http://localhost:4200/) will look like −
Upon clicking the Click Me button, the position of the image is changed as shown in the following screenshot −
The transform function is applied in the y direction, which is changed from 0 to 100px when the Click Me button is clicked. The image is stored in the assets/images folder.
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": 2268,
"s": 1995,
"text": "Animations add a lot of interaction between the html elements. Animation was also available with Angular2. The difference with Angular 6 is that animation is no more a part of the @angular/core library, but is a separate package that needs to be imported in app.module.ts."
},
{
"code": null,
"e": 2326,
"s": 2268,
"text": "To start with, we need to import the library as follows −"
},
{
"code": null,
"e": 2407,
"s": 2326,
"text": "import { BrowserAnimationsModule } from '@angular/platform-browser/animations';\n"
},
{
"code": null,
"e": 2507,
"s": 2407,
"text": "The BrowserAnimationsModule needs to be added to the import array in app.module.ts as shown below −"
},
{
"code": null,
"e": 2940,
"s": 2507,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { AppComponent } from './app.component';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3022,
"s": 2940,
"text": "In app.component.html, we have added the html elements, which are to be animated."
},
{
"code": null,
"e": 3218,
"s": 3022,
"text": "<div>\n <button (click) = \"animate()\">Click Me</button>\n <div [@myanimation] = \"state\" class = \"rotate\">\n <img src = \"assets/images/img.png\" width = \"100\" height = \"100\">\n </div>\n</div>"
},
{
"code": null,
"e": 3432,
"s": 3218,
"text": "For the main div, we have added a button and a div with an image. There is a click event for which the animate function is called. And for the div, the @myanimation directive is added and given the value as state."
},
{
"code": null,
"e": 3500,
"s": 3432,
"text": "Let us now see the app.component.ts where the animation is defined."
},
{
"code": null,
"e": 4411,
"s": 3500,
"text": "import { Component } from '@angular/core';\nimport { trigger, state, style, transition, animate } from '@angular/animations';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css'],\n styles:[`\n div{\n margin: 0 auto;\n text-align: center;\n width:200px;\n }\n .rotate{\n width:100px;\n height:100px;\n border:solid 1px red;\n }\n `],\n animations: [\n trigger('myanimation',[\n state('smaller',style({\n transform : 'translateY(100px)'\n })),\n state('larger',style({\n transform : 'translateY(0px)'\n })),\n transition('smaller <=> larger',animate('300ms ease-in'))\n ])\n ]\n})\nexport class AppComponent {\n state: string = \"smaller\";\n animate() {\n this.state= this.state == 'larger' ? 'smaller' : 'larger';\n }\n}"
},
{
"code": null,
"e": 4503,
"s": 4411,
"text": "We have to import the animation function that is to be used in the .ts file as shown above."
},
{
"code": null,
"e": 4586,
"s": 4503,
"text": "import { trigger, state, style, transition, animate } from '@angular/animations';\n"
},
{
"code": null,
"e": 4681,
"s": 4586,
"text": "Here we have imported trigger, state, style, transition, and animate from @angular/animations."
},
{
"code": null,
"e": 4755,
"s": 4681,
"text": "Now, we will add the animations property to the @Component () decorator −"
},
{
"code": null,
"e": 5029,
"s": 4755,
"text": "animations: [\n trigger('myanimation',[\n state('smaller',style({\n transform : 'translateY(100px)'\n })),\n state('larger',style({\n transform : 'translateY(0px)'\n })),\n transition('smaller <=> larger',animate('300ms ease-in'))\n ])\n]"
},
{
"code": null,
"e": 5274,
"s": 5029,
"text": "Trigger defines the start of the animation. The first param to it is the name of the animation to be given to the html tag to which the animation needs to be applied. The second param are the functions we have imported - state, transition, etc."
},
{
"code": null,
"e": 5528,
"s": 5274,
"text": "The state function involves the animation steps, which the element will transition between. Right now we have defined two states, smaller and larger. For smaller state, we have given the style transform:translateY(100px) and transform:translateY(100px)."
},
{
"code": null,
"e": 5781,
"s": 5528,
"text": "Transition function adds animation to the html element. The first argument takes the states, i.e., start and end; the second argument accepts the animate function. The animate function allows you to define the length, delay, and easing of a transition."
},
{
"code": null,
"e": 5852,
"s": 5781,
"text": "Let us now see the .html file to see how the transition function works"
},
{
"code": null,
"e": 6046,
"s": 5852,
"text": "<div>\n <button (click) = \"animate()\">Click Me</button>\n <div [@myanimation] = \"state\" class=\"rotate\">\n <img src = \"assets/images/img.png\" width = \"100\" height = \"100\">\n </div>\n</div>"
},
{
"code": null,
"e": 6202,
"s": 6046,
"text": "There is a style property added in the @component directive, which centrally aligns the div. Let us consider the following example to understand the same −"
},
{
"code": null,
"e": 6380,
"s": 6202,
"text": "styles:[`\n div{\n margin: 0 auto;\n text-align: center;\n width:200px;\n }\n .rotate{\n width:100px;\n height:100px;\n border:solid 1px red;\n }\n`],"
},
{
"code": null,
"e": 6546,
"s": 6380,
"text": "Here, a special character [``] is used to add styles to the html element, if any. For the div, we have given the animation name defined in the app.component.ts file."
},
{
"code": null,
"e": 6661,
"s": 6546,
"text": "On the click of a button it calls the animate function, which is defined in the app.component.ts file as follows −"
},
{
"code": null,
"e": 6805,
"s": 6661,
"text": "export class AppComponent {\n state: string = \"smaller\";\n animate() {\n this.state= this.state == �larger�? 'smaller' : 'larger';\n }\n}"
},
{
"code": null,
"e": 7022,
"s": 6805,
"text": "The state variable is defined and is given the default value as smaller. The animate function changes the state on click. If the state is larger, it will convert to smaller; and if smaller, it will convert to larger."
},
{
"code": null,
"e": 7102,
"s": 7022,
"text": "This is how the output in the browser (http://localhost:4200/) will look like −"
},
{
"code": null,
"e": 7213,
"s": 7102,
"text": "Upon clicking the Click Me button, the position of the image is changed as shown in the following screenshot −"
},
{
"code": null,
"e": 7386,
"s": 7213,
"text": "The transform function is applied in the y direction, which is changed from 0 to 100px when the Click Me button is clicked. The image is stored in the assets/images folder."
},
{
"code": null,
"e": 7421,
"s": 7386,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7435,
"s": 7421,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7470,
"s": 7435,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7484,
"s": 7470,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7519,
"s": 7484,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7539,
"s": 7519,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7574,
"s": 7539,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7591,
"s": 7574,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7624,
"s": 7591,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7636,
"s": 7624,
"text": " Senol Atac"
},
{
"code": null,
"e": 7671,
"s": 7636,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7683,
"s": 7671,
"text": " Senol Atac"
},
{
"code": null,
"e": 7690,
"s": 7683,
"text": " Print"
},
{
"code": null,
"e": 7701,
"s": 7690,
"text": " Add Notes"
}
] |
AtomicReference getAndUpdate() method in Java with Examples - GeeksforGeeks
|
15 Apr, 2021
The getAndUpdate() method of a AtomicReference class is used to atomically updates which updates the current value of the AtomicReference by applying the specified updateFunction operation on the current value. It takes an object of updateFunction interface as its parameter and applies the operation specified in the object to the current value. It returns the previous value.Syntax:
public final V getAndUpdate(UnaryOperator<V> updateFunction)
Parameters: This method accepts updateFunction which is a side-effect-free function.Return value: This method returns the previous value.Below programs illustrate the getAndUpdate() method: Program 1:
Java
// Java program to demonstrate// AtomicReference.getAndUpdate() method import java.util.concurrent.atomic.AtomicReference;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { // AtomicReference with value AtomicReference<Integer> ref = new AtomicReference<>(987654); // Declaring the updateFunction // applying function UnaryOperator twoDigits = (v) -> v.toString() .substring(0, 2); // apply getAndUpdate() int value = ref.getAndUpdate(twoDigits); // print AtomicReference System.out.println( "The AtomicReference previous value: " + value); System.out.println( "The AtomicReference new value: " + ref.get()); }}
Program 2:
Java
// Java program to demonstrate// AtomicReference.getAndUpdate() method import java.util.concurrent.atomic.*;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { // AtomicReference with value AtomicReference<String> ref = new AtomicReference<>("welcome"); // Declaring the updateFunction // applying function UnaryOperator twoDigits = (v) -> v + " to gfg"; // apply getAndUpdate() String value = ref.getAndUpdate(twoDigits); // print AtomicReference System.out.println( "The AtomicReference previous value: " + value); System.out.println( "The AtomicReference new value: " + ref.get()); }}
References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#getAndUpdate(java.util.function.UnaryOperator)
arorakashish0911
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n15 Apr, 2021"
},
{
"code": null,
"e": 24335,
"s": 23948,
"text": "The getAndUpdate() method of a AtomicReference class is used to atomically updates which updates the current value of the AtomicReference by applying the specified updateFunction operation on the current value. It takes an object of updateFunction interface as its parameter and applies the operation specified in the object to the current value. It returns the previous value.Syntax: "
},
{
"code": null,
"e": 24396,
"s": 24335,
"text": "public final V getAndUpdate(UnaryOperator<V> updateFunction)"
},
{
"code": null,
"e": 24599,
"s": 24396,
"text": "Parameters: This method accepts updateFunction which is a side-effect-free function.Return value: This method returns the previous value.Below programs illustrate the getAndUpdate() method: Program 1: "
},
{
"code": null,
"e": 24604,
"s": 24599,
"text": "Java"
},
{
"code": "// Java program to demonstrate// AtomicReference.getAndUpdate() method import java.util.concurrent.atomic.AtomicReference;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { // AtomicReference with value AtomicReference<Integer> ref = new AtomicReference<>(987654); // Declaring the updateFunction // applying function UnaryOperator twoDigits = (v) -> v.toString() .substring(0, 2); // apply getAndUpdate() int value = ref.getAndUpdate(twoDigits); // print AtomicReference System.out.println( \"The AtomicReference previous value: \" + value); System.out.println( \"The AtomicReference new value: \" + ref.get()); }}",
"e": 25444,
"s": 24604,
"text": null
},
{
"code": null,
"e": 25459,
"s": 25446,
"text": "Program 2: "
},
{
"code": null,
"e": 25464,
"s": 25459,
"text": "Java"
},
{
"code": "// Java program to demonstrate// AtomicReference.getAndUpdate() method import java.util.concurrent.atomic.*;import java.util.function.UnaryOperator; public class GFG { public static void main(String args[]) { // AtomicReference with value AtomicReference<String> ref = new AtomicReference<>(\"welcome\"); // Declaring the updateFunction // applying function UnaryOperator twoDigits = (v) -> v + \" to gfg\"; // apply getAndUpdate() String value = ref.getAndUpdate(twoDigits); // print AtomicReference System.out.println( \"The AtomicReference previous value: \" + value); System.out.println( \"The AtomicReference new value: \" + ref.get()); }}",
"e": 26261,
"s": 25464,
"text": null
},
{
"code": null,
"e": 26415,
"s": 26263,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#getAndUpdate(java.util.function.UnaryOperator) "
},
{
"code": null,
"e": 26432,
"s": 26415,
"text": "arorakashish0911"
},
{
"code": null,
"e": 26447,
"s": 26432,
"text": "Java-Functions"
},
{
"code": null,
"e": 26452,
"s": 26447,
"text": "Java"
},
{
"code": null,
"e": 26457,
"s": 26452,
"text": "Java"
},
{
"code": null,
"e": 26555,
"s": 26457,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26570,
"s": 26555,
"text": "Stream In Java"
},
{
"code": null,
"e": 26616,
"s": 26570,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26637,
"s": 26616,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26656,
"s": 26637,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26686,
"s": 26656,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26703,
"s": 26686,
"text": "Generics in Java"
},
{
"code": null,
"e": 26746,
"s": 26703,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26775,
"s": 26746,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26796,
"s": 26775,
"text": "Introduction to Java"
}
] |
Represent Int32 as a Binary String in C#
|
To represent Int632as a Binary string in C#, use the ToString() method and set the base as the ToString() method’s second parameter i.e. 2 for Binary.
Int32 represents a 32-bit signed integer.
Firstly, set an Int64 variable −
int val = 30;
Now, convert it to a binary string by including 2 as the second parameter.
Convert.ToString(val, 2)
Live Demo
using System;
class Demo {
static void Main() {
int val = 30;
Console.WriteLine("Integer: "+val);
Console.Write("Binary String: "+Convert.ToString(val, 2));
}
}
Integer: 30
Binary String: 11110
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "To represent Int632as a Binary string in C#, use the ToString() method and set the base as the ToString() method’s second parameter i.e. 2 for Binary."
},
{
"code": null,
"e": 1255,
"s": 1213,
"text": "Int32 represents a 32-bit signed integer."
},
{
"code": null,
"e": 1288,
"s": 1255,
"text": "Firstly, set an Int64 variable −"
},
{
"code": null,
"e": 1302,
"s": 1288,
"text": "int val = 30;"
},
{
"code": null,
"e": 1377,
"s": 1302,
"text": "Now, convert it to a binary string by including 2 as the second parameter."
},
{
"code": null,
"e": 1402,
"s": 1377,
"text": "Convert.ToString(val, 2)"
},
{
"code": null,
"e": 1413,
"s": 1402,
"text": " Live Demo"
},
{
"code": null,
"e": 1598,
"s": 1413,
"text": "using System;\nclass Demo {\n static void Main() {\n int val = 30;\n Console.WriteLine(\"Integer: \"+val);\n Console.Write(\"Binary String: \"+Convert.ToString(val, 2));\n }\n}"
},
{
"code": null,
"e": 1631,
"s": 1598,
"text": "Integer: 30\nBinary String: 11110"
}
] |
Comprehensive Churn Prediction and Analysis | by Mandy Gu | Towards Data Science
|
Customer churn, also known as attrition, occurs when a customer stops doing business with a company. Understanding and detecting churn is the first step to retaining these customers and improving the company’s offerings.
We will be training our churn model over the Telco-Customer-Churn Dataset to predict the likelihood of customers leaving the fictional telecommunications company, Telco. This synthetic dataset was put together by IBM and includes a label indicating whether or not the customer left within the last month.
Goal: predict whether a customer will churn based on their demographic and service information.
The exploration and modelling will be conducted using a Jupyter notebook. We begin by loading the required libraries and importing the data as a DataFrame.
Indexing the first row shows us the columns and a sample record from our dataset.
This dataset is fairly clean with no missing entries. There is a total of 7043 observations. Around 27% of the customers churned (not a good sign for Telco).
We can use the info(), describe() methods from pandas for a quick overview of data integrity. The dataset does not have any missing values. Although pandas interpreted SeniorCitizen as a continuous variable, it is actually a binary indicator.
We can use the seaborn library to further visualize and inspect the dataset. Let’s examine the continuous variables tenure, MonthlyCharges first. Since TotalCharges can be approximatedas a function of these two variables, we will exclude it from the plot.
Seaborn’s pairplot functionality plots pairwise relationships in the data.
Interpreting the Pair plot:
the diagonal axis is the histogram for the particular variable with the y-axis measuring the number of occurrences
the bottom left triangle of the plots and the top right triangle capture the same information, except the axis are flipped
The histograms tell us that the tenure distribution of churned clients is right skewed while the same distribution for churned clients is more uniform. It also shows that clients with higher MonthlyCharges see a higher rate of churn.
The other two charts capture very similar information with a distinctive divide between the orange churn and blue unchurned.
Next, we use boxplots to illustrate the quantile differences between customers who churned and who did not churn.
The first box plot compares the tenure quantiles between the two groups. The median tenure for churned customers is a lot shorter than unchurned customers. 75% of customers who end up leaving Telco do so within their first 30 months. There are a few outliers that churned after being with Telco for 70 months.
The second box plot compares MonthlyCharges against churn. The median MonthlyCharges of churned customers is significantly higher than those who did not churn. This suggests that discounts and promotions can be an enticing reason for customers to stay.
Next, we can examine the categorical variables, starting with the demographic variables: gender, SeniorCitizen, Partner and Dependents.
The top left graph counts the intersection between gender and churn. There is very little difference in churn proportionsbetween male and female customers.
There is a higher proportionof churn amongst SeniorCitizen(top right chart), customers with no Partners(bottom left chart) and customers with no dependents(bottom right chart).
The second finding might be of interest to business stakeholders. Non-senior citizens with no partners and dependents describe a particular intersection of customers. In lieu of other indicators, less frequent churn in this demographic speaks positively towards their lifetime value.
The other categorical variables can be divided between service and billing information.
These charts capture the service variables. There is a higher proportion of churn in customers without OnlineSecurity, OnlineBackup, DeviceProtection, and TechSupport. Based on my fairly limited knowledge about telecommunication services, I don’t think most people are frequently paying for these services. It suggests that those with increased reliabilityon Telco’s services, or those who need their device for particular uses, tend to churn less.
Next, we examine the intersection between billing method and churn. The top left chart compares churn across contract type. To no surprise, those with shorter plans (month to month) see a higher rate of churn. Those with longer plans face additional barriers when cancelling prematurely.
Surprisingly, those who opt out of PaperlessBilling are more frequently to churn as well as those who pay by electronic check. Some of these behaviors may be confounded with other variables (for instance, older customers might have a preference towards paper bills).
Here are the libraries that we are going to use to build our model. I am using a new notebook, so I will load the data in again.
In the TotalCharges column, 11 records are an empty string. All of these records have a valid MonthlyCharges value, but a tenure of 0. We can impute these values using 0.
First, we one hot encode categorical variables and randomly partition the data between training and testing. After partitioning the dataset, we do not touch the test set except for evaluation purposes.
The prior exploration already gave a lot of information regarding which features are important. We can use that in conjunction with a Chi-squared test to make a more informed decision.
Note: the Chi-squared test can only be used to assess categorical variables.
We will need to understand p-values to interpret the Chi-squared output.
The P-value indicates the % of more “extreme” observations if the null hypothesis is true and if we repeat the same experiment many times. The null hypothesis here is that the feature has no effect on the target (i.e. we should not use it as a predictor). Low p-values suggest we should reject our null hypothesis — in other words, reject the claim that the feature has no effect.
The p-values for most of the features are very low. Only gender, MultipleLines, PhoneServicehave p-values > 0.05, which means that we do not have enough evidence to reject the claim that these features have no effect. This is well aligned with the story from the charts.
For a better visual, let’s plot all categorical variables with p-value > 0.05.
We will also drop the TotalChargessince the same information is captured by MonthlyCharges, Tenure to further reduce the dimensionality (the other two columns appear to be more reliable than this one, which had data issues).
We will use a Logistic Regression model to predict churn. This might not necessarily be the most performant algorithm or the algorithm which best separates the data (the only way to find out is to try), but let’s assume it is good enough for simplification. One additional advantage of Logistic Regression is the ease of interpretation.
We can leverage the GridSearchCV function from Sklearn for hyperparameter tuning. . Since we do not want to touch our test set until the very end, we will further partition our training set into training and validation.
We will use grid search to determine the optimal values for these hyperparameters: — whether we should use a L1 or L2 penalty — the C value — whether we should fit an intercept — class weight (whether we should put more emphasis on the Churn class as opposed to the non-Churn class).
Under the hood, GridSearchCV will be training and evaluating numerous models against the validation set to determine which hyperparameters yield the best performance.
Note: while I have not done so here, GridSearchCV can be used to test candidate algorithms.
We can find the best hyperparameter values using grid.best_params_ , which in this case is:
{'C': 1, 'fit_intercept': False, 'penalty': 'l1'}
With this information, we can formally train our model. We will be training the model on the training and validation set combined.
Let’s test the model against our test set. The classification report gives the precision, recall and f1-score (the support is the number of observations in each class). The micro f1-score is 0.81 while the macro f1-score is 0.74.
We can visualize this result using a confusion matrix.
Not bad for an initial model. This synthetic dataset was very simple: real world telecommunication companies will likely have more than 7000 data points. Other variables, such as customer interactions with support staff, could have been helpful in predicting churn.
However, this dataset was incredibly clean and came with a nice churn indicator that we often don’t find in the real world.
If you enjoyed this article, check out my other articles on Data Science, Math and Programming. Follow me on Medium for the latest updates. 😃
I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project.
If you want to support my writing, consider using my affiliate link the next time you sign up for a Coursera course. Full disclosure — I receive commission for every enrollment, but it comes at no extra cost for you.
Thank you again for reading! 📕
|
[
{
"code": null,
"e": 392,
"s": 171,
"text": "Customer churn, also known as attrition, occurs when a customer stops doing business with a company. Understanding and detecting churn is the first step to retaining these customers and improving the company’s offerings."
},
{
"code": null,
"e": 697,
"s": 392,
"text": "We will be training our churn model over the Telco-Customer-Churn Dataset to predict the likelihood of customers leaving the fictional telecommunications company, Telco. This synthetic dataset was put together by IBM and includes a label indicating whether or not the customer left within the last month."
},
{
"code": null,
"e": 793,
"s": 697,
"text": "Goal: predict whether a customer will churn based on their demographic and service information."
},
{
"code": null,
"e": 949,
"s": 793,
"text": "The exploration and modelling will be conducted using a Jupyter notebook. We begin by loading the required libraries and importing the data as a DataFrame."
},
{
"code": null,
"e": 1031,
"s": 949,
"text": "Indexing the first row shows us the columns and a sample record from our dataset."
},
{
"code": null,
"e": 1189,
"s": 1031,
"text": "This dataset is fairly clean with no missing entries. There is a total of 7043 observations. Around 27% of the customers churned (not a good sign for Telco)."
},
{
"code": null,
"e": 1432,
"s": 1189,
"text": "We can use the info(), describe() methods from pandas for a quick overview of data integrity. The dataset does not have any missing values. Although pandas interpreted SeniorCitizen as a continuous variable, it is actually a binary indicator."
},
{
"code": null,
"e": 1688,
"s": 1432,
"text": "We can use the seaborn library to further visualize and inspect the dataset. Let’s examine the continuous variables tenure, MonthlyCharges first. Since TotalCharges can be approximatedas a function of these two variables, we will exclude it from the plot."
},
{
"code": null,
"e": 1763,
"s": 1688,
"text": "Seaborn’s pairplot functionality plots pairwise relationships in the data."
},
{
"code": null,
"e": 1791,
"s": 1763,
"text": "Interpreting the Pair plot:"
},
{
"code": null,
"e": 1906,
"s": 1791,
"text": "the diagonal axis is the histogram for the particular variable with the y-axis measuring the number of occurrences"
},
{
"code": null,
"e": 2029,
"s": 1906,
"text": "the bottom left triangle of the plots and the top right triangle capture the same information, except the axis are flipped"
},
{
"code": null,
"e": 2263,
"s": 2029,
"text": "The histograms tell us that the tenure distribution of churned clients is right skewed while the same distribution for churned clients is more uniform. It also shows that clients with higher MonthlyCharges see a higher rate of churn."
},
{
"code": null,
"e": 2388,
"s": 2263,
"text": "The other two charts capture very similar information with a distinctive divide between the orange churn and blue unchurned."
},
{
"code": null,
"e": 2502,
"s": 2388,
"text": "Next, we use boxplots to illustrate the quantile differences between customers who churned and who did not churn."
},
{
"code": null,
"e": 2812,
"s": 2502,
"text": "The first box plot compares the tenure quantiles between the two groups. The median tenure for churned customers is a lot shorter than unchurned customers. 75% of customers who end up leaving Telco do so within their first 30 months. There are a few outliers that churned after being with Telco for 70 months."
},
{
"code": null,
"e": 3065,
"s": 2812,
"text": "The second box plot compares MonthlyCharges against churn. The median MonthlyCharges of churned customers is significantly higher than those who did not churn. This suggests that discounts and promotions can be an enticing reason for customers to stay."
},
{
"code": null,
"e": 3201,
"s": 3065,
"text": "Next, we can examine the categorical variables, starting with the demographic variables: gender, SeniorCitizen, Partner and Dependents."
},
{
"code": null,
"e": 3357,
"s": 3201,
"text": "The top left graph counts the intersection between gender and churn. There is very little difference in churn proportionsbetween male and female customers."
},
{
"code": null,
"e": 3534,
"s": 3357,
"text": "There is a higher proportionof churn amongst SeniorCitizen(top right chart), customers with no Partners(bottom left chart) and customers with no dependents(bottom right chart)."
},
{
"code": null,
"e": 3818,
"s": 3534,
"text": "The second finding might be of interest to business stakeholders. Non-senior citizens with no partners and dependents describe a particular intersection of customers. In lieu of other indicators, less frequent churn in this demographic speaks positively towards their lifetime value."
},
{
"code": null,
"e": 3906,
"s": 3818,
"text": "The other categorical variables can be divided between service and billing information."
},
{
"code": null,
"e": 4355,
"s": 3906,
"text": "These charts capture the service variables. There is a higher proportion of churn in customers without OnlineSecurity, OnlineBackup, DeviceProtection, and TechSupport. Based on my fairly limited knowledge about telecommunication services, I don’t think most people are frequently paying for these services. It suggests that those with increased reliabilityon Telco’s services, or those who need their device for particular uses, tend to churn less."
},
{
"code": null,
"e": 4643,
"s": 4355,
"text": "Next, we examine the intersection between billing method and churn. The top left chart compares churn across contract type. To no surprise, those with shorter plans (month to month) see a higher rate of churn. Those with longer plans face additional barriers when cancelling prematurely."
},
{
"code": null,
"e": 4910,
"s": 4643,
"text": "Surprisingly, those who opt out of PaperlessBilling are more frequently to churn as well as those who pay by electronic check. Some of these behaviors may be confounded with other variables (for instance, older customers might have a preference towards paper bills)."
},
{
"code": null,
"e": 5039,
"s": 4910,
"text": "Here are the libraries that we are going to use to build our model. I am using a new notebook, so I will load the data in again."
},
{
"code": null,
"e": 5210,
"s": 5039,
"text": "In the TotalCharges column, 11 records are an empty string. All of these records have a valid MonthlyCharges value, but a tenure of 0. We can impute these values using 0."
},
{
"code": null,
"e": 5412,
"s": 5210,
"text": "First, we one hot encode categorical variables and randomly partition the data between training and testing. After partitioning the dataset, we do not touch the test set except for evaluation purposes."
},
{
"code": null,
"e": 5597,
"s": 5412,
"text": "The prior exploration already gave a lot of information regarding which features are important. We can use that in conjunction with a Chi-squared test to make a more informed decision."
},
{
"code": null,
"e": 5674,
"s": 5597,
"text": "Note: the Chi-squared test can only be used to assess categorical variables."
},
{
"code": null,
"e": 5747,
"s": 5674,
"text": "We will need to understand p-values to interpret the Chi-squared output."
},
{
"code": null,
"e": 6128,
"s": 5747,
"text": "The P-value indicates the % of more “extreme” observations if the null hypothesis is true and if we repeat the same experiment many times. The null hypothesis here is that the feature has no effect on the target (i.e. we should not use it as a predictor). Low p-values suggest we should reject our null hypothesis — in other words, reject the claim that the feature has no effect."
},
{
"code": null,
"e": 6399,
"s": 6128,
"text": "The p-values for most of the features are very low. Only gender, MultipleLines, PhoneServicehave p-values > 0.05, which means that we do not have enough evidence to reject the claim that these features have no effect. This is well aligned with the story from the charts."
},
{
"code": null,
"e": 6478,
"s": 6399,
"text": "For a better visual, let’s plot all categorical variables with p-value > 0.05."
},
{
"code": null,
"e": 6703,
"s": 6478,
"text": "We will also drop the TotalChargessince the same information is captured by MonthlyCharges, Tenure to further reduce the dimensionality (the other two columns appear to be more reliable than this one, which had data issues)."
},
{
"code": null,
"e": 7040,
"s": 6703,
"text": "We will use a Logistic Regression model to predict churn. This might not necessarily be the most performant algorithm or the algorithm which best separates the data (the only way to find out is to try), but let’s assume it is good enough for simplification. One additional advantage of Logistic Regression is the ease of interpretation."
},
{
"code": null,
"e": 7260,
"s": 7040,
"text": "We can leverage the GridSearchCV function from Sklearn for hyperparameter tuning. . Since we do not want to touch our test set until the very end, we will further partition our training set into training and validation."
},
{
"code": null,
"e": 7544,
"s": 7260,
"text": "We will use grid search to determine the optimal values for these hyperparameters: — whether we should use a L1 or L2 penalty — the C value — whether we should fit an intercept — class weight (whether we should put more emphasis on the Churn class as opposed to the non-Churn class)."
},
{
"code": null,
"e": 7711,
"s": 7544,
"text": "Under the hood, GridSearchCV will be training and evaluating numerous models against the validation set to determine which hyperparameters yield the best performance."
},
{
"code": null,
"e": 7803,
"s": 7711,
"text": "Note: while I have not done so here, GridSearchCV can be used to test candidate algorithms."
},
{
"code": null,
"e": 7895,
"s": 7803,
"text": "We can find the best hyperparameter values using grid.best_params_ , which in this case is:"
},
{
"code": null,
"e": 7945,
"s": 7895,
"text": "{'C': 1, 'fit_intercept': False, 'penalty': 'l1'}"
},
{
"code": null,
"e": 8076,
"s": 7945,
"text": "With this information, we can formally train our model. We will be training the model on the training and validation set combined."
},
{
"code": null,
"e": 8306,
"s": 8076,
"text": "Let’s test the model against our test set. The classification report gives the precision, recall and f1-score (the support is the number of observations in each class). The micro f1-score is 0.81 while the macro f1-score is 0.74."
},
{
"code": null,
"e": 8361,
"s": 8306,
"text": "We can visualize this result using a confusion matrix."
},
{
"code": null,
"e": 8627,
"s": 8361,
"text": "Not bad for an initial model. This synthetic dataset was very simple: real world telecommunication companies will likely have more than 7000 data points. Other variables, such as customer interactions with support staff, could have been helpful in predicting churn."
},
{
"code": null,
"e": 8751,
"s": 8627,
"text": "However, this dataset was incredibly clean and came with a nice churn indicator that we often don’t find in the real world."
},
{
"code": null,
"e": 8893,
"s": 8751,
"text": "If you enjoyed this article, check out my other articles on Data Science, Math and Programming. Follow me on Medium for the latest updates. 😃"
},
{
"code": null,
"e": 9028,
"s": 8893,
"text": "I am also building a comprehensive set of free Data Science lessons and practice problems at www.dscrashcourse.com as a hobby project."
},
{
"code": null,
"e": 9245,
"s": 9028,
"text": "If you want to support my writing, consider using my affiliate link the next time you sign up for a Coursera course. Full disclosure — I receive commission for every enrollment, but it comes at no extra cost for you."
}
] |
Zero Sum Subarrays | Practice | GeeksforGeeks
|
You are given an array arr[] of size n. Find the total count of sub-arrays having their sum equal to 0.
Example 1:
Input:
n = 6
arr[] = {0,0,5,5,0,0}
Output: 6
Explanation: The 6 subarrays are
[0], [0], [0], [0], [0,0], and [0,0].
Example 2:
Input:
n = 10
arr[] = {6,-1,-3,4,-2,2,4,6,-12,-7}
Output: 4
Explanation: The 4 subarrays are [-1 -3 4]
[-2 2], [2 4 6 -12], and [-1 -3 4 -2 2]
Your Task:
You don't need to read input or print anything. Complete the function findSubarray() that takes the array arr and its size n as input parameters and returns the total number of sub-arrays with 0 sum.
Expected Time Complexity : O(n)
Expected Auxilliary Space : O(n)
Constraints:
1<= n <= 107
-1010 <= arri <= 1010
0
gauravyashwardhansingh00021 hours ago
int sum=0, count=0, i=0, j=0; unordered_map<int, int>s; for(i=0; i<n; i++){ sum += nums[i]; if(sum==0) count++; if(s.find(sum-0)!=s.end()) count+=s[sum-0]; s[sum]++; } return count;
0
shubham211019973 days ago
public static long findSubarray(long[] arr ,int n)
{
long count=0;
HashMap<Long,Long>h=new HashMap<>();
h.put((long)0,(long)1);
long presum=0;
for(long i:arr){
presum+=i;
if(h.containsKey(presum)){
count+=(long)(h.get(presum));
h.put(presum,h.getOrDefault(presum,(long)0)+(long)1);
}else{
h.put(presum,h.getOrDefault(presum,(long)0)+(long)1);
}
}
return count;
}
+1
madhukartemba3 weeks ago
JAVA SOLUTION:
class Solution{
//Function to count subarrays with sum equal to 0.
public static long findSubarray(long[] arr ,int n)
{
HashMap<Long, Long> map = new HashMap<>();
long count = 0;
long cur_sum = 0;
for(int i=0; i<n; i++)
{
cur_sum += arr[i];
if(cur_sum==0) count++;
count += map.getOrDefault(cur_sum, 0l);
//System.out.println(count);
map.put(cur_sum, map.getOrDefault(cur_sum, 0l)+1l);
}
return count;
}
}
+2
harshilgupta00993 weeks ago
ll findSubarray(vector<ll> arr, int n ) {
//code here
unordered_map<int,int> umap;
ll presum=0,ans=0;
umap[presum]=1;
for(auto x:arr){
presum+=x;
if(umap.find(presum)!=umap.end()){
ans+=umap[presum];
}
umap[presum]++;
}
return ans;
}
+1
kashyapjhon3 weeks ago
C++ Solution Time=(1.55/4.79) MEDIUM:
ll findSubarray(vector<ll> arr, int n ) { unordered_map<int,int> u; u.insert({0,1}); ll sum=0,c=0; for(int i=0;i<n;i++){ sum=sum+arr[i]; auto it= u.find(sum); if(it!=u.end()){ c=c+it->second; } u[sum]++; } return c; }
0
gulashanshashishekhar293 weeks ago
ll count = 0, sum = 0;
unordered_map<ll, int> m;
for (int i = 0; i < n; i++) {
sum += arr[i];
count += m[sum]++;
if (sum == 0) count++;
}
return count;
0
chintubhuarya753 weeks ago
//1.5 second solution
int count=0; unordered_map<int,int> m; unordered_map<int,int> :: iterator it; m[0]++; int add=0; for(int i=0; i<n; i++) { add = add+ arr[i]; it=m.find(add); if(it!=m.end()) { count+=it->second; } m[add]++;
}
return count;
+2
ansarizia93351 month ago
3.3 sec JAVA Soln(Using HashMap)
T:O(N)
S:O(N)
class Solution{ //Function to count subarrays with sum equal to 0. public static long findSubarray(long[] ar ,int n) { long sum=0,count=0; HashMap<Long,Long> hs=new HashMap<>(); hs.put(0L,1L); for(int i=0;i<n;i++) {sum+=ar[i]; long x=hs.getOrDefault(sum,0L); count+=x; hs.put(sum,x+1); } return count; }}
0
itachinamikaze2211 month ago
JAVA
class Solution{ //Function to count subarrays with sum equal to 0. public static long findSubarray(long[] arr ,int n) { long c=0; long sum=0; HashMap<Long, Integer> map= new HashMap<>(); map.put(sum,1); for(int i=0; i<arr.length; i++) { sum=sum+arr[i]; if (map.containsKey(sum)) { c=c+map.get(sum); map.put(sum, map.get(sum)+1); } else map.put(sum, 1); } return c; }}
0
tirtha19025681 month ago
class Solution{
public static long findSubarray(long[] arr ,int n)
{
HashMap<Long,Long>map = new HashMap<>();
map.put(0l,1l);
long count = 0;
long sum = 0;
for(int i=0;i<n;i++)
{
sum = sum + arr[i];
if(map.containsKey(sum)){
count+=map.get(sum);
map.put(sum,map.get(sum)+1);
}else{
map.put(sum,1l);
}
}
return count;
}
}
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": 342,
"s": 238,
"text": "You are given an array arr[] of size n. Find the total count of sub-arrays having their sum equal to 0."
},
{
"code": null,
"e": 354,
"s": 342,
"text": "\nExample 1:"
},
{
"code": null,
"e": 471,
"s": 354,
"text": "Input:\nn = 6\narr[] = {0,0,5,5,0,0}\nOutput: 6\nExplanation: The 6 subarrays are \n[0], [0], [0], [0], [0,0], and [0,0]."
},
{
"code": null,
"e": 483,
"s": 471,
"text": "\nExample 2:"
},
{
"code": null,
"e": 627,
"s": 483,
"text": "Input:\nn = 10\narr[] = {6,-1,-3,4,-2,2,4,6,-12,-7}\nOutput: 4\nExplanation: The 4 subarrays are [-1 -3 4]\n[-2 2], [2 4 6 -12], and [-1 -3 4 -2 2]\n"
},
{
"code": null,
"e": 842,
"s": 627,
"text": "\nYour Task:\nYou don't need to read input or print anything. Complete the function findSubarray() that takes the array arr and its size n as input parameters and returns the total number of sub-arrays with 0 sum. \n "
},
{
"code": null,
"e": 909,
"s": 842,
"text": "Expected Time Complexity : O(n)\nExpected Auxilliary Space : O(n)\n "
},
{
"code": null,
"e": 961,
"s": 909,
"text": "Constraints: \n1<= n <= 107\n-1010 <= arri <= 1010"
},
{
"code": null,
"e": 965,
"s": 963,
"text": "0"
},
{
"code": null,
"e": 1003,
"s": 965,
"text": "gauravyashwardhansingh00021 hours ago"
},
{
"code": null,
"e": 1293,
"s": 1003,
"text": "int sum=0, count=0, i=0, j=0; unordered_map<int, int>s; for(i=0; i<n; i++){ sum += nums[i]; if(sum==0) count++; if(s.find(sum-0)!=s.end()) count+=s[sum-0]; s[sum]++; } return count;"
},
{
"code": null,
"e": 1295,
"s": 1293,
"text": "0"
},
{
"code": null,
"e": 1321,
"s": 1295,
"text": "shubham211019973 days ago"
},
{
"code": null,
"e": 1829,
"s": 1321,
"text": " public static long findSubarray(long[] arr ,int n) \n {\n long count=0;\n HashMap<Long,Long>h=new HashMap<>();\n h.put((long)0,(long)1);\n long presum=0;\n for(long i:arr){\n presum+=i;\n if(h.containsKey(presum)){\n count+=(long)(h.get(presum));\n h.put(presum,h.getOrDefault(presum,(long)0)+(long)1);\n }else{\n h.put(presum,h.getOrDefault(presum,(long)0)+(long)1);\n }\n }\n return count;\n }"
},
{
"code": null,
"e": 1832,
"s": 1829,
"text": "+1"
},
{
"code": null,
"e": 1857,
"s": 1832,
"text": "madhukartemba3 weeks ago"
},
{
"code": null,
"e": 1872,
"s": 1857,
"text": "JAVA SOLUTION:"
},
{
"code": null,
"e": 2539,
"s": 1872,
"text": "class Solution{\n //Function to count subarrays with sum equal to 0.\n public static long findSubarray(long[] arr ,int n) \n {\n \n HashMap<Long, Long> map = new HashMap<>();\n \n long count = 0;\n \n long cur_sum = 0;\n \n \n for(int i=0; i<n; i++)\n {\n cur_sum += arr[i];\n \n if(cur_sum==0) count++;\n \n count += map.getOrDefault(cur_sum, 0l);\n \n //System.out.println(count);\n \n map.put(cur_sum, map.getOrDefault(cur_sum, 0l)+1l);\n \n }\n \n return count;\n \n }\n}"
},
{
"code": null,
"e": 2542,
"s": 2539,
"text": "+2"
},
{
"code": null,
"e": 2570,
"s": 2542,
"text": "harshilgupta00993 weeks ago"
},
{
"code": null,
"e": 2950,
"s": 2570,
"text": "ll findSubarray(vector<ll> arr, int n ) {\n //code here\n unordered_map<int,int> umap;\n ll presum=0,ans=0;\n umap[presum]=1;\n \n for(auto x:arr){\n presum+=x;\n \n if(umap.find(presum)!=umap.end()){\n ans+=umap[presum];\n }\n umap[presum]++;\n }\n return ans;\n }"
},
{
"code": null,
"e": 2953,
"s": 2950,
"text": "+1"
},
{
"code": null,
"e": 2976,
"s": 2953,
"text": "kashyapjhon3 weeks ago"
},
{
"code": null,
"e": 3014,
"s": 2976,
"text": "C++ Solution Time=(1.55/4.79) MEDIUM:"
},
{
"code": null,
"e": 3334,
"s": 3014,
"text": "ll findSubarray(vector<ll> arr, int n ) { unordered_map<int,int> u; u.insert({0,1}); ll sum=0,c=0; for(int i=0;i<n;i++){ sum=sum+arr[i]; auto it= u.find(sum); if(it!=u.end()){ c=c+it->second; } u[sum]++; } return c; }"
},
{
"code": null,
"e": 3336,
"s": 3334,
"text": "0"
},
{
"code": null,
"e": 3371,
"s": 3336,
"text": "gulashanshashishekhar293 weeks ago"
},
{
"code": null,
"e": 3535,
"s": 3371,
"text": "ll count = 0, sum = 0;\nunordered_map<ll, int> m;\nfor (int i = 0; i < n; i++) {\n sum += arr[i];\n count += m[sum]++;\n if (sum == 0) count++;\n}\nreturn count;"
},
{
"code": null,
"e": 3537,
"s": 3535,
"text": "0"
},
{
"code": null,
"e": 3564,
"s": 3537,
"text": "chintubhuarya753 weeks ago"
},
{
"code": null,
"e": 3586,
"s": 3564,
"text": "//1.5 second solution"
},
{
"code": null,
"e": 3848,
"s": 3586,
"text": "int count=0; unordered_map<int,int> m; unordered_map<int,int> :: iterator it; m[0]++; int add=0; for(int i=0; i<n; i++) { add = add+ arr[i]; it=m.find(add); if(it!=m.end()) { count+=it->second; } m[add]++;"
},
{
"code": null,
"e": 3856,
"s": 3848,
"text": " } "
},
{
"code": null,
"e": 3873,
"s": 3856,
"text": " return count;"
},
{
"code": null,
"e": 3876,
"s": 3873,
"text": "+2"
},
{
"code": null,
"e": 3901,
"s": 3876,
"text": "ansarizia93351 month ago"
},
{
"code": null,
"e": 3934,
"s": 3901,
"text": "3.3 sec JAVA Soln(Using HashMap)"
},
{
"code": null,
"e": 3941,
"s": 3934,
"text": "T:O(N)"
},
{
"code": null,
"e": 3948,
"s": 3941,
"text": "S:O(N)"
},
{
"code": null,
"e": 4322,
"s": 3948,
"text": "class Solution{ //Function to count subarrays with sum equal to 0. public static long findSubarray(long[] ar ,int n) { long sum=0,count=0; HashMap<Long,Long> hs=new HashMap<>(); hs.put(0L,1L); for(int i=0;i<n;i++) {sum+=ar[i]; long x=hs.getOrDefault(sum,0L); count+=x; hs.put(sum,x+1); } return count; }}"
},
{
"code": null,
"e": 4324,
"s": 4322,
"text": "0"
},
{
"code": null,
"e": 4353,
"s": 4324,
"text": "itachinamikaze2211 month ago"
},
{
"code": null,
"e": 4359,
"s": 4353,
"text": "JAVA "
},
{
"code": null,
"e": 4872,
"s": 4359,
"text": "class Solution{ //Function to count subarrays with sum equal to 0. public static long findSubarray(long[] arr ,int n) { long c=0; long sum=0; HashMap<Long, Integer> map= new HashMap<>(); map.put(sum,1); for(int i=0; i<arr.length; i++) { sum=sum+arr[i]; if (map.containsKey(sum)) { c=c+map.get(sum); map.put(sum, map.get(sum)+1); } else map.put(sum, 1); } return c; }}"
},
{
"code": null,
"e": 4874,
"s": 4872,
"text": "0"
},
{
"code": null,
"e": 4899,
"s": 4874,
"text": "tirtha19025681 month ago"
},
{
"code": null,
"e": 5391,
"s": 4899,
"text": "class Solution{\n public static long findSubarray(long[] arr ,int n) \n {\n HashMap<Long,Long>map = new HashMap<>();\n map.put(0l,1l);\n long count = 0;\n long sum = 0;\n \n for(int i=0;i<n;i++)\n {\n sum = sum + arr[i];\n if(map.containsKey(sum)){\n count+=map.get(sum);\n map.put(sum,map.get(sum)+1);\n }else{\n map.put(sum,1l);\n }\n }\n \n return count;\n }\n}"
},
{
"code": null,
"e": 5537,
"s": 5391,
"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": 5573,
"s": 5537,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5583,
"s": 5573,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5593,
"s": 5583,
"text": "\nContest\n"
},
{
"code": null,
"e": 5656,
"s": 5593,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5804,
"s": 5656,
"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": 6012,
"s": 5804,
"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": 6118,
"s": 6012,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to rename multiple files recursively using Python?
|
You can use os.walk to recursively walk through the directory and subsequently use os.rename to rename the files.
import os
def replace(folder_path, old, new):
for path, subdirs, files in os.walk(folder_path):
for name in files:
if(old.lower() in name.lower()):
file_path = os.path.join(path,name)
new_name = os.path.join(path,name.lower().replace(old,new))
os.rename(file_path, new_name)
You can use this function as follows −
replace('my_folder', 'IMG', 'Image')
This will find all files recursively within the folder and its sub-folders and replace IMG with Image in each one of them. You can modify the function as it suits you for a better result suited to your need.
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "You can use os.walk to recursively walk through the directory and subsequently use os.rename to rename the files."
},
{
"code": null,
"e": 1523,
"s": 1176,
"text": "import os\ndef replace(folder_path, old, new):\n for path, subdirs, files in os.walk(folder_path):\n for name in files:\n if(old.lower() in name.lower()):\n file_path = os.path.join(path,name)\n new_name = os.path.join(path,name.lower().replace(old,new))\n os.rename(file_path, new_name)"
},
{
"code": null,
"e": 1562,
"s": 1523,
"text": "You can use this function as follows −"
},
{
"code": null,
"e": 1599,
"s": 1562,
"text": "replace('my_folder', 'IMG', 'Image')"
},
{
"code": null,
"e": 1807,
"s": 1599,
"text": "This will find all files recursively within the folder and its sub-folders and replace IMG with Image in each one of them. You can modify the function as it suits you for a better result suited to your need."
}
] |
numpy.column_stack() in Python - GeeksforGeeks
|
06 Jan, 2019
numpy.column_stack() function is used to stack 1-D arrays as columns into a 2-D array.It takes a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack function.
Syntax : numpy.column_stack(tup)
Parameters :tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same first dimension.Return : [stacked 2-D array] The stacked 2-D array of the input arrays.
Code #1 :
# Python program explaining# column_stack() function import numpy as geek # input arrayin_arr1 = geek.array(( 1, 2, 3 ))print ("1st Input array : \n", in_arr1) in_arr2 = geek.array(( 4, 5, 6 ))print ("2nd Input array : \n", in_arr2) # Stacking the two arrays out_arr = geek.column_stack((in_arr1, in_arr2))print ("Output stacked array:\n ", out_arr)
1st Input array :
[1 2 3]
2nd Input array :
[4 5 6]
Output stacked array:
[[1 4]
[2 5]
[3 6]]
Code #2 :
# Python program explaining# column_stack() function import numpy as geek # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print ("1st Input array : \n", in_arr1) in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print ("2nd Input array : \n", in_arr2) # Stacking the two arrays out_arr = geek.column_stack((in_arr1, in_arr2))print ("Output stacked array :\n ", out_arr)
1st Input array :
[[ 1 2 3]
[-1 -2 -3]]
2nd Input array :
[[ 4 5 6]
[-4 -5 -6]]
Output stacked array :
[[ 1 2 3 4 5 6]
[-1 -2 -3 -4 -5 -6]]
Python numpy-arrayManipulation
Python-numpy
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
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
|
[
{
"code": null,
"e": 26221,
"s": 26193,
"text": "\n06 Jan, 2019"
},
{
"code": null,
"e": 26457,
"s": 26221,
"text": "numpy.column_stack() function is used to stack 1-D arrays as columns into a 2-D array.It takes a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack function."
},
{
"code": null,
"e": 26490,
"s": 26457,
"text": "Syntax : numpy.column_stack(tup)"
},
{
"code": null,
"e": 26688,
"s": 26490,
"text": "Parameters :tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same first dimension.Return : [stacked 2-D array] The stacked 2-D array of the input arrays."
},
{
"code": null,
"e": 26698,
"s": 26688,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# column_stack() function import numpy as geek # input arrayin_arr1 = geek.array(( 1, 2, 3 ))print (\"1st Input array : \\n\", in_arr1) in_arr2 = geek.array(( 4, 5, 6 ))print (\"2nd Input array : \\n\", in_arr2) # Stacking the two arrays out_arr = geek.column_stack((in_arr1, in_arr2))print (\"Output stacked array:\\n \", out_arr)",
"e": 27054,
"s": 26698,
"text": null
},
{
"code": null,
"e": 27157,
"s": 27054,
"text": "1st Input array : \n [1 2 3]\n2nd Input array : \n [4 5 6]\nOutput stacked array:\n [[1 4]\n [2 5]\n [3 6]]\n"
},
{
"code": null,
"e": 27168,
"s": 27157,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# column_stack() function import numpy as geek # input arrayin_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )print (\"1st Input array : \\n\", in_arr1) in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )print (\"2nd Input array : \\n\", in_arr2) # Stacking the two arrays out_arr = geek.column_stack((in_arr1, in_arr2))print (\"Output stacked array :\\n \", out_arr)",
"e": 27559,
"s": 27168,
"text": null
},
{
"code": null,
"e": 27718,
"s": 27559,
"text": "1st Input array : \n [[ 1 2 3]\n [-1 -2 -3]]\n2nd Input array : \n [[ 4 5 6]\n [-4 -5 -6]]\nOutput stacked array :\n [[ 1 2 3 4 5 6]\n [-1 -2 -3 -4 -5 -6]]\n"
},
{
"code": null,
"e": 27749,
"s": 27718,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 27762,
"s": 27749,
"text": "Python-numpy"
},
{
"code": null,
"e": 27769,
"s": 27762,
"text": "Python"
},
{
"code": null,
"e": 27867,
"s": 27769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27885,
"s": 27867,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27917,
"s": 27885,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27939,
"s": 27917,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27981,
"s": 27939,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28025,
"s": 27981,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28054,
"s": 28025,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28091,
"s": 28054,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28133,
"s": 28091,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28175,
"s": 28133,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
How to create a TreeView using JavaFX?
|
A tree provides a view of hierarchical structures, each tree contains a root (highest object) and it contains children. You can create a tree view by instantiating the javafx.scene.control.TreeView class.
The following Example demonstrates the creation of a TreeView.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class TreeViewExample extends Application {
public void start(Stage stage) {
//Creating tree items
TreeItem root1 = new TreeItem("Programming Languages");
TreeItem item1 = new TreeItem("Java");
TreeItem item2 = new TreeItem("Python");
TreeItem item3 = new TreeItem("C++");
//Adding elements to root1
root1.getChildren().addAll(item1, item2, item3);
TreeItem root2 = new TreeItem("NoSQL Databases");
TreeItem item4 = new TreeItem("Neo4j");
TreeItem item5 = new TreeItem("HBase");
TreeItem item6 = new TreeItem("Cassandra");
//Adding elements to root2
root2.getChildren().addAll(item4, item5, item6);
TreeItem root3 = new TreeItem("Bigdata & Analytics");
TreeItem item7 = new TreeItem("Hadoop");
TreeItem item8 = new TreeItem("Mahout");
TreeItem item9 = new TreeItem("Hive");
//Adding elements to root2
root3.getChildren().addAll(item7, item8, item9);
//list View for educational qualification
TreeItem<String> base = new TreeItem<String>("Technologies");
base.setExpanded(true);
base.getChildren().addAll(root1, root2, root3);
//Creating a TreeView item
TreeView view = new TreeView(base);
view.setPrefHeight(300);
VBox pane = new VBox(10);
pane.setPadding(new Insets(5, 5, 5, 50));
pane.getChildren().addAll(view);
//Setting the stage
Group node = new Group(pane);
Scene scene = new Scene(node, 595, 320, Color.BEIGE);
stage.setTitle("List View Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1267,
"s": 1062,
"text": "A tree provides a view of hierarchical structures, each tree contains a root (highest object) and it contains children. You can create a tree view by instantiating the javafx.scene.control.TreeView class."
},
{
"code": null,
"e": 1330,
"s": 1267,
"text": "The following Example demonstrates the creation of a TreeView."
},
{
"code": null,
"e": 3311,
"s": 1330,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.TreeItem;\nimport javafx.scene.control.TreeView;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class TreeViewExample extends Application {\n public void start(Stage stage) {\n //Creating tree items\n TreeItem root1 = new TreeItem(\"Programming Languages\");\n TreeItem item1 = new TreeItem(\"Java\");\n TreeItem item2 = new TreeItem(\"Python\");\n TreeItem item3 = new TreeItem(\"C++\");\n //Adding elements to root1\n root1.getChildren().addAll(item1, item2, item3);\n TreeItem root2 = new TreeItem(\"NoSQL Databases\");\n TreeItem item4 = new TreeItem(\"Neo4j\");\n TreeItem item5 = new TreeItem(\"HBase\");\n TreeItem item6 = new TreeItem(\"Cassandra\");\n //Adding elements to root2\n root2.getChildren().addAll(item4, item5, item6);\n TreeItem root3 = new TreeItem(\"Bigdata & Analytics\");\n TreeItem item7 = new TreeItem(\"Hadoop\");\n TreeItem item8 = new TreeItem(\"Mahout\");\n TreeItem item9 = new TreeItem(\"Hive\");\n //Adding elements to root2\n root3.getChildren().addAll(item7, item8, item9);\n //list View for educational qualification\n TreeItem<String> base = new TreeItem<String>(\"Technologies\");\n base.setExpanded(true);\n base.getChildren().addAll(root1, root2, root3);\n //Creating a TreeView item\n TreeView view = new TreeView(base);\n view.setPrefHeight(300);\n VBox pane = new VBox(10);\n pane.setPadding(new Insets(5, 5, 5, 50));\n pane.getChildren().addAll(view);\n //Setting the stage\n Group node = new Group(pane);\n Scene scene = new Scene(node, 595, 320, Color.BEIGE);\n stage.setTitle(\"List View Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
CSS | z-index Property - GeeksforGeeks
|
09 Aug, 2019
The z-index property is used to displace elements on the z-axis i.e in or out of the screen. It is used to define the order of elements if they overlap on each other.
Syntax:
z-index: auto|number|initial|inherit;
Property values:
auto: The stack order is equal to that of the parent(default).
number: The stack order depends in the number.
initial: Sets the property to its default value.
inherit: Inherits the property from the parent element.
Example 1:
<!DOCTYPE html><html> <head> <title> z-index Property </title> <style> img { position: absolute; left: 0px; top: 0px; z-index: -1; } h1, p { background-color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geek.png" width="400" height="150"> <p>This example shows the use of z-index property.</p></body> </html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title> z-index Property </title> <style> img { position: absolute; left: 0px; top: 0px; z-index: +1; } h1, p { background-color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geek.png" width="400" height="150"> <p>This example shows the use of z-index property.</p></body> </html>
Output:
In the Example-1 the z-index is set to -1 therefore, the image appears behind the text but in Example-2 when the z-index is set to +1 the image hides the text.
Supported Browsers: The browser supported by z-index property are listed below:
Google Chrome 1.0
Edge 12.0
Firefox 1.0
Opera 4.0
Apple Safari 1.0
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 23680,
"s": 23652,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 23847,
"s": 23680,
"text": "The z-index property is used to displace elements on the z-axis i.e in or out of the screen. It is used to define the order of elements if they overlap on each other."
},
{
"code": null,
"e": 23855,
"s": 23847,
"text": "Syntax:"
},
{
"code": null,
"e": 23894,
"s": 23855,
"text": "z-index: auto|number|initial|inherit;\n"
},
{
"code": null,
"e": 23911,
"s": 23894,
"text": "Property values:"
},
{
"code": null,
"e": 23974,
"s": 23911,
"text": "auto: The stack order is equal to that of the parent(default)."
},
{
"code": null,
"e": 24021,
"s": 23974,
"text": "number: The stack order depends in the number."
},
{
"code": null,
"e": 24070,
"s": 24021,
"text": "initial: Sets the property to its default value."
},
{
"code": null,
"e": 24126,
"s": 24070,
"text": "inherit: Inherits the property from the parent element."
},
{
"code": null,
"e": 24137,
"s": 24126,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> z-index Property </title> <style> img { position: absolute; left: 0px; top: 0px; z-index: -1; } h1, p { background-color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geek.png\" width=\"400\" height=\"150\"> <p>This example shows the use of z-index property.</p></body> </html>",
"e": 24661,
"s": 24137,
"text": null
},
{
"code": null,
"e": 24669,
"s": 24661,
"text": "Output:"
},
{
"code": null,
"e": 24680,
"s": 24669,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> z-index Property </title> <style> img { position: absolute; left: 0px; top: 0px; z-index: +1; } h1, p { background-color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geek.png\" width=\"400\" height=\"150\"> <p>This example shows the use of z-index property.</p></body> </html>",
"e": 25204,
"s": 24680,
"text": null
},
{
"code": null,
"e": 25212,
"s": 25204,
"text": "Output:"
},
{
"code": null,
"e": 25372,
"s": 25212,
"text": "In the Example-1 the z-index is set to -1 therefore, the image appears behind the text but in Example-2 when the z-index is set to +1 the image hides the text."
},
{
"code": null,
"e": 25452,
"s": 25372,
"text": "Supported Browsers: The browser supported by z-index property are listed below:"
},
{
"code": null,
"e": 25470,
"s": 25452,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 25480,
"s": 25470,
"text": "Edge 12.0"
},
{
"code": null,
"e": 25492,
"s": 25480,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 25502,
"s": 25492,
"text": "Opera 4.0"
},
{
"code": null,
"e": 25519,
"s": 25502,
"text": "Apple Safari 1.0"
},
{
"code": null,
"e": 25534,
"s": 25519,
"text": "CSS-Properties"
},
{
"code": null,
"e": 25541,
"s": 25534,
"text": "Picked"
},
{
"code": null,
"e": 25545,
"s": 25541,
"text": "CSS"
},
{
"code": null,
"e": 25562,
"s": 25545,
"text": "Web Technologies"
},
{
"code": null,
"e": 25660,
"s": 25562,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25669,
"s": 25660,
"text": "Comments"
},
{
"code": null,
"e": 25682,
"s": 25669,
"text": "Old Comments"
},
{
"code": null,
"e": 25744,
"s": 25682,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25794,
"s": 25744,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 25842,
"s": 25794,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25900,
"s": 25842,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 25950,
"s": 25900,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 25992,
"s": 25950,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26025,
"s": 25992,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26087,
"s": 26025,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26130,
"s": 26087,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
TypeScript | Array shift() Method - GeeksforGeeks
|
18 Jun, 2020
The Array.shift() is an inbuilt TypeScript function which is used to remove the first element from an array and returns that element. Syntax:
array.shift();
Parameter: This methods does not accept any parameter. Return Value: This method returns the removed single value of the array. Below example illustrate the Array shift() method in TypeScriptJS:
Example 1:
JavaScript
<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of shift() method var val = arr.shift(); // printing console.log( val ); console.log( arr );</script>
Output:
11
[ 89, 23, 7, 98 ]
Example 2:
JavaScript
<script> // Driver code var arr = [2, 5, 6, 3, 8, 9]; var val; // use of reverse() method val = arr.shift(); console.log( val ); val = arr.shift(); console.log( val ); // printing console.log( arr );</script>
Output:
2
5
[ 6, 3, 8, 9 ]
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26123,
"s": 26095,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 26265,
"s": 26123,
"text": "The Array.shift() is an inbuilt TypeScript function which is used to remove the first element from an array and returns that element. Syntax:"
},
{
"code": null,
"e": 26281,
"s": 26265,
"text": "array.shift(); "
},
{
"code": null,
"e": 26478,
"s": 26281,
"text": "Parameter: This methods does not accept any parameter. Return Value: This method returns the removed single value of the array. Below example illustrate the Array shift() method in TypeScriptJS:"
},
{
"code": null,
"e": 26490,
"s": 26478,
"text": "Example 1: "
},
{
"code": null,
"e": 26501,
"s": 26490,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of shift() method var val = arr.shift(); // printing console.log( val ); console.log( arr );</script>",
"e": 26698,
"s": 26501,
"text": null
},
{
"code": null,
"e": 26707,
"s": 26698,
"text": "Output: "
},
{
"code": null,
"e": 26730,
"s": 26707,
"text": "11\n[ 89, 23, 7, 98 ]\n\n"
},
{
"code": null,
"e": 26742,
"s": 26730,
"text": "Example 2: "
},
{
"code": null,
"e": 26753,
"s": 26742,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [2, 5, 6, 3, 8, 9]; var val; // use of reverse() method val = arr.shift(); console.log( val ); val = arr.shift(); console.log( val ); // printing console.log( arr );</script>",
"e": 27003,
"s": 26753,
"text": null
},
{
"code": null,
"e": 27012,
"s": 27003,
"text": "Output: "
},
{
"code": null,
"e": 27032,
"s": 27012,
"text": "2\n5\n[ 6, 3, 8, 9 ]\n"
},
{
"code": null,
"e": 27043,
"s": 27032,
"text": "TypeScript"
},
{
"code": null,
"e": 27054,
"s": 27043,
"text": "JavaScript"
},
{
"code": null,
"e": 27071,
"s": 27054,
"text": "Web Technologies"
},
{
"code": null,
"e": 27169,
"s": 27071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27209,
"s": 27169,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27254,
"s": 27209,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27315,
"s": 27254,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27387,
"s": 27315,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27439,
"s": 27387,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27479,
"s": 27439,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27512,
"s": 27479,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27557,
"s": 27512,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27600,
"s": 27557,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Colorizing text and console background in C++ - GeeksforGeeks
|
27 Jan, 2021
In C++ programming, the default background of the output screen is black and the text color is the white color, the task is to color both the background and text color in the output screen.
Header File:
The header file required to color the text and background can be either of the given header files:
#include <windows.h>or#include <stdlib.h>
Syntax of the color console:
HANDLE console_color;
// Color of the consoleconsole_color = GetStdHandle(STD_OUTPUT_HANDLE);
// P is color code according to your need.SetConsoleTextAttribute(console_color, P);
Below is the program for the same:
C++
// C++ program for the coloring the// background and text with// different color#include <iostream> // Header file to change color of// text and background#include <windows.h>using namespace std; // Driver Codeint main(){ // Color of the console HANDLE console_color; console_color = GetStdHandle( STD_OUTPUT_HANDLE); // Print different colors from 1 // to 50 on the output screen for (int P = 1; P < 50; P++) { // P is color code of the // corresponding color SetConsoleTextAttribute( console_color, P); // Print Statement cout << P << " Hello Geeks, " << "good night!!!"; } return 0;}
Output:
Technical Scripter 2020
C++
C++ Programs
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
CSV file management using C++
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 24098,
"s": 24070,
"text": "\n27 Jan, 2021"
},
{
"code": null,
"e": 24288,
"s": 24098,
"text": "In C++ programming, the default background of the output screen is black and the text color is the white color, the task is to color both the background and text color in the output screen."
},
{
"code": null,
"e": 24301,
"s": 24288,
"text": "Header File:"
},
{
"code": null,
"e": 24400,
"s": 24301,
"text": "The header file required to color the text and background can be either of the given header files:"
},
{
"code": null,
"e": 24442,
"s": 24400,
"text": "#include <windows.h>or#include <stdlib.h>"
},
{
"code": null,
"e": 24471,
"s": 24442,
"text": "Syntax of the color console:"
},
{
"code": null,
"e": 24493,
"s": 24471,
"text": "HANDLE console_color;"
},
{
"code": null,
"e": 24565,
"s": 24493,
"text": "// Color of the consoleconsole_color = GetStdHandle(STD_OUTPUT_HANDLE);"
},
{
"code": null,
"e": 24650,
"s": 24565,
"text": "// P is color code according to your need.SetConsoleTextAttribute(console_color, P);"
},
{
"code": null,
"e": 24685,
"s": 24650,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 24689,
"s": 24685,
"text": "C++"
},
{
"code": "// C++ program for the coloring the// background and text with// different color#include <iostream> // Header file to change color of// text and background#include <windows.h>using namespace std; // Driver Codeint main(){ // Color of the console HANDLE console_color; console_color = GetStdHandle( STD_OUTPUT_HANDLE); // Print different colors from 1 // to 50 on the output screen for (int P = 1; P < 50; P++) { // P is color code of the // corresponding color SetConsoleTextAttribute( console_color, P); // Print Statement cout << P << \" Hello Geeks, \" << \"good night!!!\"; } return 0;}",
"e": 25375,
"s": 24689,
"text": null
},
{
"code": null,
"e": 25383,
"s": 25375,
"text": "Output:"
},
{
"code": null,
"e": 25407,
"s": 25383,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 25411,
"s": 25407,
"text": "C++"
},
{
"code": null,
"e": 25424,
"s": 25411,
"text": "C++ Programs"
},
{
"code": null,
"e": 25443,
"s": 25424,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25447,
"s": 25443,
"text": "CPP"
},
{
"code": null,
"e": 25545,
"s": 25447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25554,
"s": 25545,
"text": "Comments"
},
{
"code": null,
"e": 25567,
"s": 25554,
"text": "Old Comments"
},
{
"code": null,
"e": 25595,
"s": 25567,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25616,
"s": 25595,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 25649,
"s": 25616,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 25669,
"s": 25649,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 25693,
"s": 25669,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 25728,
"s": 25693,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 25754,
"s": 25728,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 25813,
"s": 25754,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 25843,
"s": 25813,
"text": "CSV file management using C++"
}
] |
Level with maximum number of nodes - GeeksforGeeks
|
28 Jun, 2021
Find the level in a binary tree which has the maximum number of nodes. The root is at level 0.Examples:
Input:
Output : 2
Explanation:
Input:
Output:1
Explanation
Approach: It is known that in level order traversal of binary tree with queue, at any time our queue contains all elements of a particular level. So find level with maximum number of nodes in queue. BFS traversal is an algorithm for traversing or searching tree or graphs . It starts at the tree root , and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. So at any point the queue of BFS will contain elements of adjacent layers. So this makes the algorithm perfect for this problem.Algorithm:
Create the tree, a queue to store the nodes and insert the root in the queue. Create variables level=0,count =0 and level_no=-1The implementation will be slightly different, all the elements of same level will be removed in a single iteration.Run a loop while size of queue is greater than 0. Get the size of queue (size) and store it. If size is greater than count then update count = size and level_no = level.Now run a loop size times, and pop one node from the queue and insert its childrens (if present).Increment level.
Create the tree, a queue to store the nodes and insert the root in the queue. Create variables level=0,count =0 and level_no=-1
The implementation will be slightly different, all the elements of same level will be removed in a single iteration.
Run a loop while size of queue is greater than 0. Get the size of queue (size) and store it. If size is greater than count then update count = size and level_no = level.
Now run a loop size times, and pop one node from the queue and insert its childrens (if present).
Increment level.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the level// having maximum number of Nodes#include <bits/stdc++.h>using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = NULL; node->right = NULL; return(node);} // function to find the level// having maximum number of Nodesint maxNodeLevel(Node *root){ if (root == NULL) return -1; queue<Node *> q; q.push(root); // Current level int level = 0; // Maximum Nodes at same level int max = INT_MIN; // Level having maximum Nodes int level_no = 0; while (1) { // Count Nodes in a level int NodeCount = q.size(); if (NodeCount == 0) break; // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { Node *Node = q.front(); q.pop(); if (Node->left != NULL) q.push(Node->left); if (Node->right != NULL) q.push(Node->right); NodeCount--; } // Increment for next level level++; } return level_no;} // Driver program to test aboveint main(){ // binary tree formation struct Node *root = newNode(2); /* 2 */ root->left = newNode(1); /* / \ */ root->right = newNode(3); /* 1 3 */ root->left->left = newNode(4); /* / \ \ */ root->left->right = newNode(6); /* 4 6 8 */ root->right->right = newNode(8); /* / */ root->left->right->left = newNode(5);/* 5 */ printf("Level having maximum number of Nodes : %d", maxNodeLevel(root)); return 0;}
// Java implementation to find the level// having maximum number of Nodesimport java.util.*;class GfG { /* A binary tree Node has data, pointerto left child and a pointer to rightchild */static class Node{ int data; Node left; Node right;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return(node);} // function to find the level// having maximum number of Nodesstatic int maxNodeLevel(Node root){ if (root == null) return -1; Queue<Node> q = new LinkedList<Node> (); q.add(root); // Current level int level = 0; // Maximum Nodes at same level int max = Integer.MIN_VALUE; // Level having maximum Nodes int level_no = 0; while (true) { // Count Nodes in a level int NodeCount = q.size(); if (NodeCount == 0) break; // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { Node Node = q.peek(); q.remove(); if (Node.left != null) q.add(Node.left); if (Node.right != null) q.add(Node.right); NodeCount--; } // Increment for next level level++; } return level_no;} // Driver program to test abovepublic static void main(String[] args){ // binary tree formation Node root = newNode(2); /* 2 */ root.left = newNode(1); /* / \ */ root.right = newNode(3); /* 1 3 */ root.left.left = newNode(4); /* / \ \ */ root.left.right = newNode(6); /* 4 6 8 */ root.right.right = newNode(8); /* / */ root.left.right.left = newNode(5);/* 5 */ System.out.println("Level having maximum number of Nodes : " + maxNodeLevel(root));}}
# Python3 implementation to find the# level having Maximum number of Nodes # Importing Queuefrom queue import Queue # Helper class that allocates a new# node with the given data and None# left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # function to find the level# having Maximum number of Nodesdef maxNodeLevel(root): if (root == None): return -1 q = Queue() q.put(root) # Current level level = 0 # Maximum Nodes at same level Max = -999999999999 # Level having Maximum Nodes level_no = 0 while (1): # Count Nodes in a level NodeCount = q.qsize() if (NodeCount == 0): break # If it is Maximum till now # Update level_no to current level if (NodeCount > Max): Max = NodeCount level_no = level # Pop complete current level while (NodeCount > 0): Node = q.queue[0] q.get() if (Node.left != None): q.put(Node.left) if (Node.right != None): q.put(Node.right) NodeCount -= 1 # Increment for next level level += 1 return level_no # Driver Codeif __name__ == '__main__': # binary tree formation root = newNode(2) # 2 root.left = newNode(1) # / \ root.right = newNode(3) # 1 3 root.left.left = newNode(4) # / \ \ root.left.right = newNode(6) # 4 6 8 root.right.right = newNode(8) # / root.left.right.left = newNode(5)# 5 print("Level having Maximum number of Nodes : ", maxNodeLevel(root)) # This code is contributed by Pranchalk
using System;using System.Collections.Generic; // C# implementation to find the level // having maximum number of Nodes public class GfG{ /* 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; public Node right;} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */public static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // function to find the level // having maximum number of Nodes public static int maxNodeLevel(Node root){ if (root == null) { return -1; } LinkedList<Node> q = new LinkedList<Node> (); q.AddLast(root); // Current level int level = 0; // Maximum Nodes at same level int max = int.MinValue; // Level having maximum Nodes int level_no = 0; while (true) { // Count Nodes in a level int NodeCount = q.Count; if (NodeCount == 0) { break; } // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { Node Node = q.First.Value; q.RemoveFirst(); if (Node.left != null) { q.AddLast(Node.left); } if (Node.right != null) { q.AddLast(Node.right); } NodeCount--; } // Increment for next level level++; } return level_no;} // Driver program to test above public static void Main(string[] args){ // binary tree formation Node root = newNode(2); // 2 root.left = newNode(1); // / \ root.right = newNode(3); // 1 3 root.left.left = newNode(4); // / \ \ root.left.right = newNode(6); // 4 6 8 root.right.right = newNode(8); // / root.left.right.left = newNode(5); // 5 Console.WriteLine("Level having maximum number of Nodes : " + maxNodeLevel(root));}} // This code is contributed by Shrikant13
<script> // Javascript implementation to find the level // having maximum number of Nodes /* A binary tree Node has data, pointer to left child and a pointer to right child */class Node{ constructor() { this.data = 0; this.left = null; this.right = null; }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */function newNode(data){ var node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // function to find the level // having maximum number of Nodes function maxNodeLevel(root){ if (root == null) { return -1; } var q = []; q.push(root); // Current level var level = 0; // Maximum Nodes at same level var max = -1000000000; // Level having maximum Nodes var level_no = 0; while (true) { // length Nodes in a level var NodeCount = q.length; if (NodeCount == 0) { break; } // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { var Node = q[0]; q.shift(); if (Node.left != null) { q.push(Node.left); } if (Node.right != null) { q.push(Node.right); } NodeCount--; } // Increment for next level level++; } return level_no;} // Driver program to test above // binary tree formation var root = newNode(2); // 2root.left = newNode(1); // / \root.right = newNode(3); // 1 3root.left.left = newNode(4); // / \ \root.left.right = newNode(6); // 4 6 8root.right.right = newNode(8); // /root.left.right.left = newNode(5); // 5document.write("Level having maximum number of Nodes : " + maxNodeLevel(root)); // This code is contributed by famously.</script>
Output:
Level having maximum number of nodes : 2
Complexity Analysis:
Time Complexity : O(n). In BFS traversal every node is visited only once, So Time Complexity is O(n).
Space Complexity: O(n). The space is required to store the nodes in a queue.
YouTubeGeeksforGeeks506K subscribersLevel with maximum number of nodes | 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 / 10:10•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3lMu93D5v5Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Ayush Jauhari. 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.
prerna saini
shrikanth13
PranchalKatiyar
andrew1234
famously
tree-level-order
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Deletion in a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1
|
[
{
"code": null,
"e": 24680,
"s": 24652,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24786,
"s": 24680,
"text": "Find the level in a binary tree which has the maximum number of nodes. The root is at level 0.Examples: "
},
{
"code": null,
"e": 24794,
"s": 24786,
"text": "Input: "
},
{
"code": null,
"e": 24818,
"s": 24794,
"text": "Output : 2\nExplanation:"
},
{
"code": null,
"e": 24825,
"s": 24818,
"text": "Input:"
},
{
"code": null,
"e": 24846,
"s": 24825,
"text": "Output:1\nExplanation"
},
{
"code": null,
"e": 25409,
"s": 24848,
"text": "Approach: It is known that in level order traversal of binary tree with queue, at any time our queue contains all elements of a particular level. So find level with maximum number of nodes in queue. BFS traversal is an algorithm for traversing or searching tree or graphs . It starts at the tree root , and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. So at any point the queue of BFS will contain elements of adjacent layers. So this makes the algorithm perfect for this problem.Algorithm: "
},
{
"code": null,
"e": 25935,
"s": 25409,
"text": "Create the tree, a queue to store the nodes and insert the root in the queue. Create variables level=0,count =0 and level_no=-1The implementation will be slightly different, all the elements of same level will be removed in a single iteration.Run a loop while size of queue is greater than 0. Get the size of queue (size) and store it. If size is greater than count then update count = size and level_no = level.Now run a loop size times, and pop one node from the queue and insert its childrens (if present).Increment level."
},
{
"code": null,
"e": 26063,
"s": 25935,
"text": "Create the tree, a queue to store the nodes and insert the root in the queue. Create variables level=0,count =0 and level_no=-1"
},
{
"code": null,
"e": 26180,
"s": 26063,
"text": "The implementation will be slightly different, all the elements of same level will be removed in a single iteration."
},
{
"code": null,
"e": 26350,
"s": 26180,
"text": "Run a loop while size of queue is greater than 0. Get the size of queue (size) and store it. If size is greater than count then update count = size and level_no = level."
},
{
"code": null,
"e": 26448,
"s": 26350,
"text": "Now run a loop size times, and pop one node from the queue and insert its childrens (if present)."
},
{
"code": null,
"e": 26465,
"s": 26448,
"text": "Increment level."
},
{
"code": null,
"e": 26483,
"s": 26465,
"text": "Implementation: "
},
{
"code": null,
"e": 26487,
"s": 26483,
"text": "C++"
},
{
"code": null,
"e": 26492,
"s": 26487,
"text": "Java"
},
{
"code": null,
"e": 26500,
"s": 26492,
"text": "Python3"
},
{
"code": null,
"e": 26503,
"s": 26500,
"text": "C#"
},
{
"code": null,
"e": 26514,
"s": 26503,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the level// having maximum number of Nodes#include <bits/stdc++.h>using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = NULL; node->right = NULL; return(node);} // function to find the level// having maximum number of Nodesint maxNodeLevel(Node *root){ if (root == NULL) return -1; queue<Node *> q; q.push(root); // Current level int level = 0; // Maximum Nodes at same level int max = INT_MIN; // Level having maximum Nodes int level_no = 0; while (1) { // Count Nodes in a level int NodeCount = q.size(); if (NodeCount == 0) break; // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { Node *Node = q.front(); q.pop(); if (Node->left != NULL) q.push(Node->left); if (Node->right != NULL) q.push(Node->right); NodeCount--; } // Increment for next level level++; } return level_no;} // Driver program to test aboveint main(){ // binary tree formation struct Node *root = newNode(2); /* 2 */ root->left = newNode(1); /* / \\ */ root->right = newNode(3); /* 1 3 */ root->left->left = newNode(4); /* / \\ \\ */ root->left->right = newNode(6); /* 4 6 8 */ root->right->right = newNode(8); /* / */ root->left->right->left = newNode(5);/* 5 */ printf(\"Level having maximum number of Nodes : %d\", maxNodeLevel(root)); return 0;}",
"e": 28661,
"s": 26514,
"text": null
},
{
"code": "// Java implementation to find the level// having maximum number of Nodesimport java.util.*;class GfG { /* A binary tree Node has data, pointerto left child and a pointer to rightchild */static class Node{ int data; Node left; Node right;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return(node);} // function to find the level// having maximum number of Nodesstatic int maxNodeLevel(Node root){ if (root == null) return -1; Queue<Node> q = new LinkedList<Node> (); q.add(root); // Current level int level = 0; // Maximum Nodes at same level int max = Integer.MIN_VALUE; // Level having maximum Nodes int level_no = 0; while (true) { // Count Nodes in a level int NodeCount = q.size(); if (NodeCount == 0) break; // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { Node Node = q.peek(); q.remove(); if (Node.left != null) q.add(Node.left); if (Node.right != null) q.add(Node.right); NodeCount--; } // Increment for next level level++; } return level_no;} // Driver program to test abovepublic static void main(String[] args){ // binary tree formation Node root = newNode(2); /* 2 */ root.left = newNode(1); /* / \\ */ root.right = newNode(3); /* 1 3 */ root.left.left = newNode(4); /* / \\ \\ */ root.left.right = newNode(6); /* 4 6 8 */ root.right.right = newNode(8); /* / */ root.left.right.left = newNode(5);/* 5 */ System.out.println(\"Level having maximum number of Nodes : \" + maxNodeLevel(root));}}",
"e": 30754,
"s": 28661,
"text": null
},
{
"code": "# Python3 implementation to find the# level having Maximum number of Nodes # Importing Queuefrom queue import Queue # Helper class that allocates a new# node with the given data and None# left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # function to find the level# having Maximum number of Nodesdef maxNodeLevel(root): if (root == None): return -1 q = Queue() q.put(root) # Current level level = 0 # Maximum Nodes at same level Max = -999999999999 # Level having Maximum Nodes level_no = 0 while (1): # Count Nodes in a level NodeCount = q.qsize() if (NodeCount == 0): break # If it is Maximum till now # Update level_no to current level if (NodeCount > Max): Max = NodeCount level_no = level # Pop complete current level while (NodeCount > 0): Node = q.queue[0] q.get() if (Node.left != None): q.put(Node.left) if (Node.right != None): q.put(Node.right) NodeCount -= 1 # Increment for next level level += 1 return level_no # Driver Codeif __name__ == '__main__': # binary tree formation root = newNode(2) # 2 root.left = newNode(1) # / \\ root.right = newNode(3) # 1 3 root.left.left = newNode(4) # / \\ \\ root.left.right = newNode(6) # 4 6 8 root.right.right = newNode(8) # / root.left.right.left = newNode(5)# 5 print(\"Level having Maximum number of Nodes : \", maxNodeLevel(root)) # This code is contributed by Pranchalk",
"e": 32554,
"s": 30754,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // C# implementation to find the level // having maximum number of Nodes public class GfG{ /* 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; public Node right;} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */public static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // function to find the level // having maximum number of Nodes public static int maxNodeLevel(Node root){ if (root == null) { return -1; } LinkedList<Node> q = new LinkedList<Node> (); q.AddLast(root); // Current level int level = 0; // Maximum Nodes at same level int max = int.MinValue; // Level having maximum Nodes int level_no = 0; while (true) { // Count Nodes in a level int NodeCount = q.Count; if (NodeCount == 0) { break; } // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { Node Node = q.First.Value; q.RemoveFirst(); if (Node.left != null) { q.AddLast(Node.left); } if (Node.right != null) { q.AddLast(Node.right); } NodeCount--; } // Increment for next level level++; } return level_no;} // Driver program to test above public static void Main(string[] args){ // binary tree formation Node root = newNode(2); // 2 root.left = newNode(1); // / \\ root.right = newNode(3); // 1 3 root.left.left = newNode(4); // / \\ \\ root.left.right = newNode(6); // 4 6 8 root.right.right = newNode(8); // / root.left.right.left = newNode(5); // 5 Console.WriteLine(\"Level having maximum number of Nodes : \" + maxNodeLevel(root));}} // This code is contributed by Shrikant13",
"e": 34797,
"s": 32554,
"text": null
},
{
"code": "<script> // Javascript implementation to find the level // having maximum number of Nodes /* A binary tree Node has data, pointer to left child and a pointer to right child */class Node{ constructor() { this.data = 0; this.left = null; this.right = null; }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */function newNode(data){ var node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // function to find the level // having maximum number of Nodes function maxNodeLevel(root){ if (root == null) { return -1; } var q = []; q.push(root); // Current level var level = 0; // Maximum Nodes at same level var max = -1000000000; // Level having maximum Nodes var level_no = 0; while (true) { // length Nodes in a level var NodeCount = q.length; if (NodeCount == 0) { break; } // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { var Node = q[0]; q.shift(); if (Node.left != null) { q.push(Node.left); } if (Node.right != null) { q.push(Node.right); } NodeCount--; } // Increment for next level level++; } return level_no;} // Driver program to test above // binary tree formation var root = newNode(2); // 2root.left = newNode(1); // / \\root.right = newNode(3); // 1 3root.left.left = newNode(4); // / \\ \\root.left.right = newNode(6); // 4 6 8root.right.right = newNode(8); // /root.left.right.left = newNode(5); // 5document.write(\"Level having maximum number of Nodes : \" + maxNodeLevel(root)); // This code is contributed by famously.</script>",
"e": 36861,
"s": 34797,
"text": null
},
{
"code": null,
"e": 36871,
"s": 36861,
"text": "Output: "
},
{
"code": null,
"e": 36913,
"s": 36871,
"text": "Level having maximum number of nodes : 2 "
},
{
"code": null,
"e": 36936,
"s": 36913,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 37038,
"s": 36936,
"text": "Time Complexity : O(n). In BFS traversal every node is visited only once, So Time Complexity is O(n)."
},
{
"code": null,
"e": 37115,
"s": 37038,
"text": "Space Complexity: O(n). The space is required to store the nodes in a queue."
},
{
"code": null,
"e": 37951,
"s": 37117,
"text": "YouTubeGeeksforGeeks506K subscribersLevel with maximum number of nodes | 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 / 10:10•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=3lMu93D5v5Q\" 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": 38414,
"s": 37951,
"text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Ayush Jauhari. 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": 38427,
"s": 38414,
"text": "prerna saini"
},
{
"code": null,
"e": 38439,
"s": 38427,
"text": "shrikanth13"
},
{
"code": null,
"e": 38455,
"s": 38439,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 38466,
"s": 38455,
"text": "andrew1234"
},
{
"code": null,
"e": 38475,
"s": 38466,
"text": "famously"
},
{
"code": null,
"e": 38492,
"s": 38475,
"text": "tree-level-order"
},
{
"code": null,
"e": 38497,
"s": 38492,
"text": "Tree"
},
{
"code": null,
"e": 38502,
"s": 38497,
"text": "Tree"
},
{
"code": null,
"e": 38600,
"s": 38502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38643,
"s": 38600,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 38684,
"s": 38643,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 38717,
"s": 38684,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 38731,
"s": 38717,
"text": "Decision Tree"
},
{
"code": null,
"e": 38781,
"s": 38731,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 38839,
"s": 38781,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 38875,
"s": 38839,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 38958,
"s": 38875,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 38984,
"s": 38958,
"text": "Deletion in a Binary Tree"
}
] |
Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order - GeeksforGeeks
|
16 Jun, 2021
Given a Binary Search Tree and a binary integer K, the task is to convert Binary search tree into a Skewed Tree in increasing order if K = 0 or in decreasing order if K = 1.
Examples:
Input: K = 0,
5
/ \
3 6
Output:
3
\
5
\
6
Input: K = 1,
2
/ \
1 3
Output:
3
\
2
\
1
Approach:
The key observation in the problem is that the first node of the skewed tree will be the extreme left or extreme right node of the BST for increasing order and decreasing order respectively.
For Increasing Order we need to do the Inorder Traversal, as the inorder traversal of a BST provides us the increasing sequence of the node values. Hence, the order of traversal at every node will be: Left node: Recurse to its left node if it exists, to get smaller value.Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node.Right node: Recurse to the right node if it exists, for larger values.
Left node: Recurse to its left node if it exists, to get smaller value.Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node.Right node: Recurse to the right node if it exists, for larger values.
Left node: Recurse to its left node if it exists, to get smaller value.
Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node.
Right node: Recurse to the right node if it exists, for larger values.
For Decreasing Order, the order of traversal at every node will be: Right node: Recurse to its right node if it exists, to get larger values.Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node.Left node: Recurse to the left node/subtree for smaller values.
Right node: Recurse to its right node if it exists, to get larger values.Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node.Left node: Recurse to the left node/subtree for smaller values.
Right node: Recurse to its right node if it exists, to get larger values.
Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node.
Left node: Recurse to the left node/subtree for smaller values.
Similarly, by keeping track of the previous node we can traverse the Binary search tree according to the order needed and form the skewed tree.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing order#include<bits/stdc++.h>using namespace std; // Class of the nodestruct Node{ int val; Node *left, *right; Node(int x) { val = x; left = right = NULL; }}; Node *prevNode = NULL;Node *headNode = NULL; // Function to to flatten the binary// search tree into a skewed tree in// increasing / decreasing ordervoid flattenBTToSkewed(Node *root, int order){ // Base Case if (!root) return; // Condition to check the order // in which the skewed tree to // maintained if (order) flattenBTToSkewed(root->right, order); else flattenBTToSkewed(root->left, order); Node *rightNode = root->right; Node *leftNode = root->left; // Condition to check if the root Node // of the skewed tree is not defined if (!headNode) { headNode = root; root->left = NULL; prevNode = root; } else { prevNode->right = root; root->left = NULL; prevNode = root; } // Similarly recurse for the left / right // subtree on the basis of the order required if (order) flattenBTToSkewed(leftNode, order); else flattenBTToSkewed(rightNode, order);} // Function to traverse the right// skewed tree using recursionvoid traverseRightSkewed(Node *root){ if (!root) return; cout << root->val << " "; traverseRightSkewed(root->right);} // Driver Codeint main(){ // 5 // / \ // 3 6 Node *root =new Node(5); root->left = new Node(3); root->right = new Node(6); // Order of the Skewed tree can // be defined as follows - // For Increasing order - 0 // For Decreasing order - 1 int order = 0; flattenBTToSkewed(root, order); traverseRightSkewed(headNode);} // This code is contributed by mohit kumar 29
// Java implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing orderimport java.io.*; // Class of the nodeclass Node{ int val; Node left, right; // Helper function that allocates a new node // with the given data and NULL left and right // pointers. Node(int item) { val = item; left = right = null; }}class GFG{ public static Node node; static Node prevNode = null; static Node headNode = null; // Function to to flatten the binary // search tree into a skewed tree in // increasing / decreasing order static void flattenBTToSkewed(Node root, int order) { // Base Case if(root == null) { return; } // Condition to check the order // in which the skewed tree to // maintained if(order > 0) { flattenBTToSkewed(root.right, order); } else { flattenBTToSkewed(root.left, order); } Node rightNode = root.right; Node leftNode = root.left; // Condition to check if the root Node // of the skewed tree is not defined if(headNode == null) { headNode = root; root.left = null; prevNode = root; } else { prevNode.right = root; root.left = null; prevNode = root; } // Similarly recurse for the left / right // subtree on the basis of the order required if (order > 0) { flattenBTToSkewed(leftNode, order); } else { flattenBTToSkewed(rightNode, order); } } // Function to traverse the right // skewed tree using recursion static void traverseRightSkewed(Node root) { if(root == null) { return; } System.out.print(root.val + " "); traverseRightSkewed(root.right); } // Driver Code public static void main (String[] args) { // 5 // / \ // 3 6 GFG tree = new GFG(); tree.node = new Node(5); tree.node.left = new Node(3); tree.node.right = new Node(6); // Order of the Skewed tree can // be defined as follows - // For Increasing order - 0 // For Decreasing order - 1 int order = 0; flattenBTToSkewed(node, order); traverseRightSkewed(headNode); }} // This code is contributed by avanitrachhadiya2155
# Python3 implementation to flatten# the binary search tree into a skewed# tree in increasing / decreasing order # Class of the nodeclass Node: # Constructor of node def __init__(self, val): self.val = val self.left = None self.right = None prevNode = NoneheadNode = None # Function to to flatten# the binary search tree into a skewed# tree in increasing / decreasing orderdef flattenBTToSkewed(root, order): # Base Case if not root: return # Condition to check the order # in which the skewed tree to maintained if order: flattenBTToSkewed(root.right, order) else: flattenBTToSkewed(root.left, order) global headNode; global prevNode rightNode = root.right leftNode = root.left # Condition to check if the root Node # of the skewed tree is not defined if not headNode: headNode = root root.left = None prevNode = root else: prevNode.right = root root.left = None prevNode = root # Similarly recurse for the left / right # subtree on the basis of the order required if order: flattenBTToSkewed(leftNode, order) else: flattenBTToSkewed(rightNode, order) # Function to traverse the right# skewed tree using recursiondef traverseRightSkewed(root): if not root: return print(root.val, end = " ") traverseRightSkewed(root.right) # Driver Codeif __name__ == "__main__": # 5 # / \ # 3 6 root = Node(5) root.left = Node(3) root.right = Node(6) prevNode = None headNode = None # Order of the Skewed tree can # be defined as follows - # For Increasing order - 0 # For Decreasing order - 1 order = 0 flattenBTToSkewed(root, order) traverseRightSkewed(headNode)
// C# implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing orderusing System; // Class of the nodeclass Node{ public int val; public Node left, right; // Helper function that allocates a new // node with the given data and NULL // left and right pointers. public Node(int item) { val = item; left = right = null; }} class GFG{ public static Node node;static Node prevNode = null;static Node headNode = null; // Function to to flatten the binary// search tree into a skewed tree in// increasing / decreasing orderstatic void flattenBTToSkewed(Node root, int order){ // Base Case if (root == null) { return; } // Condition to check the order // in which the skewed tree to // maintained if (order > 0) { flattenBTToSkewed(root.right, order); } else { flattenBTToSkewed(root.left, order); } Node rightNode = root.right; Node leftNode = root.left; // Condition to check if the root Node // of the skewed tree is not defined if (headNode == null) { headNode = root; root.left = null; prevNode = root; } else { prevNode.right = root; root.left = null; prevNode = root; } // Similarly recurse for the left / right // subtree on the basis of the order required if (order > 0) { flattenBTToSkewed(leftNode, order); } else { flattenBTToSkewed(rightNode, order); }} // Function to traverse the right// skewed tree using recursionstatic void traverseRightSkewed(Node root){ if (root == null) { return; } Console.Write(root.val + " "); traverseRightSkewed(root.right);} // Driver Codestatic public void Main(){ // 5 // / \ // 3 6 GFG.node = new Node(5); GFG.node.left = new Node(3); GFG.node.right = new Node(6); // Order of the Skewed tree can // be defined as follows - // For Increasing order - 0 // For Decreasing order - 1 int order = 0; flattenBTToSkewed(node, order); traverseRightSkewed(headNode);}} // This code is contributed by rag2127
<script>// Javascript implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing order // Class of the nodeclass Node{ // Helper function that allocates a new node // with the given data and NULL left and right // pointers. constructor(item) { this.val = item; this.left = this.right = null; }} let node;let prevNode = null;let headNode = null; // Function to to flatten the binary // search tree into a skewed tree in // increasing / decreasing orderfunction flattenBTToSkewed(root,order){ // Base Case if(root == null) { return; } // Condition to check the order // in which the skewed tree to // maintained if(order > 0) { flattenBTToSkewed(root.right, order); } else { flattenBTToSkewed(root.left, order); } let rightNode = root.right; let leftNode = root.left; // Condition to check if the root Node // of the skewed tree is not defined if(headNode == null) { headNode = root; root.left = null; prevNode = root; } else { prevNode.right = root; root.left = null; prevNode = root; } // Similarly recurse for the left / right // subtree on the basis of the order required if (order > 0) { flattenBTToSkewed(leftNode, order); } else { flattenBTToSkewed(rightNode, order); }} // Function to traverse the right // skewed tree using recursionfunction traverseRightSkewed(root){ if(root == null) { return; } document.write(root.val + " "); traverseRightSkewed(root.right); } // Driver Code // 5 // / \ // 3 6node = new Node(5);node.left = new Node(3);node.right = new Node(6); // Order of the Skewed tree can// be defined as follows -// For Increasing order - 0// For Decreasing order - 1let order = 0;flattenBTToSkewed(node, order);traverseRightSkewed(headNode); // This code is contributed by unknown2108</script>
3 5 6
mohit kumar 29
avanitrachhadiya2155
rag2127
unknown2108
Binary Search Tree
Recursion
Tree
Recursion
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Red Black Tree vs AVL Tree
Construct BST from given preorder traversal | Set 2
Print BST keys in the given range
Find median of BST in O(n) time and O(1) space
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": 25324,
"s": 25296,
"text": "\n16 Jun, 2021"
},
{
"code": null,
"e": 25498,
"s": 25324,
"text": "Given a Binary Search Tree and a binary integer K, the task is to convert Binary search tree into a Skewed Tree in increasing order if K = 0 or in decreasing order if K = 1."
},
{
"code": null,
"e": 25509,
"s": 25498,
"text": "Examples: "
},
{
"code": null,
"e": 25736,
"s": 25509,
"text": "Input: K = 0, \n 5\n / \\\n 3 6\nOutput:\n 3\n \\\n 5\n \\\n 6\n\nInput: K = 1,\n 2\n / \\\n 1 3\nOutput:\n 3\n \\\n 2\n \\\n 1"
},
{
"code": null,
"e": 25747,
"s": 25736,
"text": "Approach: "
},
{
"code": null,
"e": 25938,
"s": 25747,
"text": "The key observation in the problem is that the first node of the skewed tree will be the extreme left or extreme right node of the BST for increasing order and decreasing order respectively."
},
{
"code": null,
"e": 26409,
"s": 25938,
"text": "For Increasing Order we need to do the Inorder Traversal, as the inorder traversal of a BST provides us the increasing sequence of the node values. Hence, the order of traversal at every node will be: Left node: Recurse to its left node if it exists, to get smaller value.Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node.Right node: Recurse to the right node if it exists, for larger values."
},
{
"code": null,
"e": 26679,
"s": 26409,
"text": "Left node: Recurse to its left node if it exists, to get smaller value.Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node.Right node: Recurse to the right node if it exists, for larger values."
},
{
"code": null,
"e": 26751,
"s": 26679,
"text": "Left node: Recurse to its left node if it exists, to get smaller value."
},
{
"code": null,
"e": 26880,
"s": 26751,
"text": "Root node: After the complete traversal of its left node/subtree, connect the previous node of the skewed tree to the root node."
},
{
"code": null,
"e": 26951,
"s": 26880,
"text": "Right node: Recurse to the right node if it exists, for larger values."
},
{
"code": null,
"e": 27285,
"s": 26951,
"text": "For Decreasing Order, the order of traversal at every node will be: Right node: Recurse to its right node if it exists, to get larger values.Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node.Left node: Recurse to the left node/subtree for smaller values."
},
{
"code": null,
"e": 27551,
"s": 27285,
"text": "Right node: Recurse to its right node if it exists, to get larger values.Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node.Left node: Recurse to the left node/subtree for smaller values."
},
{
"code": null,
"e": 27625,
"s": 27551,
"text": "Right node: Recurse to its right node if it exists, to get larger values."
},
{
"code": null,
"e": 27755,
"s": 27625,
"text": "Root node: After the complete traversal of its right node/subtree, connect the previous node of the skewed tree to the root node."
},
{
"code": null,
"e": 27819,
"s": 27755,
"text": "Left node: Recurse to the left node/subtree for smaller values."
},
{
"code": null,
"e": 27963,
"s": 27819,
"text": "Similarly, by keeping track of the previous node we can traverse the Binary search tree according to the order needed and form the skewed tree."
},
{
"code": null,
"e": 28015,
"s": 27963,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28021,
"s": 28015,
"text": "C++14"
},
{
"code": null,
"e": 28026,
"s": 28021,
"text": "Java"
},
{
"code": null,
"e": 28034,
"s": 28026,
"text": "Python3"
},
{
"code": null,
"e": 28037,
"s": 28034,
"text": "C#"
},
{
"code": null,
"e": 28048,
"s": 28037,
"text": "Javascript"
},
{
"code": "// C++ implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing order#include<bits/stdc++.h>using namespace std; // Class of the nodestruct Node{ int val; Node *left, *right; Node(int x) { val = x; left = right = NULL; }}; Node *prevNode = NULL;Node *headNode = NULL; // Function to to flatten the binary// search tree into a skewed tree in// increasing / decreasing ordervoid flattenBTToSkewed(Node *root, int order){ // Base Case if (!root) return; // Condition to check the order // in which the skewed tree to // maintained if (order) flattenBTToSkewed(root->right, order); else flattenBTToSkewed(root->left, order); Node *rightNode = root->right; Node *leftNode = root->left; // Condition to check if the root Node // of the skewed tree is not defined if (!headNode) { headNode = root; root->left = NULL; prevNode = root; } else { prevNode->right = root; root->left = NULL; prevNode = root; } // Similarly recurse for the left / right // subtree on the basis of the order required if (order) flattenBTToSkewed(leftNode, order); else flattenBTToSkewed(rightNode, order);} // Function to traverse the right// skewed tree using recursionvoid traverseRightSkewed(Node *root){ if (!root) return; cout << root->val << \" \"; traverseRightSkewed(root->right);} // Driver Codeint main(){ // 5 // / \\ // 3 6 Node *root =new Node(5); root->left = new Node(3); root->right = new Node(6); // Order of the Skewed tree can // be defined as follows - // For Increasing order - 0 // For Decreasing order - 1 int order = 0; flattenBTToSkewed(root, order); traverseRightSkewed(headNode);} // This code is contributed by mohit kumar 29",
"e": 29971,
"s": 28048,
"text": null
},
{
"code": "// Java implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing orderimport java.io.*; // Class of the nodeclass Node{ int val; Node left, right; // Helper function that allocates a new node // with the given data and NULL left and right // pointers. Node(int item) { val = item; left = right = null; }}class GFG{ public static Node node; static Node prevNode = null; static Node headNode = null; // Function to to flatten the binary // search tree into a skewed tree in // increasing / decreasing order static void flattenBTToSkewed(Node root, int order) { // Base Case if(root == null) { return; } // Condition to check the order // in which the skewed tree to // maintained if(order > 0) { flattenBTToSkewed(root.right, order); } else { flattenBTToSkewed(root.left, order); } Node rightNode = root.right; Node leftNode = root.left; // Condition to check if the root Node // of the skewed tree is not defined if(headNode == null) { headNode = root; root.left = null; prevNode = root; } else { prevNode.right = root; root.left = null; prevNode = root; } // Similarly recurse for the left / right // subtree on the basis of the order required if (order > 0) { flattenBTToSkewed(leftNode, order); } else { flattenBTToSkewed(rightNode, order); } } // Function to traverse the right // skewed tree using recursion static void traverseRightSkewed(Node root) { if(root == null) { return; } System.out.print(root.val + \" \"); traverseRightSkewed(root.right); } // Driver Code public static void main (String[] args) { // 5 // / \\ // 3 6 GFG tree = new GFG(); tree.node = new Node(5); tree.node.left = new Node(3); tree.node.right = new Node(6); // Order of the Skewed tree can // be defined as follows - // For Increasing order - 0 // For Decreasing order - 1 int order = 0; flattenBTToSkewed(node, order); traverseRightSkewed(headNode); }} // This code is contributed by avanitrachhadiya2155",
"e": 32569,
"s": 29971,
"text": null
},
{
"code": "# Python3 implementation to flatten# the binary search tree into a skewed# tree in increasing / decreasing order # Class of the nodeclass Node: # Constructor of node def __init__(self, val): self.val = val self.left = None self.right = None prevNode = NoneheadNode = None # Function to to flatten# the binary search tree into a skewed# tree in increasing / decreasing orderdef flattenBTToSkewed(root, order): # Base Case if not root: return # Condition to check the order # in which the skewed tree to maintained if order: flattenBTToSkewed(root.right, order) else: flattenBTToSkewed(root.left, order) global headNode; global prevNode rightNode = root.right leftNode = root.left # Condition to check if the root Node # of the skewed tree is not defined if not headNode: headNode = root root.left = None prevNode = root else: prevNode.right = root root.left = None prevNode = root # Similarly recurse for the left / right # subtree on the basis of the order required if order: flattenBTToSkewed(leftNode, order) else: flattenBTToSkewed(rightNode, order) # Function to traverse the right# skewed tree using recursiondef traverseRightSkewed(root): if not root: return print(root.val, end = \" \") traverseRightSkewed(root.right) # Driver Codeif __name__ == \"__main__\": # 5 # / \\ # 3 6 root = Node(5) root.left = Node(3) root.right = Node(6) prevNode = None headNode = None # Order of the Skewed tree can # be defined as follows - # For Increasing order - 0 # For Decreasing order - 1 order = 0 flattenBTToSkewed(root, order) traverseRightSkewed(headNode)",
"e": 34404,
"s": 32569,
"text": null
},
{
"code": "// C# implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing orderusing System; // Class of the nodeclass Node{ public int val; public Node left, right; // Helper function that allocates a new // node with the given data and NULL // left and right pointers. public Node(int item) { val = item; left = right = null; }} class GFG{ public static Node node;static Node prevNode = null;static Node headNode = null; // Function to to flatten the binary// search tree into a skewed tree in// increasing / decreasing orderstatic void flattenBTToSkewed(Node root, int order){ // Base Case if (root == null) { return; } // Condition to check the order // in which the skewed tree to // maintained if (order > 0) { flattenBTToSkewed(root.right, order); } else { flattenBTToSkewed(root.left, order); } Node rightNode = root.right; Node leftNode = root.left; // Condition to check if the root Node // of the skewed tree is not defined if (headNode == null) { headNode = root; root.left = null; prevNode = root; } else { prevNode.right = root; root.left = null; prevNode = root; } // Similarly recurse for the left / right // subtree on the basis of the order required if (order > 0) { flattenBTToSkewed(leftNode, order); } else { flattenBTToSkewed(rightNode, order); }} // Function to traverse the right// skewed tree using recursionstatic void traverseRightSkewed(Node root){ if (root == null) { return; } Console.Write(root.val + \" \"); traverseRightSkewed(root.right);} // Driver Codestatic public void Main(){ // 5 // / \\ // 3 6 GFG.node = new Node(5); GFG.node.left = new Node(3); GFG.node.right = new Node(6); // Order of the Skewed tree can // be defined as follows - // For Increasing order - 0 // For Decreasing order - 1 int order = 0; flattenBTToSkewed(node, order); traverseRightSkewed(headNode);}} // This code is contributed by rag2127",
"e": 36609,
"s": 34404,
"text": null
},
{
"code": "<script>// Javascript implementation to flatten the// binary search tree into a skewed// tree in increasing / decreasing order // Class of the nodeclass Node{ // Helper function that allocates a new node // with the given data and NULL left and right // pointers. constructor(item) { this.val = item; this.left = this.right = null; }} let node;let prevNode = null;let headNode = null; // Function to to flatten the binary // search tree into a skewed tree in // increasing / decreasing orderfunction flattenBTToSkewed(root,order){ // Base Case if(root == null) { return; } // Condition to check the order // in which the skewed tree to // maintained if(order > 0) { flattenBTToSkewed(root.right, order); } else { flattenBTToSkewed(root.left, order); } let rightNode = root.right; let leftNode = root.left; // Condition to check if the root Node // of the skewed tree is not defined if(headNode == null) { headNode = root; root.left = null; prevNode = root; } else { prevNode.right = root; root.left = null; prevNode = root; } // Similarly recurse for the left / right // subtree on the basis of the order required if (order > 0) { flattenBTToSkewed(leftNode, order); } else { flattenBTToSkewed(rightNode, order); }} // Function to traverse the right // skewed tree using recursionfunction traverseRightSkewed(root){ if(root == null) { return; } document.write(root.val + \" \"); traverseRightSkewed(root.right); } // Driver Code // 5 // / \\ // 3 6node = new Node(5);node.left = new Node(3);node.right = new Node(6); // Order of the Skewed tree can// be defined as follows -// For Increasing order - 0// For Decreasing order - 1let order = 0;flattenBTToSkewed(node, order);traverseRightSkewed(headNode); // This code is contributed by unknown2108</script>",
"e": 38827,
"s": 36609,
"text": null
},
{
"code": null,
"e": 38833,
"s": 38827,
"text": "3 5 6"
},
{
"code": null,
"e": 38850,
"s": 38835,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 38871,
"s": 38850,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 38879,
"s": 38871,
"text": "rag2127"
},
{
"code": null,
"e": 38891,
"s": 38879,
"text": "unknown2108"
},
{
"code": null,
"e": 38910,
"s": 38891,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 38920,
"s": 38910,
"text": "Recursion"
},
{
"code": null,
"e": 38925,
"s": 38920,
"text": "Tree"
},
{
"code": null,
"e": 38935,
"s": 38925,
"text": "Recursion"
},
{
"code": null,
"e": 38954,
"s": 38935,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 38959,
"s": 38954,
"text": "Tree"
},
{
"code": null,
"e": 39057,
"s": 38959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39089,
"s": 39057,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 39116,
"s": 39089,
"text": "Red Black Tree vs AVL Tree"
},
{
"code": null,
"e": 39168,
"s": 39116,
"text": "Construct BST from given preorder traversal | Set 2"
},
{
"code": null,
"e": 39202,
"s": 39168,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 39249,
"s": 39202,
"text": "Find median of BST in O(n) time and O(1) space"
},
{
"code": null,
"e": 39309,
"s": 39249,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 39394,
"s": 39309,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 39404,
"s": 39394,
"text": "Recursion"
},
{
"code": null,
"e": 39431,
"s": 39404,
"text": "Program for Tower of Hanoi"
}
] |
R - Multiple Regression
|
Multiple regression is an extension of linear regression into relationship between more than two variables. In simple linear relation we have one predictor and one response variable, but in multiple regression we have more than one predictor variable and one response variable.
The general mathematical equation for multiple regression is −
y = a + b1x1 + b2x2 +...bnxn
Following is the description of the parameters used −
y is the response variable.
y is the response variable.
a, b1, b2...bn are the coefficients.
a, b1, b2...bn are the coefficients.
x1, x2, ...xn are the predictor variables.
x1, x2, ...xn are the predictor variables.
We create the regression model using the lm() function in R. The model determines the value of the coefficients using the input data. Next we can predict the value of the response variable for a given set of predictor variables using these coefficients.
This function creates the relationship model between the predictor and the response variable.
The basic syntax for lm() function in multiple regression is −
lm(y ~ x1+x2+x3...,data)
Following is the description of the parameters used −
formula is a symbol presenting the relation between the response variable and predictor variables.
formula is a symbol presenting the relation between the response variable and predictor variables.
data is the vector on which the formula will be applied.
data is the vector on which the formula will be applied.
Consider the data set "mtcars" available in the R environment. It gives a comparison between different car models in terms of mileage per gallon (mpg), cylinder displacement("disp"), horse power("hp"), weight of the car("wt") and some more parameters.
The goal of the model is to establish the relationship between "mpg" as a response variable with "disp","hp" and "wt" as predictor variables. We create a subset of these variables from the mtcars data set for this purpose.
input <- mtcars[,c("mpg","disp","hp","wt")]
print(head(input))
When we execute the above code, it produces the following result −
mpg disp hp wt
Mazda RX4 21.0 160 110 2.620
Mazda RX4 Wag 21.0 160 110 2.875
Datsun 710 22.8 108 93 2.320
Hornet 4 Drive 21.4 258 110 3.215
Hornet Sportabout 18.7 360 175 3.440
Valiant 18.1 225 105 3.460
input <- mtcars[,c("mpg","disp","hp","wt")]
# Create the relationship model.
model <- lm(mpg~disp+hp+wt, data = input)
# Show the model.
print(model)
# Get the Intercept and coefficients as vector elements.
cat("# # # # The Coefficient Values # # # ","\n")
a <- coef(model)[1]
print(a)
Xdisp <- coef(model)[2]
Xhp <- coef(model)[3]
Xwt <- coef(model)[4]
print(Xdisp)
print(Xhp)
print(Xwt)
When we execute the above code, it produces the following result −
Call:
lm(formula = mpg ~ disp + hp + wt, data = input)
Coefficients:
(Intercept) disp hp wt
37.105505 -0.000937 -0.031157 -3.800891
# # # # The Coefficient Values # # #
(Intercept)
37.10551
disp
-0.0009370091
hp
-0.03115655
wt
-3.800891
Based on the above intercept and coefficient values, we create the mathematical equation.
Y = a+Xdisp.x1+Xhp.x2+Xwt.x3
or
Y = 37.15+(-0.000937)*x1+(-0.0311)*x2+(-3.8008)*x3
We can use the regression equation created above to predict the mileage when a new set of values for displacement, horse power and weight is provided.
For a car with disp = 221, hp = 102 and wt = 2.91 the predicted mileage is −
Y = 37.15+(-0.000937)*221+(-0.0311)*102+(-3.8008)*2.91 = 22.7104
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2680,
"s": 2402,
"text": "Multiple regression is an extension of linear regression into relationship between more than two variables. In simple linear relation we have one predictor and one response variable, but in multiple regression we have more than one predictor variable and one response variable."
},
{
"code": null,
"e": 2743,
"s": 2680,
"text": "The general mathematical equation for multiple regression is −"
},
{
"code": null,
"e": 2773,
"s": 2743,
"text": "y = a + b1x1 + b2x2 +...bnxn\n"
},
{
"code": null,
"e": 2827,
"s": 2773,
"text": "Following is the description of the parameters used −"
},
{
"code": null,
"e": 2855,
"s": 2827,
"text": "y is the response variable."
},
{
"code": null,
"e": 2883,
"s": 2855,
"text": "y is the response variable."
},
{
"code": null,
"e": 2920,
"s": 2883,
"text": "a, b1, b2...bn are the coefficients."
},
{
"code": null,
"e": 2957,
"s": 2920,
"text": "a, b1, b2...bn are the coefficients."
},
{
"code": null,
"e": 3000,
"s": 2957,
"text": "x1, x2, ...xn are the predictor variables."
},
{
"code": null,
"e": 3043,
"s": 3000,
"text": "x1, x2, ...xn are the predictor variables."
},
{
"code": null,
"e": 3297,
"s": 3043,
"text": "We create the regression model using the lm() function in R. The model determines the value of the coefficients using the input data. Next we can predict the value of the response variable for a given set of predictor variables using these coefficients."
},
{
"code": null,
"e": 3391,
"s": 3297,
"text": "This function creates the relationship model between the predictor and the response variable."
},
{
"code": null,
"e": 3454,
"s": 3391,
"text": "The basic syntax for lm() function in multiple regression is −"
},
{
"code": null,
"e": 3480,
"s": 3454,
"text": "lm(y ~ x1+x2+x3...,data)\n"
},
{
"code": null,
"e": 3534,
"s": 3480,
"text": "Following is the description of the parameters used −"
},
{
"code": null,
"e": 3633,
"s": 3534,
"text": "formula is a symbol presenting the relation between the response variable and predictor variables."
},
{
"code": null,
"e": 3732,
"s": 3633,
"text": "formula is a symbol presenting the relation between the response variable and predictor variables."
},
{
"code": null,
"e": 3789,
"s": 3732,
"text": "data is the vector on which the formula will be applied."
},
{
"code": null,
"e": 3846,
"s": 3789,
"text": "data is the vector on which the formula will be applied."
},
{
"code": null,
"e": 4098,
"s": 3846,
"text": "Consider the data set \"mtcars\" available in the R environment. It gives a comparison between different car models in terms of mileage per gallon (mpg), cylinder displacement(\"disp\"), horse power(\"hp\"), weight of the car(\"wt\") and some more parameters."
},
{
"code": null,
"e": 4321,
"s": 4098,
"text": "The goal of the model is to establish the relationship between \"mpg\" as a response variable with \"disp\",\"hp\" and \"wt\" as predictor variables. We create a subset of these variables from the mtcars data set for this purpose."
},
{
"code": null,
"e": 4384,
"s": 4321,
"text": "input <- mtcars[,c(\"mpg\",\"disp\",\"hp\",\"wt\")]\nprint(head(input))"
},
{
"code": null,
"e": 4451,
"s": 4384,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 4757,
"s": 4451,
"text": " mpg disp hp wt\nMazda RX4 21.0 160 110 2.620\nMazda RX4 Wag 21.0 160 110 2.875\nDatsun 710 22.8 108 93 2.320\nHornet 4 Drive 21.4 258 110 3.215\nHornet Sportabout 18.7 360 175 3.440\nValiant 18.1 225 105 3.460\n"
},
{
"code": null,
"e": 5152,
"s": 4757,
"text": "input <- mtcars[,c(\"mpg\",\"disp\",\"hp\",\"wt\")]\n\n# Create the relationship model.\nmodel <- lm(mpg~disp+hp+wt, data = input)\n\n# Show the model.\nprint(model)\n\n# Get the Intercept and coefficients as vector elements.\ncat(\"# # # # The Coefficient Values # # # \",\"\\n\")\n\na <- coef(model)[1]\nprint(a)\n\nXdisp <- coef(model)[2]\nXhp <- coef(model)[3]\nXwt <- coef(model)[4]\n\nprint(Xdisp)\nprint(Xhp)\nprint(Xwt)"
},
{
"code": null,
"e": 5219,
"s": 5152,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 5545,
"s": 5219,
"text": "Call:\nlm(formula = mpg ~ disp + hp + wt, data = input)\n\nCoefficients:\n(Intercept) disp hp wt \n 37.105505 -0.000937 -0.031157 -3.800891 \n\n# # # # The Coefficient Values # # # \n(Intercept) \n 37.10551 \n disp \n-0.0009370091 \n hp \n-0.03115655 \n wt \n-3.800891 \n"
},
{
"code": null,
"e": 5635,
"s": 5545,
"text": "Based on the above intercept and coefficient values, we create the mathematical equation."
},
{
"code": null,
"e": 5719,
"s": 5635,
"text": "Y = a+Xdisp.x1+Xhp.x2+Xwt.x3\nor\nY = 37.15+(-0.000937)*x1+(-0.0311)*x2+(-3.8008)*x3\n"
},
{
"code": null,
"e": 5870,
"s": 5719,
"text": "We can use the regression equation created above to predict the mileage when a new set of values for displacement, horse power and weight is provided."
},
{
"code": null,
"e": 5947,
"s": 5870,
"text": "For a car with disp = 221, hp = 102 and wt = 2.91 the predicted mileage is −"
},
{
"code": null,
"e": 6013,
"s": 5947,
"text": "Y = 37.15+(-0.000937)*221+(-0.0311)*102+(-3.8008)*2.91 = 22.7104\n"
},
{
"code": null,
"e": 6046,
"s": 6013,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6061,
"s": 6046,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6096,
"s": 6061,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6111,
"s": 6096,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6146,
"s": 6111,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6161,
"s": 6146,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6194,
"s": 6161,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6208,
"s": 6194,
"text": " Asif Hussain"
},
{
"code": null,
"e": 6243,
"s": 6208,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6258,
"s": 6243,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6293,
"s": 6258,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6307,
"s": 6293,
"text": " Asif Hussain"
},
{
"code": null,
"e": 6314,
"s": 6307,
"text": " Print"
},
{
"code": null,
"e": 6325,
"s": 6314,
"text": " Add Notes"
}
] |
Convert Iterator to Iterable in Java - GeeksforGeeks
|
10 Nov, 2021
Given an Iterator, the task is to convert it into Iterables in Java.
Examples:
Input: Iterator = {1, 2, 3, 4, 5}
Output: {1, 2, 3, 4, 5}
Input: Iterator = {'G', 'e', 'e', 'k', 's'}
Output: {'G', 'e', 'e', 'k', 's'}
Below are the various ways to do so:
By overriding the abstract method Iterable.iterator():Get the Iterator.Override the Iterable.iterator() method and get the iterable.Return the Iterable.Below is the implementation of the above approach:// Java program to get a Iterable// from a given Iterator import java.util.*; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}Output:1
2
3
4
5
Get the Iterator.Override the Iterable.iterator() method and get the iterable.Return the Iterable.
Get the Iterator.
Override the Iterable.iterator() method and get the iterable.
Return the Iterable.
Below is the implementation of the above approach:
// Java program to get a Iterable// from a given Iterator import java.util.*; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}
1
2
3
4
5
Using Java 8 lambda expression:Get the Iterator.Convert the iterator to iterable using Lambda Expression.Return the Iterable.Below is the implementation of the above approach:// Java program to get an Iterable// from a given Iterator import java.util.*; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return () -> iterator; } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}Output:1
2
3
4
5
Get the Iterator.Convert the iterator to iterable using Lambda Expression.Return the Iterable.
Get the Iterator.
Convert the iterator to iterable using Lambda Expression.
Return the Iterable.
Below is the implementation of the above approach:
// Java program to get an Iterable// from a given Iterator import java.util.*; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return () -> iterator; } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}
1
2
3
4
5
Using Spliterators:Get the Iterator.Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.Convert the Spliterator into Sequential Stream using StreamSupport.stream() method.Collect the elements of the Sequential Stream as an Iterable using collect() method.Return the Iterable.Below is the implementation of the above approach:// Java program to get a Iterable// from a given Iterator import java.util.*;import java.util.stream.Collectors;import java.util.stream.StreamSupport; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return StreamSupport // Convert the iterator into a Spliterator // and then into a sequential stream .stream(Spliterators.spliteratorUnknownSize(iterator, 0), false) // Convert the stream to an iterable .collect(Collectors.toList()); } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}Output:1
2
3
4
5
Get the Iterator.Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.Convert the Spliterator into Sequential Stream using StreamSupport.stream() method.Collect the elements of the Sequential Stream as an Iterable using collect() method.Return the Iterable.
Get the Iterator.
Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.
Convert the Spliterator into Sequential Stream using StreamSupport.stream() method.
Collect the elements of the Sequential Stream as an Iterable using collect() method.
Return the Iterable.
Below is the implementation of the above approach:
// Java program to get a Iterable// from a given Iterator import java.util.*;import java.util.stream.Collectors;import java.util.stream.StreamSupport; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return StreamSupport // Convert the iterator into a Spliterator // and then into a sequential stream .stream(Spliterators.spliteratorUnknownSize(iterator, 0), false) // Convert the stream to an iterable .collect(Collectors.toList()); } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}
1
2
3
4
5
sumitgumber28
Java - util package
Java-Iterable
Java-Iterator
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 24017,
"s": 23948,
"text": "Given an Iterator, the task is to convert it into Iterables in Java."
},
{
"code": null,
"e": 24027,
"s": 24017,
"text": "Examples:"
},
{
"code": null,
"e": 24165,
"s": 24027,
"text": "Input: Iterator = {1, 2, 3, 4, 5}\nOutput: {1, 2, 3, 4, 5}\n\nInput: Iterator = {'G', 'e', 'e', 'k', 's'}\nOutput: {'G', 'e', 'e', 'k', 's'}\n"
},
{
"code": null,
"e": 24202,
"s": 24165,
"text": "Below are the various ways to do so:"
},
{
"code": null,
"e": 25244,
"s": 24202,
"text": "By overriding the abstract method Iterable.iterator():Get the Iterator.Override the Iterable.iterator() method and get the iterable.Return the Iterable.Below is the implementation of the above approach:// Java program to get a Iterable// from a given Iterator import java.util.*; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}Output:1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 25343,
"s": 25244,
"text": "Get the Iterator.Override the Iterable.iterator() method and get the iterable.Return the Iterable."
},
{
"code": null,
"e": 25361,
"s": 25343,
"text": "Get the Iterator."
},
{
"code": null,
"e": 25423,
"s": 25361,
"text": "Override the Iterable.iterator() method and get the iterable."
},
{
"code": null,
"e": 25444,
"s": 25423,
"text": "Return the Iterable."
},
{
"code": null,
"e": 25495,
"s": 25444,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a Iterable// from a given Iterator import java.util.*; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}",
"e": 26318,
"s": 25495,
"text": null
},
{
"code": null,
"e": 26329,
"s": 26318,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 27211,
"s": 26329,
"text": "Using Java 8 lambda expression:Get the Iterator.Convert the iterator to iterable using Lambda Expression.Return the Iterable.Below is the implementation of the above approach:// Java program to get an Iterable// from a given Iterator import java.util.*; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return () -> iterator; } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}Output:1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 27306,
"s": 27211,
"text": "Get the Iterator.Convert the iterator to iterable using Lambda Expression.Return the Iterable."
},
{
"code": null,
"e": 27324,
"s": 27306,
"text": "Get the Iterator."
},
{
"code": null,
"e": 27382,
"s": 27324,
"text": "Convert the iterator to iterable using Lambda Expression."
},
{
"code": null,
"e": 27403,
"s": 27382,
"text": "Return the Iterable."
},
{
"code": null,
"e": 27454,
"s": 27403,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get an Iterable// from a given Iterator import java.util.*; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return () -> iterator; } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}",
"e": 28144,
"s": 27454,
"text": null
},
{
"code": null,
"e": 28155,
"s": 28144,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 29583,
"s": 28155,
"text": "Using Spliterators:Get the Iterator.Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.Convert the Spliterator into Sequential Stream using StreamSupport.stream() method.Collect the elements of the Sequential Stream as an Iterable using collect() method.Return the Iterable.Below is the implementation of the above approach:// Java program to get a Iterable// from a given Iterator import java.util.*;import java.util.stream.Collectors;import java.util.stream.StreamSupport; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return StreamSupport // Convert the iterator into a Spliterator // and then into a sequential stream .stream(Spliterators.spliteratorUnknownSize(iterator, 0), false) // Convert the stream to an iterable .collect(Collectors.toList()); } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}Output:1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 29875,
"s": 29583,
"text": "Get the Iterator.Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.Convert the Spliterator into Sequential Stream using StreamSupport.stream() method.Collect the elements of the Sequential Stream as an Iterable using collect() method.Return the Iterable."
},
{
"code": null,
"e": 29893,
"s": 29875,
"text": "Get the Iterator."
},
{
"code": null,
"e": 29981,
"s": 29893,
"text": "Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method."
},
{
"code": null,
"e": 30065,
"s": 29981,
"text": "Convert the Spliterator into Sequential Stream using StreamSupport.stream() method."
},
{
"code": null,
"e": 30150,
"s": 30065,
"text": "Collect the elements of the Sequential Stream as an Iterable using collect() method."
},
{
"code": null,
"e": 30171,
"s": 30150,
"text": "Return the Iterable."
},
{
"code": null,
"e": 30222,
"s": 30171,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a Iterable// from a given Iterator import java.util.*;import java.util.stream.Collectors;import java.util.stream.StreamSupport; class GFG { // Function to get the Spliterator public static <T> Iterable<T> getIterableFromIterator(Iterator<T> iterator) { return StreamSupport // Convert the iterator into a Spliterator // and then into a sequential stream .stream(Spliterators.spliteratorUnknownSize(iterator, 0), false) // Convert the stream to an iterable .collect(Collectors.toList()); } // Driver code public static void main(String[] args) { // Get the Iterator Iterator<Integer> iterator = Arrays.asList(1, 2, 3, 4, 5) .iterator(); // Get the Iterable from the Iterator Iterable<Integer> iterable = getIterableFromIterator(iterator); // Print the elements of Iterable iterable.forEach(System.out::println); }}",
"e": 31273,
"s": 30222,
"text": null
},
{
"code": null,
"e": 31284,
"s": 31273,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 31298,
"s": 31284,
"text": "sumitgumber28"
},
{
"code": null,
"e": 31318,
"s": 31298,
"text": "Java - util package"
},
{
"code": null,
"e": 31332,
"s": 31318,
"text": "Java-Iterable"
},
{
"code": null,
"e": 31346,
"s": 31332,
"text": "Java-Iterator"
},
{
"code": null,
"e": 31351,
"s": 31346,
"text": "Java"
},
{
"code": null,
"e": 31356,
"s": 31351,
"text": "Java"
},
{
"code": null,
"e": 31454,
"s": 31356,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31469,
"s": 31454,
"text": "Stream In Java"
},
{
"code": null,
"e": 31515,
"s": 31469,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31536,
"s": 31515,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31555,
"s": 31536,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31585,
"s": 31555,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31602,
"s": 31585,
"text": "Generics in Java"
},
{
"code": null,
"e": 31645,
"s": 31602,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31674,
"s": 31645,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 31695,
"s": 31674,
"text": "Introduction to Java"
}
] |
How to Easily Convert a Python Script to an Executable File (.exe) | by Frank Andrade | Towards Data Science
|
Although running a Python script using the terminal or your favorite text editor is straightforward, there are some situations in which you will prefer to hide all the code written in the script (.py) inside an executable file (.exe).
Maybe you need to send the script to someone who doesn’t code at all or you might need to schedule a job that runs a .exe at a specific time on your computer. Whatever the situation, in this guide, I will show you 2 ways to create an executable file. The first (auto-py-to-exe) has a friendly interface that will help beginners to easily create executables, while the second (PyInstaller) offers a straightforward way to create executables through the terminal.
Table of Contents1. Making an Executable file with auto-py-to-exe - Installing with pip - Running auto-py-to-exe - Step 1: Add the script location - Step 2: Choosing “One Directory” or “One File” - Step 3. Choosing “Console Based” or “Window Based” - Step 4: Advanced option(e.g. output directory, additional import) - Step 5: Convert the file2. Making an Executable file with PyInstaller
The first option offers a nice GUI (graphical user interface) that takes care of all the stuff necessary to convert your Python script into an executable file.
By the way, you can also watch my YouTube video to learn how to convert a .py to .exe, in case you prefer watching the steps below rather than reading them.
To install the last version of auto-py-to-exe, just open up a terminal and run the following command.
pip install auto-py-to-exe
Note: Make sure that the working environment in which you’re installing auto-py-to-exe contains all the libraries that your script needs to run.
Once you install auto-py-to-exe, making an executable file is as easy as writing the following command.
auto-py-to-exe
After running the command, the following GUI application will open.
I will walk you through each option to properly create an executable file.
Browse the script you wish to convert and add it to the “Script Location” field. In this example, I’m going to choose a script that automates Excel reports (you can find my guide to automate Excel in the link below)
towardsdatascience.com
Feel free to choose any script you want. However, if your script needs to read a path make sure that you use absolute paths since relative paths won’t behave as you might expect with executable files. If necessary, include the following line of code below to know where the executable file is located and make the necessary changes to your script so you read/export files on the right directory.
application_path = os.path.dirname(sys.executable)
Now we have to choose whether we want to create “one directory” or “one file.” The first creates a directory with all the dependencies your script needs to run (including the executable file), while the second creates only a single executable file.
For this example, I’ll choose the “one file” option.
Now it’s time to choose whether the console will be displayed or not. If you choose “Console Based,” the console will open after running the executable file, which is recommended if your script generates console-based outputs. However, if you don’t want to show the console outputs when running the executable file, choose “Window Based”
My script needs the name of the Excel spreadsheet to be introduced as input in order to create my Excel report, so I’m going to choose “Console Based.”
medium.com
You can add an icon, add files that your script needs to run, and more! However, for this example, I’ll only modify the path where the executable file will be exported. To do so, click on the “Setting” option and browse the output directory you wish.
Note: If you see an error like this “ModuleFoundNotError: Not module named ‘ name_of_module’” after double-clicking on the executable file created, you’ll have to repeat from step 1 again, but now in the “Advanced” option write the module name is missing inside the “hidden-import” field.
To convert the .py file to .exe just click the blue button you see below.
Something really important that auto-py-to-exe shows above the convert button is the code that pyinstaller (the main library and second option in this guide to make .exe files) needs to create an executable file behind that fancy GUI you see on the screen.
Once the process is finished the executable file should be located in the output directory you set in step 4!
This option fits better for those who prefer to quickly create an executable file running a command on the terminal.
If you’re used to working with the terminal, then the PyInstaller library will be the best option. To install PyInstaller follow these steps.
Step 1: Open up a terminal and run pip install pyinstaller
Step 2: Using the terminal, go to the directory where your script is located (use the cd command)
Step 3: Once you‘re in the right directory, write a command with the following syntaxpyinstaller --onefile name_of_script.py in the terminal to make the script executable.
The command used in step 3 is similar to the code shown in the step 5 picture for the auto-py-to-exe option. You can play a little bit with the GUI offered by auto-py-to-exe to get used to the many options you can add to this command.
After running the command, you should see a message that says “completed successfully.” In the directory where your script is located, a folder named “dist” should have been created. Inside the folder, you’ll find the standalone executable!
Congratulations! Now your Python script has been converted to an executable file. In case you want to schedule when this file will run on your computer check this guide.
towardsdatascience.com
Below you can find some guides I made on libraries used in data science (Matplotlib/Seaborn, Pandas, and Scikit-Learn).
A Pandas Guide for Excel Users
How to Make Beautiful Visualizations with Matplotlib and Seaborn
A Simple Guide to Scikit-Learn — Build Your First Machine Learning Model in Python
Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)
|
[
{
"code": null,
"e": 407,
"s": 172,
"text": "Although running a Python script using the terminal or your favorite text editor is straightforward, there are some situations in which you will prefer to hide all the code written in the script (.py) inside an executable file (.exe)."
},
{
"code": null,
"e": 869,
"s": 407,
"text": "Maybe you need to send the script to someone who doesn’t code at all or you might need to schedule a job that runs a .exe at a specific time on your computer. Whatever the situation, in this guide, I will show you 2 ways to create an executable file. The first (auto-py-to-exe) has a friendly interface that will help beginners to easily create executables, while the second (PyInstaller) offers a straightforward way to create executables through the terminal."
},
{
"code": null,
"e": 1258,
"s": 869,
"text": "Table of Contents1. Making an Executable file with auto-py-to-exe - Installing with pip - Running auto-py-to-exe - Step 1: Add the script location - Step 2: Choosing “One Directory” or “One File” - Step 3. Choosing “Console Based” or “Window Based” - Step 4: Advanced option(e.g. output directory, additional import) - Step 5: Convert the file2. Making an Executable file with PyInstaller"
},
{
"code": null,
"e": 1418,
"s": 1258,
"text": "The first option offers a nice GUI (graphical user interface) that takes care of all the stuff necessary to convert your Python script into an executable file."
},
{
"code": null,
"e": 1575,
"s": 1418,
"text": "By the way, you can also watch my YouTube video to learn how to convert a .py to .exe, in case you prefer watching the steps below rather than reading them."
},
{
"code": null,
"e": 1677,
"s": 1575,
"text": "To install the last version of auto-py-to-exe, just open up a terminal and run the following command."
},
{
"code": null,
"e": 1704,
"s": 1677,
"text": "pip install auto-py-to-exe"
},
{
"code": null,
"e": 1849,
"s": 1704,
"text": "Note: Make sure that the working environment in which you’re installing auto-py-to-exe contains all the libraries that your script needs to run."
},
{
"code": null,
"e": 1953,
"s": 1849,
"text": "Once you install auto-py-to-exe, making an executable file is as easy as writing the following command."
},
{
"code": null,
"e": 1968,
"s": 1953,
"text": "auto-py-to-exe"
},
{
"code": null,
"e": 2036,
"s": 1968,
"text": "After running the command, the following GUI application will open."
},
{
"code": null,
"e": 2111,
"s": 2036,
"text": "I will walk you through each option to properly create an executable file."
},
{
"code": null,
"e": 2327,
"s": 2111,
"text": "Browse the script you wish to convert and add it to the “Script Location” field. In this example, I’m going to choose a script that automates Excel reports (you can find my guide to automate Excel in the link below)"
},
{
"code": null,
"e": 2350,
"s": 2327,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2746,
"s": 2350,
"text": "Feel free to choose any script you want. However, if your script needs to read a path make sure that you use absolute paths since relative paths won’t behave as you might expect with executable files. If necessary, include the following line of code below to know where the executable file is located and make the necessary changes to your script so you read/export files on the right directory."
},
{
"code": null,
"e": 2797,
"s": 2746,
"text": "application_path = os.path.dirname(sys.executable)"
},
{
"code": null,
"e": 3046,
"s": 2797,
"text": "Now we have to choose whether we want to create “one directory” or “one file.” The first creates a directory with all the dependencies your script needs to run (including the executable file), while the second creates only a single executable file."
},
{
"code": null,
"e": 3099,
"s": 3046,
"text": "For this example, I’ll choose the “one file” option."
},
{
"code": null,
"e": 3437,
"s": 3099,
"text": "Now it’s time to choose whether the console will be displayed or not. If you choose “Console Based,” the console will open after running the executable file, which is recommended if your script generates console-based outputs. However, if you don’t want to show the console outputs when running the executable file, choose “Window Based”"
},
{
"code": null,
"e": 3589,
"s": 3437,
"text": "My script needs the name of the Excel spreadsheet to be introduced as input in order to create my Excel report, so I’m going to choose “Console Based.”"
},
{
"code": null,
"e": 3600,
"s": 3589,
"text": "medium.com"
},
{
"code": null,
"e": 3851,
"s": 3600,
"text": "You can add an icon, add files that your script needs to run, and more! However, for this example, I’ll only modify the path where the executable file will be exported. To do so, click on the “Setting” option and browse the output directory you wish."
},
{
"code": null,
"e": 4140,
"s": 3851,
"text": "Note: If you see an error like this “ModuleFoundNotError: Not module named ‘ name_of_module’” after double-clicking on the executable file created, you’ll have to repeat from step 1 again, but now in the “Advanced” option write the module name is missing inside the “hidden-import” field."
},
{
"code": null,
"e": 4214,
"s": 4140,
"text": "To convert the .py file to .exe just click the blue button you see below."
},
{
"code": null,
"e": 4471,
"s": 4214,
"text": "Something really important that auto-py-to-exe shows above the convert button is the code that pyinstaller (the main library and second option in this guide to make .exe files) needs to create an executable file behind that fancy GUI you see on the screen."
},
{
"code": null,
"e": 4581,
"s": 4471,
"text": "Once the process is finished the executable file should be located in the output directory you set in step 4!"
},
{
"code": null,
"e": 4698,
"s": 4581,
"text": "This option fits better for those who prefer to quickly create an executable file running a command on the terminal."
},
{
"code": null,
"e": 4840,
"s": 4698,
"text": "If you’re used to working with the terminal, then the PyInstaller library will be the best option. To install PyInstaller follow these steps."
},
{
"code": null,
"e": 4899,
"s": 4840,
"text": "Step 1: Open up a terminal and run pip install pyinstaller"
},
{
"code": null,
"e": 4997,
"s": 4899,
"text": "Step 2: Using the terminal, go to the directory where your script is located (use the cd command)"
},
{
"code": null,
"e": 5169,
"s": 4997,
"text": "Step 3: Once you‘re in the right directory, write a command with the following syntaxpyinstaller --onefile name_of_script.py in the terminal to make the script executable."
},
{
"code": null,
"e": 5404,
"s": 5169,
"text": "The command used in step 3 is similar to the code shown in the step 5 picture for the auto-py-to-exe option. You can play a little bit with the GUI offered by auto-py-to-exe to get used to the many options you can add to this command."
},
{
"code": null,
"e": 5645,
"s": 5404,
"text": "After running the command, you should see a message that says “completed successfully.” In the directory where your script is located, a folder named “dist” should have been created. Inside the folder, you’ll find the standalone executable!"
},
{
"code": null,
"e": 5815,
"s": 5645,
"text": "Congratulations! Now your Python script has been converted to an executable file. In case you want to schedule when this file will run on your computer check this guide."
},
{
"code": null,
"e": 5838,
"s": 5815,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5958,
"s": 5838,
"text": "Below you can find some guides I made on libraries used in data science (Matplotlib/Seaborn, Pandas, and Scikit-Learn)."
},
{
"code": null,
"e": 5989,
"s": 5958,
"text": "A Pandas Guide for Excel Users"
},
{
"code": null,
"e": 6054,
"s": 5989,
"text": "How to Make Beautiful Visualizations with Matplotlib and Seaborn"
},
{
"code": null,
"e": 6137,
"s": 6054,
"text": "A Simple Guide to Scikit-Learn — Build Your First Machine Learning Model in Python"
}
] |
turtle.tracer() function in Python - GeeksforGeeks
|
06 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to turn turtle animation on or off and set a delay for update drawings.
Syntax : turtle.tracer(n=None, delay=None)
Parameters:
n: If n is given, only each n-th regular screen update is really performed.
delay: sets delay value
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle # check default valueprint(turtle.tracer())
Output :
1
Example 2 :
Python3
# importing packageimport turtle # loop for motion with# default tracer as 1for i in range(20): turtle.forward(1+1*i) turtle.right(45) # set tracer values as (2,0)# 2 -> for screen update# 0 -> delayturtle.tracer(n=2, delay=0) # loop for motion with# above tracer valuesfor i in range(20, 40): turtle.forward(1+1*i) turtle.right(45) # set tracer values as (1,50)# 1 -> for screen update# 50 -> delayturtle.tracer(n=1, delay=50) # loop for motion with# above tracer valuesfor i in range(40, 60): turtle.forward(1+1*i) turtle.right(45)
Output :
Python-turtle
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
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24197,
"s": 24169,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 24414,
"s": 24197,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 24508,
"s": 24414,
"text": "This function is used to turn turtle animation on or off and set a delay for update drawings."
},
{
"code": null,
"e": 24551,
"s": 24508,
"text": "Syntax : turtle.tracer(n=None, delay=None)"
},
{
"code": null,
"e": 24563,
"s": 24551,
"text": "Parameters:"
},
{
"code": null,
"e": 24639,
"s": 24563,
"text": "n: If n is given, only each n-th regular screen update is really performed."
},
{
"code": null,
"e": 24663,
"s": 24639,
"text": "delay: sets delay value"
},
{
"code": null,
"e": 24732,
"s": 24663,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 24744,
"s": 24732,
"text": "Example 1 :"
},
{
"code": null,
"e": 24752,
"s": 24744,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # check default valueprint(turtle.tracer())",
"e": 24830,
"s": 24752,
"text": null
},
{
"code": null,
"e": 24839,
"s": 24830,
"text": "Output :"
},
{
"code": null,
"e": 24842,
"s": 24839,
"text": "1\n"
},
{
"code": null,
"e": 24854,
"s": 24842,
"text": "Example 2 :"
},
{
"code": null,
"e": 24862,
"s": 24854,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # loop for motion with# default tracer as 1for i in range(20): turtle.forward(1+1*i) turtle.right(45) # set tracer values as (2,0)# 2 -> for screen update# 0 -> delayturtle.tracer(n=2, delay=0) # loop for motion with# above tracer valuesfor i in range(20, 40): turtle.forward(1+1*i) turtle.right(45) # set tracer values as (1,50)# 1 -> for screen update# 50 -> delayturtle.tracer(n=1, delay=50) # loop for motion with# above tracer valuesfor i in range(40, 60): turtle.forward(1+1*i) turtle.right(45)",
"e": 25419,
"s": 24862,
"text": null
},
{
"code": null,
"e": 25428,
"s": 25419,
"text": "Output :"
},
{
"code": null,
"e": 25442,
"s": 25428,
"text": "Python-turtle"
},
{
"code": null,
"e": 25449,
"s": 25442,
"text": "Python"
},
{
"code": null,
"e": 25547,
"s": 25449,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25556,
"s": 25547,
"text": "Comments"
},
{
"code": null,
"e": 25569,
"s": 25556,
"text": "Old Comments"
},
{
"code": null,
"e": 25587,
"s": 25569,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25622,
"s": 25587,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25644,
"s": 25622,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25676,
"s": 25644,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25706,
"s": 25676,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25748,
"s": 25706,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25791,
"s": 25748,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 25817,
"s": 25791,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25861,
"s": 25817,
"text": "Reading and Writing to text files in Python"
}
] |
How to convert excel content into DataFrame in R ? - GeeksforGeeks
|
17 Apr, 2021
R Programming Language allows us to read and write data into various files like CSV, Excel, XML, etc. In this article, we are going to discuss how to convert excel content into DataFrame in R Programming. To read an excel file itself, read.xlsx() function from xlsx is used.
This module is not built into R but it can be installed and imported explicitly. Open the R console and type the command given below to install xlsx package.
install.packages(“xlsx”)
read_xlsx() can be used in the following way:
Syntax: read.xlsx(“Excel File Path”, sheetName = “sheet name”, ...)
Parameters: it is necessary to give the Excel file path and sheetName as argument in read.xlsx() function but many other parameters can be used by this function such as colNames, rowNames, skipEmptyRows, skipEmptyCols, rows, cols, etc. for doing some extra modifications. Here we used colIndex as parameter for getting only column that we want. here we give 1 as a value of colIndex parameter for getting first column of Excel file.
File in use:
First, we import xlsx package by using the library() function then give the full path of the Excel file to excel_path named variable. To create a dataframe keep extracting columns from the file and combine them into one data frame once done.
Program:
R
library(xlsx) excel_path <- "excelContent.xlsx" id <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 1)Name <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 2)Age <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 3) DataFrame <- data.frame(id, Name, Age)
Output:
DataFrame created from excel content
Picked
R-Excel
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
How to change the order of bars in bar chart in R ?
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n17 Apr, 2021"
},
{
"code": null,
"e": 25126,
"s": 24851,
"text": "R Programming Language allows us to read and write data into various files like CSV, Excel, XML, etc. In this article, we are going to discuss how to convert excel content into DataFrame in R Programming. To read an excel file itself, read.xlsx() function from xlsx is used."
},
{
"code": null,
"e": 25285,
"s": 25126,
"text": "This module is not built into R but it can be installed and imported explicitly. Open the R console and type the command given below to install xlsx package."
},
{
"code": null,
"e": 25310,
"s": 25285,
"text": "install.packages(“xlsx”)"
},
{
"code": null,
"e": 25356,
"s": 25310,
"text": "read_xlsx() can be used in the following way:"
},
{
"code": null,
"e": 25424,
"s": 25356,
"text": "Syntax: read.xlsx(“Excel File Path”, sheetName = “sheet name”, ...)"
},
{
"code": null,
"e": 25858,
"s": 25424,
"text": "Parameters: it is necessary to give the Excel file path and sheetName as argument in read.xlsx() function but many other parameters can be used by this function such as colNames, rowNames, skipEmptyRows, skipEmptyCols, rows, cols, etc. for doing some extra modifications. Here we used colIndex as parameter for getting only column that we want. here we give 1 as a value of colIndex parameter for getting first column of Excel file. "
},
{
"code": null,
"e": 25871,
"s": 25858,
"text": "File in use:"
},
{
"code": null,
"e": 26113,
"s": 25871,
"text": "First, we import xlsx package by using the library() function then give the full path of the Excel file to excel_path named variable. To create a dataframe keep extracting columns from the file and combine them into one data frame once done."
},
{
"code": null,
"e": 26122,
"s": 26113,
"text": "Program:"
},
{
"code": null,
"e": 26124,
"s": 26122,
"text": "R"
},
{
"code": "library(xlsx) excel_path <- \"excelContent.xlsx\" id <- read.xlsx(excel_path, sheetName = \"ageData\", colIndex = 1)Name <- read.xlsx(excel_path, sheetName = \"ageData\", colIndex = 2)Age <- read.xlsx(excel_path, sheetName = \"ageData\", colIndex = 3) DataFrame <- data.frame(id, Name, Age)",
"e": 26412,
"s": 26124,
"text": null
},
{
"code": null,
"e": 26421,
"s": 26412,
"text": "Output: "
},
{
"code": null,
"e": 26458,
"s": 26421,
"text": "DataFrame created from excel content"
},
{
"code": null,
"e": 26465,
"s": 26458,
"text": "Picked"
},
{
"code": null,
"e": 26473,
"s": 26465,
"text": "R-Excel"
},
{
"code": null,
"e": 26484,
"s": 26473,
"text": "R Language"
},
{
"code": null,
"e": 26582,
"s": 26484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26591,
"s": 26582,
"text": "Comments"
},
{
"code": null,
"e": 26604,
"s": 26591,
"text": "Old Comments"
},
{
"code": null,
"e": 26656,
"s": 26604,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26694,
"s": 26656,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26729,
"s": 26694,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26787,
"s": 26729,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26836,
"s": 26787,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26879,
"s": 26836,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 26929,
"s": 26879,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 26946,
"s": 26929,
"text": "R - if statement"
},
{
"code": null,
"e": 26983,
"s": 26946,
"text": "How to import an Excel File into R ?"
}
] |
Python Program to print strings with repetitive occurrence of an element in a list - GeeksforGeeks
|
11 Dec, 2020
Given a strings List, write a Python program that extracts all the strings with more than one occurrence of a specific value(here described using K) in elements of a list.
Examples:
Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = ‘e’ Output : [‘geeksforgeeks’, ‘geeks’] Explanation : geeks and geeksforgeeks have 2 and 4 occurrences of K respectively.
.Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = ‘k’ Output : [‘geeksforgeeks’] Explanation : geeksforgeeks has 2 occurrences of K
Method 1 : Using loop and count()
In this, we check for all the occurrence of K in each string using count, and check if any string has more than 1 occurrence of K and if found extract that string.
Python3
# initializing Matrixtest_list = ["geeksforgeeks", "best", "for", "geeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 'e' res = []for ele in test_list: # checking for count greater than 1 (repetitive) if ele.count(K) > 1: res.append(ele) # printing resultprint("Repeated K strings : " + str(res))
Output:
The original list is : [‘geeksforgeeks’, ‘best’, ‘for’, ‘geeks’]
Repeated K strings : [‘geeksforgeeks’, ‘geeks’]
Method 2 : Using list comprehension and count()
This is short hand solution for this task, similar to above method, just iteration using is done using list comprehension.
Python3
# initializing Matrixtest_list = ["geeksforgeeks", "best", "for", "geeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 'e' # checking for count greater than 1 (repetitive)# one-liner using list comprehensionres = [ele for ele in test_list if ele.count(K) > 1] # printing resultprint("Repeated K strings : " + str(res))
Output:
The original list is : [‘geeksforgeeks’, ‘best’, ‘for’, ‘geeks’]
Repeated K strings : [‘geeksforgeeks’, ‘geeks’]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Split string into list of characters
Python Program for Binary Search (Recursive and Iterative)
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 24073,
"s": 23901,
"text": "Given a strings List, write a Python program that extracts all the strings with more than one occurrence of a specific value(here described using K) in elements of a list."
},
{
"code": null,
"e": 24083,
"s": 24073,
"text": "Examples:"
},
{
"code": null,
"e": 24272,
"s": 24083,
"text": "Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = ‘e’ Output : [‘geeksforgeeks’, ‘geeks’] Explanation : geeks and geeksforgeeks have 2 and 4 occurrences of K respectively."
},
{
"code": null,
"e": 24424,
"s": 24272,
"text": ".Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = ‘k’ Output : [‘geeksforgeeks’] Explanation : geeksforgeeks has 2 occurrences of K "
},
{
"code": null,
"e": 24458,
"s": 24424,
"text": "Method 1 : Using loop and count()"
},
{
"code": null,
"e": 24622,
"s": 24458,
"text": "In this, we check for all the occurrence of K in each string using count, and check if any string has more than 1 occurrence of K and if found extract that string."
},
{
"code": null,
"e": 24630,
"s": 24622,
"text": "Python3"
},
{
"code": "# initializing Matrixtest_list = [\"geeksforgeeks\", \"best\", \"for\", \"geeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing KK = 'e' res = []for ele in test_list: # checking for count greater than 1 (repetitive) if ele.count(K) > 1: res.append(ele) # printing resultprint(\"Repeated K strings : \" + str(res))",
"e": 24997,
"s": 24630,
"text": null
},
{
"code": null,
"e": 25006,
"s": 24997,
"text": " Output:"
},
{
"code": null,
"e": 25071,
"s": 25006,
"text": "The original list is : [‘geeksforgeeks’, ‘best’, ‘for’, ‘geeks’]"
},
{
"code": null,
"e": 25119,
"s": 25071,
"text": "Repeated K strings : [‘geeksforgeeks’, ‘geeks’]"
},
{
"code": null,
"e": 25167,
"s": 25119,
"text": "Method 2 : Using list comprehension and count()"
},
{
"code": null,
"e": 25291,
"s": 25167,
"text": "This is short hand solution for this task, similar to above method, just iteration using is done using list comprehension. "
},
{
"code": null,
"e": 25299,
"s": 25291,
"text": "Python3"
},
{
"code": "# initializing Matrixtest_list = [\"geeksforgeeks\", \"best\", \"for\", \"geeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing KK = 'e' # checking for count greater than 1 (repetitive)# one-liner using list comprehensionres = [ele for ele in test_list if ele.count(K) > 1] # printing resultprint(\"Repeated K strings : \" + str(res))",
"e": 25672,
"s": 25299,
"text": null
},
{
"code": null,
"e": 25680,
"s": 25672,
"text": "Output:"
},
{
"code": null,
"e": 25745,
"s": 25680,
"text": "The original list is : [‘geeksforgeeks’, ‘best’, ‘for’, ‘geeks’]"
},
{
"code": null,
"e": 25793,
"s": 25745,
"text": "Repeated K strings : [‘geeksforgeeks’, ‘geeks’]"
},
{
"code": null,
"e": 25814,
"s": 25793,
"text": "Python list-programs"
},
{
"code": null,
"e": 25821,
"s": 25814,
"text": "Python"
},
{
"code": null,
"e": 25837,
"s": 25821,
"text": "Python Programs"
},
{
"code": null,
"e": 25935,
"s": 25837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25944,
"s": 25935,
"text": "Comments"
},
{
"code": null,
"e": 25957,
"s": 25944,
"text": "Old Comments"
},
{
"code": null,
"e": 25993,
"s": 25957,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 26016,
"s": 25993,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26055,
"s": 26016,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26088,
"s": 26055,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 26137,
"s": 26088,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 26159,
"s": 26137,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26198,
"s": 26159,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26236,
"s": 26198,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 26282,
"s": 26236,
"text": "Python | Split string into list of characters"
}
] |
From scratch to search: setup Elasticsearch under 4 minutes, load a CSV with Python and read some more about it | by Stanislav Prihoda 🔥 | Towards Data Science
|
Primary aim of this article is to provide a short and simple guidance on how to initially setup your first Elasticsearch “dev” environment in order to get going quickly and start exploring/exploiting what the technology offers. The introduction will be based around the foremost APIs that Elasticsearch offers which are fundamental for getting the data in and for execution of data queries. Secondary aim is to provide links on documentation and other interesting resources to be aware of other potential operations aspects, additional cool features and various tools (generally stuff I find useful when working with Elasticsearch). I have been missing this kind of an “intro with pointers further”, so this is an attempt for anyone alike :). These links will be summed up in dedicated What next sections in each chapter.
Intended audience could be individual data analyst or web developer, eventually small teams on budget that are having relevant data use-case and have already heard of Elasticsearch. What is not intended is to provide full technical overview of the technology (clusters, nodes, shards, replicas, Lucene, inverted indexes etc.) or a deep dive on some specific topic as there are many good resources on that... some of which will be linked in the article or in the What next sections.
If you’re just wondering how Elasticsearch can be useful for your purposes, then there are generally three main areas (among other) which can be effectively supported by the Elastic Stack
“big data” analytics & specific data science tasks which can revolve around having large semi-structured data (text and json objects) requiring highly available storage and fast full-text search capabilities. Interesting cases can be found for example in the NLP area, or when dealing with loads of GEO-based data with the need to perform geo-location queries and visualisations. Also it can bring value if you need just a ready-made exploration/dashboarding tool for some more complex business analytics queries.
time-series processing, storage and browsing relevant for dealing with streams of time-stamped data coming in. These can include Elastic’s power area log processing from vast amount of running services, or their monitoring from the health and uptime perspective and also for example processing any sensor data that can be ingested into the Elasticsearch etc.
full-text search of any large textual data (websites, enterprise stuff, document archives etc.) to make their content available for complex textual queries. These can (with correct setup) get returned under tens of milliseconds thus highly supporting user experience and ability to drill relevant information. Inspiration can be also found eg. in combination with other techniques such as OCR.
From my perspective the easiest way to start experimenting with Elasticsearch (and many other software technologies) is via Docker and thus the examples will utilize this approach. Generally the containerisation is (already for some time) taking over also the actual production deployment/ops so this can be two-in-one benefit. Large scale example of this is presented by Uber showing their fully containerised approach with hundreds of Elastic clusters. So let's do it...
I presume you are already familiar with Docker (if not... install Docker for Desktop for Mac, Windows or Linux distributions, read some intro stuff and you are good to go). Note: examples were tested on macOS Mojave, remember there might be some Docker specifics on Linux distros or Win.
When you have your docker environment ready just open your terminal and start Elasticsearch cluster with these commands:
docker network create elastic-network
This will create for us a basic communication “space” for our future containers.
Now if you want to go with just a single node deployment — just run:
docker run --rm --name esn01 -p 9200:9200 -v esdata01:/usr/share/elasticsearch/data --network elastic-network -e "node.name=esn01" -e "cluster.name=stanislavs-docker-cluster" -e "cluster.initial_master_nodes=esn01" -e "bootstrap.memory_lock=true" --ulimit memlock=-1:-1 -e ES_JAVA_OPTS="-Xms2g -Xmx2g" docker.elastic.co/elasticsearch/elasticsearch:7.3.0
Wait couple of seconds and in your log you should find message confirming setup success from your Elasticsearch cluster:
{“type”: “server”, “timestamp”: “2019–08–18T13:40:18,575+0000”, “level”: “INFO”, “component”: “o.e.n.Node”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn01”, “cluster.uuid”: “ilHqkY4UQuSRYnE5hFbhBg”, “node.id”: “KKnVMTDwQR6tinaGW_8kKg”, “message”: “started” }
Hooray... we have started our first Elasticsearch node (esn01) running in Docker container (named equally), listening on a port 9201 (docker -p parameter). Thanks to cluster.initial_master_nodes it has formed a new cluster (with name given in cluster.name) in the process known as cluster bootstrapping and immediately elected itself as the master of the cluster (what else to do when you are alone :)). Last thing worth mentioning is the -v parameter, which created new Docker volume esdata01 and bound it to a data directory of the running Elasticsearch — so that after restart our working data will be preserved. The rest of the parameters is more “system” related (and belong to important system settings) — we disable swapping with bootstrap.memory_lock, increase file/process limits with ulimit memlock and assigned initial/max heap size with ES_JAVA_OPTS (ie dedicated memory so adjust to your configuration... but remember that Elasticsearch utilizes also off-heap so do not set above 50% of available memory). Licensing note: it is by default running with a basic license but if you want to go with pure open-source flavor just add *-oss to the end of the image name.
Now if you want to try the taste of a distributed setup add two (or more) other nodes to your cluster. It is not needed for the rest of the tutorial (running on a local machine :)) nor even actual basic operations. Nevertheless as the distribution of the processing is actually one of the core value-adding capabilities of Elasticsearch (as the indexing part is mostly taken care by Apache Lucene library), it is at least good to be aware of it. So if you’re up to... here are our two other nodes (run in separate terminals):
docker run --rm --name esn02 -p 9202:9200 -v esdata02:/usr/share/elasticsearch/data --network elastic-network -e "node.name=esn02" -e "cluster.name=stanislavs-docker-cluster" -e "discovery.seed_hosts=esn01" -e "bootstrap.memory_lock=true" --ulimit memlock=-1:-1 -e ES_JAVA_OPTS="-Xms1g -Xmx1g" docker.elastic.co/elasticsearch/elasticsearch:7.3.0docker run --rm --name esn03 -p 9203:9200 -v esdata03:/usr/share/elasticsearch/data --network elastic-network -e "node.name=esn03" -e "cluster.name=stanislavs-docker-cluster" -e "discovery.seed_hosts=esn01,esn02" -e "bootstrap.memory_lock=true" --ulimit memlock=-1:-1 -e ES_JAVA_OPTS="-Xms1g -Xmx1g" docker.elastic.co/elasticsearch/elasticsearch:7.3.0
Now it starts to be more interesting as the nodes are joining our cluster. You can observe this process in logs, where you have messages about the additions (below from the master of our cluster about newly added node esn02). Generally the nodes are joining the cluster contacting other “already-present” nodes listed in discovery.seed_hosts parameter (to get an up-to-date info on the cluster setup) — this param belongs (along with aforementioned cluster.initial_master_nodes) to important discovery settings. All communication between nodes in the cluster is performed directly over the Transport layer (ie without the HTTP overhead) that’s why there is the port 9300 (not the port 920x we have exposed for “outside” communication with the cluster).
{“type”: “server”, “timestamp”: “2019–08–18T13:40:28,169+0000”, “level”: “INFO”, “component”: “o.e.c.s.ClusterApplierService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn01”, “cluster.uuid”: “ilHqkY4UQuSRYnE5hFbhBg”, “node.id”: “KKnVMTDwQR6tinaGW_8kKg”, “message”: “added {{esn02}{4xOwc-_fQDO_lwTlpPks2A}{FW-6YGVSSsmgEt3Mo_GY_Q}{172.18.0.3}{172.18.0.3:9300}{dim}{ml.machine_memory=8360488960, ml.max_open_jobs=20, xpack.installed=true},}, term: 1, version: 16, reason: Publication{term=1, version=16}” }
Everything is up and running so we can check couple of things about our Elasticsearch cluster (notice that we can contact any node in our cluster as generally any node can become coordinating node to process the incoming request via scatter-gather approach):
Basic info about the contacted node:
curl localhost:9200
returns:
{ "name" : "esn01", "cluster_name" : "stanislavs-docker-cluster", "cluster_uuid" : "ilHqkY4UQuSRYnE5hFbhBg", "version" : { "number" : "7.3.0", "build_flavor" : "default", "build_type" : "docker", "build_hash" : "de777fa", "build_date" : "2019–07–24T18:30:11.767338Z", "build_snapshot" : false, "lucene_version" : "8.1.0", "minimum_wire_compatibility_version" : "6.8.0", "minimum_index_compatibility_version" : "6.0.0-beta1" }, "tagline" : "You Know, for Search"}
Basic info about the cluster status:
curl localhost:9202/_cluster/health?pretty
returns:
{ "cluster_name" : "stanislavs-docker-cluster", "status" : "green", "timed_out" : false, "number_of_nodes" : 3, "number_of_data_nodes" : 3, "active_primary_shards" : 0, "active_shards" : 0, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0, "delayed_unassigned_shards" : 0, "number_of_pending_tasks" : 0, "number_of_in_flight_fetch" : 0, "task_max_waiting_in_queue_millis" : 0, "active_shards_percent_as_number" : 100.0}
Further info about the nodes in the cluster:
curl localhost:9203/_cat/nodes?v
returns:
ip heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name172.19.0.2 26 56 3 0.01 0.16 0.17 dim * esn01172.19.0.4 13 56 1 0.01 0.16 0.17 dim — esn03172.19.0.3 20 56 2 0.01 0.16 0.17 dim — esn02
Last response is probably the most interesting (as the above basically says we have an empty cluster :) . We can see all of the three nodes we have in our cluster (esn01–03). From node.role we can see that all nodes are of the type mdi — which means they are master-eligible (can be elected master if the current master “breaks down”), data (holds actual data ie shards and can perform CRUD/search operations) and ingest (can setup special ingest pipeline to pre-process ie transform/enrich the incoming data before actual indexing). We can also see our current master (marked with *).
DEPLOYMENT: think with your devops about the best option to run in your integration/production environment — options are: standard local installation on your servers, managed-service solution Elastic Cloud or AWS Elasticsearch etc. or sort of a “middle option” mentioned earlier with deploying the docker/OCI images into some containerization platform (Kubernetes, OpenShift, Swarm) running again either on-prem or in the cloud
CONFIGURATION: fundamental configuration resource is elasticsearch.yml file (located in config directory) which is present in any Elasticsearch instance — read more info on that (and other key params) in the important settings
SECURITY: first...! you can go with native ES Security option or with more complex setup with some Security plugin (SearchGuard, Open Distro Security). At least have TLS and role-based auth!
CLUSTERING: so distributed much fault-tolerant ... no seriously if you want to dive deeper into the clustering concepts read something about different node type ie master-eligible/data/ingest/ML and the dig into discovery modules and process (ie to find out why you should have three or more master-eligible nodes in your cluster)
SIZING: read more on sizing and capacity planning
DOCKER: further info on Docker setup, volumes, networks or if you are dealing with specific Elasticsearch version you can get matching image
LOGGING OF ELASTICSEARCH: change logging configuration (based on log4j) in specific hierarchy etc. useful when setting the thing up
LICENSING: it’s good to check under which specific licensing schema some specific desired feature falls (in this article I try to work with either pure oss under Apache 2.0 or basic-licensed stuff for testing)
APIs: Elasticsearch provides a good documentation of all their REST APIs so check it out
APIs: if you liked the cat API with info on your cluster (such as I do) know that there is plenty more covering nodes, shards, indices, health, segments etc. etc.
When you have your initial environment set up it is time to get our data to our running node(s) to be ready for searching. The basic principle of Elasticsearch is that any “unit” of our data that is put to it is called DOCUMENT. Required format of these documents is JSON. These documents are not stored individually but are grouped into specific collections that are called INDEXes. Documents in one index share similar characteristics (ie data types mappings, settings etc.), thus the index serves also as a management and API layer to the contained documents.
So let’s create an index with Create — Indices API and put ie index one document to it with Index — Document API...
curl -X PUT \ http://localhost:9200/test-csv \ -H 'Content-Type: application/json' \ -d '{ "settings" : { "index" : { "number_of_shards" : 3, "number_of_replicas" : 2 } }}'
returns:
{“acknowledged”:true,”shards_acknowledged”:true,”index”:”test-csv”}
Index creation... checked! We have created our first index named test-csv and defined an important settings of the number of shards and replicas. Primary shards and shard replicas (in correct terms) are a way to split our index (ie document collection) into multiple pieces thus ensuring redundancy. Actual values depend (in a basic sense) on how many nodes we have. Number of shards (ie to how many units our index will be split into) is fixed with index creation. Number of replicas determines how many times the primary shard (ie each of our 3) will be “copied”. We have defined 2 as we want to achieve a state where on each node we have one primary shard (1⁄3 of our data) but also copies of other 2⁄3 of our data ie the full dataset. This setup ensures that if we loose one of our nodes we won’t loose any data. Hint: if you don’t want for starter to mess with these settings you don’t have to because if you attempt to index a document without an existing index — it gets created automatically (with default 1 shard and 1 replica).
curl -X PUT \ http://localhost:9203/test-csv/_doc/1?pretty \ -H 'Content-Type: application/json' \ -d '{ "value": "first document"}'
returns:
{ "_index" : "test-csv", "_type" : "_doc", "_id" : "1", "_version" : 1, "result" : "created", "_shards" : { "total" : 3, "successful" : 3, "failed" : 0 }, "_seq_no" : 0, "_primary_term" : 1}
Document indexing... checked! We have indexed our first document to our test-csv index, all shards responded correctly. We have indexed a very simple json document with only one field, but you can index basically any document (from the size, depth etc perspectives) as long as it is valid JSON — but try to keep it under 100MB per doc :). Now you can easily retrieve a single document by its id with Get API. I’ll leave that up to you.
Now obviously you don’t want to index your documents one by one with curl. The more when you probably already have this data somewhere in your application, database or storage drive. For these purposes there are official Elasticsearch clients for various programming languages ie Java, JS, Go, Python etc. You can grab any of these based on your technology stack and use its APIs to perform indexing/deleting/updating/... actions programmatically.
But if you just have the data and want to quickly get them in you have two options... I took the Python client and prepared very simple CLI script that allows you to index data from given file — supporting CSV format and NDJSON format (newline delimited JSON which is often used for logging, streaming processing etc.). Take it as a possible way how to tackle your data “problem” and write something better based on your needs :). You can browse many other methods and helpers matching the Elasticsearch APIs it offers in the client docs. In any way don’t forget to pip install elasticsearch (to install the module) before using the script.
Code/script freely available in this repo:
github.com
I won’t describe the whole code contents (as it always could be written better :)), but there are two relevant parts in the code:
1.It utilizes concept of Python generator as it goes line by line through the given file and yields one preprocessed element/row for the indexing execution. This “element-wise” operation was picked on purpose to ensure memory-efficiency to be able to process even large files.
def _csv_generator(self, es_dataset, **kwargs): with open(es_dataset.input_file) as csv_file: csv_dict_reader = csv.DictReader(csv_file) for cnt, row in enumerate(csv_dict_reader): yield self._prepare_document_for_bulk(es_dataset, row, cnt)
2. On the other hand as the actual indexing operation is somewhat costly it utilizes the BULK API to index in multiple-document chunks (default 500 items) which is aligned with recommendations for tuning for speed). For this operation it uses one of the provided helpers (which are convenience abstractions on top of the raw api) by the python elasticsearch client — elasticsearch.helpers.streaming_bulk.
for cnt, response in enumerate(streaming_bulk(self.client, generator, chunk_size)): ok, result = response
After execution it is necessary to use the refresh API to make the documents immediately searchable.
self.client.indices.refresh(index=es_dataset.es_index_name)
From the data perspective there are wide options nowadays how to get some interesting data set (Kaggle datasets, AWS datasets or other curated lists of open datasets), but as we will want to demonstrate also some text searching capabilities let’s test/showcase our script on something from NLP area — nice collection can be found here. We can use for example Jeopardy questions dataset as it is not a usual demo dataset. Note: if you use this set also consider removal of whitespaces from the header to have more concise column/field names.
Now we can run following command in terminal and watch the stdout logs (for testing purposes I left the DEBUG level on):
python3 load_csv_or_json_to_elasticsearch.py _data/JEOPARDY_CSV.csv test-csv
In the end we should receive a following message:
2019–08–18 17:03:19,013 — load_csv_or_json_to_elasticsearch.py — INFO — Script execution FINALIZED in 44.15356087684631 seconds. Dataset from file _data/JEOPARDY_CSV.csv loaded to Elasticsearch at localhost:9200. Number of documents processed: 216929.
The execution took 44 seconds which is not that fast, but as we are running everything on a single machine it is (must be :)) acceptable. Actually quite a bit of that is the cost of the 3+2 sharding so so for test if go just with 1+0 (and single node) we are under 25 seconds. It could probably be further improved by self-optimized management of the chunks sizing as recommended in tune for speed documentation (ie starting at 100 and then gradually increased until the speed plateau), so you can do it as an interesting exercise. On the other hand if we were to index the documents one by one we are up to beautiful 1411 seconds :), so it seems the bulk api makes some sense.
Now we can recheck the /_cat/indices?v API to make sure all of our data are in place.
INDEX MAPPING/SETTINGS: check the data structure of your index with Get Mapping API and index settings with Get Settings API — there are various settings options.
INDEX TEMPLATING: for usecases where similar indexes get created on an ongoing basis (ie on some time periods) it is convenient to use a predefined structure for that — this is case for Index Templates
INDEX CHANGES: you can move the data between indexes with Reindex API (useful when you need to make changes in sharding — which is not possible after creation), this can be used in conjunction with Index Aliases that allow to create a “nickname” to which we can point our queries (this layer of abstraction allows to then change the indexes behind the alias more freely)
ANALYSIS: when we index or full-text search the query goes through the analysis process, read more about the Analyzers and its core building blocks character filters, tokenizers, and token filters or create your custom analyzer.
CLIENTS: official Elasticsearch clients for various programming languages ie Java, JS, Go, Python etc.
DATA INGESTION: usually with time-based data (such as logs, monitoring etc.) you might consider using other tools from the Elastic Stack such a Beats (multi-purpose lightweights data shippers) or/and Logstash for more sophisticated data pre-processing before indexing to Elasticsearch
MEMORY/STORAGE: if you find yourself with growing amounts of indexed data running low on disk space you might consider Index Lifecycle Management that allows based on defined rules to change or delete indices. Or/and if you are low on memory you can consider index freezing that will move various overhead data structures off the heap. Or just buy more disk space and memory :)
PERFORMANCE: tune for indexing speed or efficient disk usage
Now that we have indexed our data we can finally search and browse through our data. Elasticsearch uses specific JSON-based language Query DSL (Domain Specific Language) to perform various complex queries across the indexed data. As there are many options in the Query DSL world of Elasticsearch we will just go through couple and let you try the rest.
The simplest way to search in Elasticsearch though is without the Query DSL just providing the searched string as a query parameter in URI Search which is useful for quick curl tests as Elastic itself says :). So let’s start with that and search for documents consisting the term impressionism.
curl localhost:9200/test-csv/_search?q=question:impressionism
returns:
{ "took": 10, "timed_out": false, "_shards": { "total": 3, "successful": 3, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 4, "relation": "eq" }, "max_score": 13.689855, "hits": [(...) { "_index": "test-csv", "_type": "_doc", "_id": "68959", "_score": 12.518969, "_source": { "show-number": "4943", "air-date": "2006–02–22", "round": "Double Jeopardy!", "category": "ART & ARTISTS", "value": "$1200", "question": "Impressionism got its name thanks to his painting \"Impression: Sunrise\"", "answer": "(Claude) Monet" } }(...)
We can see that the query on our 216k documents took 10ms, has gone through all 3 shards successfully and 4 documents with the given term were found. The actual results are under the hits object in hits array. For each document ie hit we have received along with the actual contents in the _source field also the _score field which is a calculation of relevance
Now let’s use the Query DSL to search across multiple fields. For this purpose we will use the Multi-match query that allows exactly that. As can be seen in the linked docs there are various options to play with conditions, relevance calculation and other params. Let’s keep the topic and search for Claude Monet. We will specify the phrase as a type as we want to match both, Elasticsearch would otherwise also return documents matching only one of the terms (Claude but no Monet).
curl -X GET \ http://localhost:9203/test-csv/_search \ -H 'Content-Type: application/json' \ -d '{ "query": { "multi_match" : { "query": "Claude Monet", "fields": [ "category", "question", "answer" ], "type": "phrase" } }}'
returns:
{"took": 16, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 36, "relation": "eq" }, "max_score": 22.763008, "hits": [ { "_index": "test-csv", "_type": "_doc", "_id": "171125", "_score": 22.763008, "_source": { "show-number": "2918", "air-date": "1997–04–16", "round": "Jeopardy!", "category": "CROSSWORD CLUES \"I\"", "value": "$400", "question": "Claude Monet or Rich Little (13)", "answer": "Impressionist" } },(...)
We have now 36 hits and the top 10 were returned under the hits field. Btw. the first result... I wonder what would Claude say to his fellow’s impressions :).
For the third query let’s go even more complex and combine the above two searches in a way that we seek again for Claude Monet (that’s a MUST) but also we value more result matching also the term impressionism (that’s a SHOULD)... The must/should stuff might seem weird to you but as we are going to use the Boolean query for our search we will be using exactly these terms. Bool query is the default from so called Compound queries that allow combining multiple leaf queries (which are the actual queries matching some field) or other compound queries.
curl -X GET \ http://localhost:9202/test-csv/_search \ -H 'Content-Type: application/json' \ -d '{ "query": { "bool" : { "must" : { "multi_match" : { "query": "Claude Monet", "fields": [ "category", "question", "answer" ], "type": "phrase" } }, "should" : { "match" : { "question" : "impressionism" } } } }}'
returns:
{ "took": 6, "timed_out": false, "_shards": { "total": 3, "successful": 3, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 36, "relation": "eq" }, "max_score": 28.663502, "hits": [ { "_index": "test-csv", "_type": "_doc", "_id": "68959", "_score": 28.663502, "_source": { "show-number": "4943", "air-date": "2006–02–22", "round": "Double Jeopardy!", "category": "ART & ARTISTS", "value": "$1200", "question": "Impressionism got its name thanks to his painting \"Impression: Sunrise\"", "answer": "(Claude) Monet" } }, { "_index": "test-csv", "_type": "_doc", "_id": "171125", "_score": 22.763008, "_source": { "show-number": "2918", "air-date": "1997–04–16", "round": "Jeopardy!", "category": "CROSSWORD CLUES \"I\"", "value": "$400", "question": "Claude Monet or Rich Little (13)", "answer": "Impressionist" } },(...)
We can see that we have received as a top score the original result as it is the only one matching all of our terms in the exact form.
QUERY DSL: check all the various options for the full-text queries
QUERY CONTEXT & FILTER CONTEXT: does the document match our query vs how well it matches
LEAF QUERIES & COMPOUND QUERIES: with Leaf queries look for a particular value in a particular field, such as the match, term or range queries, on the other hand with Compound queries you can wrap other compound or leaf queries together
AGGREGATIONS: instead of working with the data on a “document-level” basis you can aggregate your results to different types of aggregate outcomes such as buckets, metrices, matrixes, pipelines with wide range of options
COMMON OPTIONS: see the various options that can be applied to all of the REST APIs or specifically to the search query body
PERFORMANCE: tune for the max search speed
SCORE TUNING: you can play with relevance score with Function score query or Script score query (allowing custom script for score calc) or check out other tunning options (such as rank_feature) to make the results more relevant for your case
HIGHLIGHTING & SUGGESTERS: there is plentiful of other cool features such as Completion suggester for auto-complete/search-as-you-type functionality or Highlighting for wrapping the results in html tags to emphasise where the matches are
Up until now we have been interacting directly with our Elasticsearch cluster. In the first chapter via python client but later mostly with simple terminal cURL commands. cURL is fine for quick tests and putting things together but when you want to perform some data exploration with plotting, filtering etc. or need some tool for administration checks and updates on your cluster and indexes you might want to choose some more convenient UI-based app. Which is exactly what Kibana is or as Elastic puts it window to Elasticsearch. Without further ado let’s add it to our setup and see what we are up to:
docker run --rm --link esn01:elasticsearch --name kibana --network elastic-network -p 5601:5601 docker.elastic.co/kibana/kibana:7.3.0
The Kibana docker params are quite simple. We basically need to do two things — add Kibana to our docker network (with — network) and link it with our Elasticsearch cluster (eg. with — link pointed towards our esn01 node), we also keep the default port 5601 and pick the same version 7.3. as we are running our Elasticsearch on — must do for compatibility purposes. Note: these can also be overridden with bind-mounted custom kibana.yml or via environment variables. After it loads up you have your Kibana instance running at: http://localhost:5601 so don’t waste your time and check it out :). It will take you to your Home section and you can start browsing the Kibana neighbourhood.
Our goal is to start working with the data quickly so we will head straight to Management -> Index Patterns and select create our first index pattern. From the Kibana usage perspective the index patterns are likely the most important concept. They represent a logical structure over the Elasticsearch indexes and which tells Kibana what indexes (and related fields) to work with. Index pattern can match the name of a single index, or include a wildcard (*) to match multiple indices. So let’s create test-* index pattern (that shall match our test-csv index).
In the next step we will select a timestamp field which will be later used for time-based filtering. This can be omitted by selecting I don’t want to use Time Filter but if you have any timestamp field in your data I recommend not to so that we can do time-series visualizations. Select Create and we are done. It will take you to the index pattern overview page where you have list of all your fields (which can be refreshed in top-right corner if you added some more fields). You can change the formats of the individual fields and you can also add new Scripted (but as Elastic recommends for performance purposes Please familiarize yourself with script fields and with scripts in aggregations before using scripted fields.).
We can do other sorts of Elasticsearch administration/configuration stuff in the Kibana Management application eg. we can check out Index management section with info/actions on our indices (eg. freeze, delete, merge etc.) or setup automatic jobs and rules for Index Lifecycle Management (that will do this for us). On a last note all Kibana settings gets stored to Elasticsearch in the .kibana system indices so thanks to our docker volumes these will be preserved after restarts along with our other data.
The go-to section when you want to browse, query and filter your data is the Discover application (first in the left menu). When you open it you will see our default index pattern that we have created and the individual data points.
Here you can:
filter for required time range (remember our data is from 1984–2012)
filter out for required field or value (tip: use magnifier symbol next to the field or value)
use Kibana Query Language to perform searches on the data ie category: STUPID ANSWERS
see basic field statistics
view your single document data and list other document in its context (ie from time perspective)
Kibana is also useful when you’re in need to visually present your data findings or to provide interactive performance/status/metrics/KIPs overviews of the area you are dealing with. For these purposes you can create visualizations in the Kibana Visualize app and group these visualizations on rich Dashboards that can be also provided with explanatory markdowns etc. All of this is built on top of your indexed data and allows in real-time for further filtering and customizable views eg. for specific time-range.
As our showcase dataset is not really numeric in its nature we can’t really utilize all the options but let’s crate at least couple of document-counts visualizations and put them on a dashboard to have the sense of what it is about. So let’s go to the Visualize app (second on the left) and select Create new visualization.
Let’ do a count of documents (ie Questions we have in our data) grouped by year. Pick a Vertical Bar and select our test-* index pattern through which the data will be pulled. Then let’s add to Buckets and X-axis bucket with Date Histogram Aggregation, pick our air-date field and select a Yearly interval. Optionally you can drop partial buckets and in the top-right corner you should see “play arrow” button which will apply defined settings to our visualization. And... you’re done.
To put this on a Dashboard go to the Dashboard app (bellow Visualize) and Create new dashboard. In the top menu you have an Add option so use it to add a panel with your visualization. And... you’re done. Now you can try couple of these and I’m sure you can do much better than I did with my simple dashboard bellow :).
CONFIGURATION: at some point you will find the need to change other Kibana configurations so linked is a overview of the options
SECURITY: see the first What next section and check the linked resources as these are obviously must apply also for Kibana (generally there are equivalent plugins or native-capabilities also for Kibana)
VISUALISATION: create a visualization in the Visualize app, put multiple visualizations together with interactive Dashboard or share even more visually customizable reports with Canvas, if you have a GeoJSON data put the on Maps
SPACES: uses spaces to separate out different data areas/domains etc.
MONITORING: Stack Monitoring app is very useful especially when dealing with higher number of instances of the stack tools (having loads of servers with Beats deployed, multiple nodes in the cluster etc.)
OTHER KIBANA APPS: there are plenty depending on your stack setup eg. Uptime used with Heartbeats for endpoint monitoring
DEV TOOLS: use Dev Tools when liking the Kibana UI but still want to perform some request-based stuff
CSV FILE LOAD: you can perform the same CSV/NDJSON ingestion (we have done with our Python script) via still quite new Kibana tool (still with Experimental status) File Data Visualizer that allow index data up to 100MB — very good for quick data checks.
SAMPLE DATA: if you just want to play with Kibana use provided sample data
It wouldn’t be a full (distributed) picture without seeing a master election. You can play with these easily in Docker, but remember to put all back up afterwards:). We check who is the current master (eg. /_cat/nodes remember) and to kill it we can run:
docker stop esn01
This will immediately cause an exception in our cluster and initiate a master elections. Except the apparent exception (about the failed connection to the master) you can see in the logs that both nodes became candidates for the master (both are master-eligible as we already know) and execution of the elections with two candidating nodes. Everything happened under 200ms (for real life scenario also add some network overhead etc.).
{“type”: “server”, “timestamp”: “2019–08–18T18:31:15,485+0000”, “level”: “INFO”, “component”: “o.e.c.s.ClusterApplierService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn02”, “cluster.uuid”: “w16btQPhSQ-iE96DSM6PnQ”, “node.id”: “yPAolS5gTxes0mcltF5WvA”, “message”: “master node changed {previous [{esn01}{EHEDowSVRMenU2BaVM442g}{thFwnNprQs-QwOx75KUbUg}{172.18.0.2}{172.18.0.2:9300}], current []}, term: 1, version: 5, reason: becoming candidate: onLeaderFailure” }(...){“type”: “server”, “timestamp”: “2019–08–18T18:31:15,626+0000”, “level”: “INFO”, “component”: “o.e.c.s.MasterService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn03”, “cluster.uuid”: “w16btQPhSQ-iE96DSM6PnQ”, “node.id”: “rLAI506ATr6lvqw-aiKgHg”, “message”: “elected-as-master ([2] nodes joined)[{esn03}{rLAI506ATr6lvqw-aiKgHg}{pf-3B_9GTGayL4KzmGkqIQ}{172.18.0.4}{172.18.0.4:9300} elect leader, {esn02}{yPAolS5gTxes0mcltF5WvA}{kadMA9eFTO2WR4v0t4aXzQ}{172.18.0.3}{172.18.0.3:9300} elect leader, _BECOME_MASTER_TASK_, _FINISH_ELECTION_], term: 2, version: 6, reason: master node changed {previous [], current [{esn03}{rLAI506ATr6lvqw-aiKgHg}{pf-3B_9GTGayL4KzmGkqIQ}{172.18.0.4}{172.18.0.4:9300}]}” }
Afterwards you can request the /_cat/nodes?v again to see who is the new boss. When you’re done you can clean things up for the fresh start with docker system prune — volumes which will remove unused containers, volumes, networks etc.
That’s it... we went through a simple “end-to-end” process with Elasticsearch starting with Docker setup, getting the data in the cluster and performing basic search queries. We then also added Kibana to our stack to have some browsing and administration comfort and useful visualisations features. From the original goals outlined in the introduction maybe the shortness wasn’t really reached :) but hopefully you gained some understanding what the technology can offer to have a basis for decision on how to eventually deploy it to your architecture. Feel free to share any additional interesting resources that can be appended to the What next sections lists.
|
[
{
"code": null,
"e": 994,
"s": 172,
"text": "Primary aim of this article is to provide a short and simple guidance on how to initially setup your first Elasticsearch “dev” environment in order to get going quickly and start exploring/exploiting what the technology offers. The introduction will be based around the foremost APIs that Elasticsearch offers which are fundamental for getting the data in and for execution of data queries. Secondary aim is to provide links on documentation and other interesting resources to be aware of other potential operations aspects, additional cool features and various tools (generally stuff I find useful when working with Elasticsearch). I have been missing this kind of an “intro with pointers further”, so this is an attempt for anyone alike :). These links will be summed up in dedicated What next sections in each chapter."
},
{
"code": null,
"e": 1476,
"s": 994,
"text": "Intended audience could be individual data analyst or web developer, eventually small teams on budget that are having relevant data use-case and have already heard of Elasticsearch. What is not intended is to provide full technical overview of the technology (clusters, nodes, shards, replicas, Lucene, inverted indexes etc.) or a deep dive on some specific topic as there are many good resources on that... some of which will be linked in the article or in the What next sections."
},
{
"code": null,
"e": 1664,
"s": 1476,
"text": "If you’re just wondering how Elasticsearch can be useful for your purposes, then there are generally three main areas (among other) which can be effectively supported by the Elastic Stack"
},
{
"code": null,
"e": 2178,
"s": 1664,
"text": "“big data” analytics & specific data science tasks which can revolve around having large semi-structured data (text and json objects) requiring highly available storage and fast full-text search capabilities. Interesting cases can be found for example in the NLP area, or when dealing with loads of GEO-based data with the need to perform geo-location queries and visualisations. Also it can bring value if you need just a ready-made exploration/dashboarding tool for some more complex business analytics queries."
},
{
"code": null,
"e": 2537,
"s": 2178,
"text": "time-series processing, storage and browsing relevant for dealing with streams of time-stamped data coming in. These can include Elastic’s power area log processing from vast amount of running services, or their monitoring from the health and uptime perspective and also for example processing any sensor data that can be ingested into the Elasticsearch etc."
},
{
"code": null,
"e": 2931,
"s": 2537,
"text": "full-text search of any large textual data (websites, enterprise stuff, document archives etc.) to make their content available for complex textual queries. These can (with correct setup) get returned under tens of milliseconds thus highly supporting user experience and ability to drill relevant information. Inspiration can be also found eg. in combination with other techniques such as OCR."
},
{
"code": null,
"e": 3404,
"s": 2931,
"text": "From my perspective the easiest way to start experimenting with Elasticsearch (and many other software technologies) is via Docker and thus the examples will utilize this approach. Generally the containerisation is (already for some time) taking over also the actual production deployment/ops so this can be two-in-one benefit. Large scale example of this is presented by Uber showing their fully containerised approach with hundreds of Elastic clusters. So let's do it..."
},
{
"code": null,
"e": 3692,
"s": 3404,
"text": "I presume you are already familiar with Docker (if not... install Docker for Desktop for Mac, Windows or Linux distributions, read some intro stuff and you are good to go). Note: examples were tested on macOS Mojave, remember there might be some Docker specifics on Linux distros or Win."
},
{
"code": null,
"e": 3813,
"s": 3692,
"text": "When you have your docker environment ready just open your terminal and start Elasticsearch cluster with these commands:"
},
{
"code": null,
"e": 3851,
"s": 3813,
"text": "docker network create elastic-network"
},
{
"code": null,
"e": 3932,
"s": 3851,
"text": "This will create for us a basic communication “space” for our future containers."
},
{
"code": null,
"e": 4001,
"s": 3932,
"text": "Now if you want to go with just a single node deployment — just run:"
},
{
"code": null,
"e": 4355,
"s": 4001,
"text": "docker run --rm --name esn01 -p 9200:9200 -v esdata01:/usr/share/elasticsearch/data --network elastic-network -e \"node.name=esn01\" -e \"cluster.name=stanislavs-docker-cluster\" -e \"cluster.initial_master_nodes=esn01\" -e \"bootstrap.memory_lock=true\" --ulimit memlock=-1:-1 -e ES_JAVA_OPTS=\"-Xms2g -Xmx2g\" docker.elastic.co/elasticsearch/elasticsearch:7.3.0"
},
{
"code": null,
"e": 4476,
"s": 4355,
"text": "Wait couple of seconds and in your log you should find message confirming setup success from your Elasticsearch cluster:"
},
{
"code": null,
"e": 4753,
"s": 4476,
"text": "{“type”: “server”, “timestamp”: “2019–08–18T13:40:18,575+0000”, “level”: “INFO”, “component”: “o.e.n.Node”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn01”, “cluster.uuid”: “ilHqkY4UQuSRYnE5hFbhBg”, “node.id”: “KKnVMTDwQR6tinaGW_8kKg”, “message”: “started” }"
},
{
"code": null,
"e": 5930,
"s": 4753,
"text": "Hooray... we have started our first Elasticsearch node (esn01) running in Docker container (named equally), listening on a port 9201 (docker -p parameter). Thanks to cluster.initial_master_nodes it has formed a new cluster (with name given in cluster.name) in the process known as cluster bootstrapping and immediately elected itself as the master of the cluster (what else to do when you are alone :)). Last thing worth mentioning is the -v parameter, which created new Docker volume esdata01 and bound it to a data directory of the running Elasticsearch — so that after restart our working data will be preserved. The rest of the parameters is more “system” related (and belong to important system settings) — we disable swapping with bootstrap.memory_lock, increase file/process limits with ulimit memlock and assigned initial/max heap size with ES_JAVA_OPTS (ie dedicated memory so adjust to your configuration... but remember that Elasticsearch utilizes also off-heap so do not set above 50% of available memory). Licensing note: it is by default running with a basic license but if you want to go with pure open-source flavor just add *-oss to the end of the image name."
},
{
"code": null,
"e": 6456,
"s": 5930,
"text": "Now if you want to try the taste of a distributed setup add two (or more) other nodes to your cluster. It is not needed for the rest of the tutorial (running on a local machine :)) nor even actual basic operations. Nevertheless as the distribution of the processing is actually one of the core value-adding capabilities of Elasticsearch (as the indexing part is mostly taken care by Apache Lucene library), it is at least good to be aware of it. So if you’re up to... here are our two other nodes (run in separate terminals):"
},
{
"code": null,
"e": 7153,
"s": 6456,
"text": "docker run --rm --name esn02 -p 9202:9200 -v esdata02:/usr/share/elasticsearch/data --network elastic-network -e \"node.name=esn02\" -e \"cluster.name=stanislavs-docker-cluster\" -e \"discovery.seed_hosts=esn01\" -e \"bootstrap.memory_lock=true\" --ulimit memlock=-1:-1 -e ES_JAVA_OPTS=\"-Xms1g -Xmx1g\" docker.elastic.co/elasticsearch/elasticsearch:7.3.0docker run --rm --name esn03 -p 9203:9200 -v esdata03:/usr/share/elasticsearch/data --network elastic-network -e \"node.name=esn03\" -e \"cluster.name=stanislavs-docker-cluster\" -e \"discovery.seed_hosts=esn01,esn02\" -e \"bootstrap.memory_lock=true\" --ulimit memlock=-1:-1 -e ES_JAVA_OPTS=\"-Xms1g -Xmx1g\" docker.elastic.co/elasticsearch/elasticsearch:7.3.0"
},
{
"code": null,
"e": 7906,
"s": 7153,
"text": "Now it starts to be more interesting as the nodes are joining our cluster. You can observe this process in logs, where you have messages about the additions (below from the master of our cluster about newly added node esn02). Generally the nodes are joining the cluster contacting other “already-present” nodes listed in discovery.seed_hosts parameter (to get an up-to-date info on the cluster setup) — this param belongs (along with aforementioned cluster.initial_master_nodes) to important discovery settings. All communication between nodes in the cluster is performed directly over the Transport layer (ie without the HTTP overhead) that’s why there is the port 9300 (not the port 920x we have exposed for “outside” communication with the cluster)."
},
{
"code": null,
"e": 8429,
"s": 7906,
"text": "{“type”: “server”, “timestamp”: “2019–08–18T13:40:28,169+0000”, “level”: “INFO”, “component”: “o.e.c.s.ClusterApplierService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn01”, “cluster.uuid”: “ilHqkY4UQuSRYnE5hFbhBg”, “node.id”: “KKnVMTDwQR6tinaGW_8kKg”, “message”: “added {{esn02}{4xOwc-_fQDO_lwTlpPks2A}{FW-6YGVSSsmgEt3Mo_GY_Q}{172.18.0.3}{172.18.0.3:9300}{dim}{ml.machine_memory=8360488960, ml.max_open_jobs=20, xpack.installed=true},}, term: 1, version: 16, reason: Publication{term=1, version=16}” }"
},
{
"code": null,
"e": 8688,
"s": 8429,
"text": "Everything is up and running so we can check couple of things about our Elasticsearch cluster (notice that we can contact any node in our cluster as generally any node can become coordinating node to process the incoming request via scatter-gather approach):"
},
{
"code": null,
"e": 8725,
"s": 8688,
"text": "Basic info about the contacted node:"
},
{
"code": null,
"e": 8745,
"s": 8725,
"text": "curl localhost:9200"
},
{
"code": null,
"e": 8754,
"s": 8745,
"text": "returns:"
},
{
"code": null,
"e": 9298,
"s": 8754,
"text": "{ \"name\" : \"esn01\", \"cluster_name\" : \"stanislavs-docker-cluster\", \"cluster_uuid\" : \"ilHqkY4UQuSRYnE5hFbhBg\", \"version\" : { \"number\" : \"7.3.0\", \"build_flavor\" : \"default\", \"build_type\" : \"docker\", \"build_hash\" : \"de777fa\", \"build_date\" : \"2019–07–24T18:30:11.767338Z\", \"build_snapshot\" : false, \"lucene_version\" : \"8.1.0\", \"minimum_wire_compatibility_version\" : \"6.8.0\", \"minimum_index_compatibility_version\" : \"6.0.0-beta1\" }, \"tagline\" : \"You Know, for Search\"}"
},
{
"code": null,
"e": 9335,
"s": 9298,
"text": "Basic info about the cluster status:"
},
{
"code": null,
"e": 9378,
"s": 9335,
"text": "curl localhost:9202/_cluster/health?pretty"
},
{
"code": null,
"e": 9387,
"s": 9378,
"text": "returns:"
},
{
"code": null,
"e": 9879,
"s": 9387,
"text": "{ \"cluster_name\" : \"stanislavs-docker-cluster\", \"status\" : \"green\", \"timed_out\" : false, \"number_of_nodes\" : 3, \"number_of_data_nodes\" : 3, \"active_primary_shards\" : 0, \"active_shards\" : 0, \"relocating_shards\" : 0, \"initializing_shards\" : 0, \"unassigned_shards\" : 0, \"delayed_unassigned_shards\" : 0, \"number_of_pending_tasks\" : 0, \"number_of_in_flight_fetch\" : 0, \"task_max_waiting_in_queue_millis\" : 0, \"active_shards_percent_as_number\" : 100.0}"
},
{
"code": null,
"e": 9924,
"s": 9879,
"text": "Further info about the nodes in the cluster:"
},
{
"code": null,
"e": 9957,
"s": 9924,
"text": "curl localhost:9203/_cat/nodes?v"
},
{
"code": null,
"e": 9966,
"s": 9957,
"text": "returns:"
},
{
"code": null,
"e": 10180,
"s": 9966,
"text": "ip heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name172.19.0.2 26 56 3 0.01 0.16 0.17 dim * esn01172.19.0.4 13 56 1 0.01 0.16 0.17 dim — esn03172.19.0.3 20 56 2 0.01 0.16 0.17 dim — esn02"
},
{
"code": null,
"e": 10766,
"s": 10180,
"text": "Last response is probably the most interesting (as the above basically says we have an empty cluster :) . We can see all of the three nodes we have in our cluster (esn01–03). From node.role we can see that all nodes are of the type mdi — which means they are master-eligible (can be elected master if the current master “breaks down”), data (holds actual data ie shards and can perform CRUD/search operations) and ingest (can setup special ingest pipeline to pre-process ie transform/enrich the incoming data before actual indexing). We can also see our current master (marked with *)."
},
{
"code": null,
"e": 11194,
"s": 10766,
"text": "DEPLOYMENT: think with your devops about the best option to run in your integration/production environment — options are: standard local installation on your servers, managed-service solution Elastic Cloud or AWS Elasticsearch etc. or sort of a “middle option” mentioned earlier with deploying the docker/OCI images into some containerization platform (Kubernetes, OpenShift, Swarm) running again either on-prem or in the cloud"
},
{
"code": null,
"e": 11421,
"s": 11194,
"text": "CONFIGURATION: fundamental configuration resource is elasticsearch.yml file (located in config directory) which is present in any Elasticsearch instance — read more info on that (and other key params) in the important settings"
},
{
"code": null,
"e": 11612,
"s": 11421,
"text": "SECURITY: first...! you can go with native ES Security option or with more complex setup with some Security plugin (SearchGuard, Open Distro Security). At least have TLS and role-based auth!"
},
{
"code": null,
"e": 11943,
"s": 11612,
"text": "CLUSTERING: so distributed much fault-tolerant ... no seriously if you want to dive deeper into the clustering concepts read something about different node type ie master-eligible/data/ingest/ML and the dig into discovery modules and process (ie to find out why you should have three or more master-eligible nodes in your cluster)"
},
{
"code": null,
"e": 11993,
"s": 11943,
"text": "SIZING: read more on sizing and capacity planning"
},
{
"code": null,
"e": 12134,
"s": 11993,
"text": "DOCKER: further info on Docker setup, volumes, networks or if you are dealing with specific Elasticsearch version you can get matching image"
},
{
"code": null,
"e": 12266,
"s": 12134,
"text": "LOGGING OF ELASTICSEARCH: change logging configuration (based on log4j) in specific hierarchy etc. useful when setting the thing up"
},
{
"code": null,
"e": 12476,
"s": 12266,
"text": "LICENSING: it’s good to check under which specific licensing schema some specific desired feature falls (in this article I try to work with either pure oss under Apache 2.0 or basic-licensed stuff for testing)"
},
{
"code": null,
"e": 12565,
"s": 12476,
"text": "APIs: Elasticsearch provides a good documentation of all their REST APIs so check it out"
},
{
"code": null,
"e": 12728,
"s": 12565,
"text": "APIs: if you liked the cat API with info on your cluster (such as I do) know that there is plenty more covering nodes, shards, indices, health, segments etc. etc."
},
{
"code": null,
"e": 13291,
"s": 12728,
"text": "When you have your initial environment set up it is time to get our data to our running node(s) to be ready for searching. The basic principle of Elasticsearch is that any “unit” of our data that is put to it is called DOCUMENT. Required format of these documents is JSON. These documents are not stored individually but are grouped into specific collections that are called INDEXes. Documents in one index share similar characteristics (ie data types mappings, settings etc.), thus the index serves also as a management and API layer to the contained documents."
},
{
"code": null,
"e": 13407,
"s": 13291,
"text": "So let’s create an index with Create — Indices API and put ie index one document to it with Index — Document API..."
},
{
"code": null,
"e": 13627,
"s": 13407,
"text": "curl -X PUT \\ http://localhost:9200/test-csv \\ -H 'Content-Type: application/json' \\ -d '{ \"settings\" : { \"index\" : { \"number_of_shards\" : 3, \"number_of_replicas\" : 2 } }}'"
},
{
"code": null,
"e": 13636,
"s": 13627,
"text": "returns:"
},
{
"code": null,
"e": 13704,
"s": 13636,
"text": "{“acknowledged”:true,”shards_acknowledged”:true,”index”:”test-csv”}"
},
{
"code": null,
"e": 14742,
"s": 13704,
"text": "Index creation... checked! We have created our first index named test-csv and defined an important settings of the number of shards and replicas. Primary shards and shard replicas (in correct terms) are a way to split our index (ie document collection) into multiple pieces thus ensuring redundancy. Actual values depend (in a basic sense) on how many nodes we have. Number of shards (ie to how many units our index will be split into) is fixed with index creation. Number of replicas determines how many times the primary shard (ie each of our 3) will be “copied”. We have defined 2 as we want to achieve a state where on each node we have one primary shard (1⁄3 of our data) but also copies of other 2⁄3 of our data ie the full dataset. This setup ensures that if we loose one of our nodes we won’t loose any data. Hint: if you don’t want for starter to mess with these settings you don’t have to because if you attempt to index a document without an existing index — it gets created automatically (with default 1 shard and 1 replica)."
},
{
"code": null,
"e": 14881,
"s": 14742,
"text": "curl -X PUT \\ http://localhost:9203/test-csv/_doc/1?pretty \\ -H 'Content-Type: application/json' \\ -d '{ \"value\": \"first document\"}'"
},
{
"code": null,
"e": 14890,
"s": 14881,
"text": "returns:"
},
{
"code": null,
"e": 15129,
"s": 14890,
"text": "{ \"_index\" : \"test-csv\", \"_type\" : \"_doc\", \"_id\" : \"1\", \"_version\" : 1, \"result\" : \"created\", \"_shards\" : { \"total\" : 3, \"successful\" : 3, \"failed\" : 0 }, \"_seq_no\" : 0, \"_primary_term\" : 1}"
},
{
"code": null,
"e": 15565,
"s": 15129,
"text": "Document indexing... checked! We have indexed our first document to our test-csv index, all shards responded correctly. We have indexed a very simple json document with only one field, but you can index basically any document (from the size, depth etc perspectives) as long as it is valid JSON — but try to keep it under 100MB per doc :). Now you can easily retrieve a single document by its id with Get API. I’ll leave that up to you."
},
{
"code": null,
"e": 16013,
"s": 15565,
"text": "Now obviously you don’t want to index your documents one by one with curl. The more when you probably already have this data somewhere in your application, database or storage drive. For these purposes there are official Elasticsearch clients for various programming languages ie Java, JS, Go, Python etc. You can grab any of these based on your technology stack and use its APIs to perform indexing/deleting/updating/... actions programmatically."
},
{
"code": null,
"e": 16654,
"s": 16013,
"text": "But if you just have the data and want to quickly get them in you have two options... I took the Python client and prepared very simple CLI script that allows you to index data from given file — supporting CSV format and NDJSON format (newline delimited JSON which is often used for logging, streaming processing etc.). Take it as a possible way how to tackle your data “problem” and write something better based on your needs :). You can browse many other methods and helpers matching the Elasticsearch APIs it offers in the client docs. In any way don’t forget to pip install elasticsearch (to install the module) before using the script."
},
{
"code": null,
"e": 16697,
"s": 16654,
"text": "Code/script freely available in this repo:"
},
{
"code": null,
"e": 16708,
"s": 16697,
"text": "github.com"
},
{
"code": null,
"e": 16838,
"s": 16708,
"text": "I won’t describe the whole code contents (as it always could be written better :)), but there are two relevant parts in the code:"
},
{
"code": null,
"e": 17115,
"s": 16838,
"text": "1.It utilizes concept of Python generator as it goes line by line through the given file and yields one preprocessed element/row for the indexing execution. This “element-wise” operation was picked on purpose to ensure memory-efficiency to be able to process even large files."
},
{
"code": null,
"e": 17384,
"s": 17115,
"text": "def _csv_generator(self, es_dataset, **kwargs): with open(es_dataset.input_file) as csv_file: csv_dict_reader = csv.DictReader(csv_file) for cnt, row in enumerate(csv_dict_reader): yield self._prepare_document_for_bulk(es_dataset, row, cnt)"
},
{
"code": null,
"e": 17789,
"s": 17384,
"text": "2. On the other hand as the actual indexing operation is somewhat costly it utilizes the BULK API to index in multiple-document chunks (default 500 items) which is aligned with recommendations for tuning for speed). For this operation it uses one of the provided helpers (which are convenience abstractions on top of the raw api) by the python elasticsearch client — elasticsearch.helpers.streaming_bulk."
},
{
"code": null,
"e": 17898,
"s": 17789,
"text": "for cnt, response in enumerate(streaming_bulk(self.client, generator, chunk_size)): ok, result = response"
},
{
"code": null,
"e": 17999,
"s": 17898,
"text": "After execution it is necessary to use the refresh API to make the documents immediately searchable."
},
{
"code": null,
"e": 18059,
"s": 17999,
"text": "self.client.indices.refresh(index=es_dataset.es_index_name)"
},
{
"code": null,
"e": 18600,
"s": 18059,
"text": "From the data perspective there are wide options nowadays how to get some interesting data set (Kaggle datasets, AWS datasets or other curated lists of open datasets), but as we will want to demonstrate also some text searching capabilities let’s test/showcase our script on something from NLP area — nice collection can be found here. We can use for example Jeopardy questions dataset as it is not a usual demo dataset. Note: if you use this set also consider removal of whitespaces from the header to have more concise column/field names."
},
{
"code": null,
"e": 18721,
"s": 18600,
"text": "Now we can run following command in terminal and watch the stdout logs (for testing purposes I left the DEBUG level on):"
},
{
"code": null,
"e": 18798,
"s": 18721,
"text": "python3 load_csv_or_json_to_elasticsearch.py _data/JEOPARDY_CSV.csv test-csv"
},
{
"code": null,
"e": 18848,
"s": 18798,
"text": "In the end we should receive a following message:"
},
{
"code": null,
"e": 19100,
"s": 18848,
"text": "2019–08–18 17:03:19,013 — load_csv_or_json_to_elasticsearch.py — INFO — Script execution FINALIZED in 44.15356087684631 seconds. Dataset from file _data/JEOPARDY_CSV.csv loaded to Elasticsearch at localhost:9200. Number of documents processed: 216929."
},
{
"code": null,
"e": 19778,
"s": 19100,
"text": "The execution took 44 seconds which is not that fast, but as we are running everything on a single machine it is (must be :)) acceptable. Actually quite a bit of that is the cost of the 3+2 sharding so so for test if go just with 1+0 (and single node) we are under 25 seconds. It could probably be further improved by self-optimized management of the chunks sizing as recommended in tune for speed documentation (ie starting at 100 and then gradually increased until the speed plateau), so you can do it as an interesting exercise. On the other hand if we were to index the documents one by one we are up to beautiful 1411 seconds :), so it seems the bulk api makes some sense."
},
{
"code": null,
"e": 19864,
"s": 19778,
"text": "Now we can recheck the /_cat/indices?v API to make sure all of our data are in place."
},
{
"code": null,
"e": 20027,
"s": 19864,
"text": "INDEX MAPPING/SETTINGS: check the data structure of your index with Get Mapping API and index settings with Get Settings API — there are various settings options."
},
{
"code": null,
"e": 20229,
"s": 20027,
"text": "INDEX TEMPLATING: for usecases where similar indexes get created on an ongoing basis (ie on some time periods) it is convenient to use a predefined structure for that — this is case for Index Templates"
},
{
"code": null,
"e": 20600,
"s": 20229,
"text": "INDEX CHANGES: you can move the data between indexes with Reindex API (useful when you need to make changes in sharding — which is not possible after creation), this can be used in conjunction with Index Aliases that allow to create a “nickname” to which we can point our queries (this layer of abstraction allows to then change the indexes behind the alias more freely)"
},
{
"code": null,
"e": 20829,
"s": 20600,
"text": "ANALYSIS: when we index or full-text search the query goes through the analysis process, read more about the Analyzers and its core building blocks character filters, tokenizers, and token filters or create your custom analyzer."
},
{
"code": null,
"e": 20932,
"s": 20829,
"text": "CLIENTS: official Elasticsearch clients for various programming languages ie Java, JS, Go, Python etc."
},
{
"code": null,
"e": 21217,
"s": 20932,
"text": "DATA INGESTION: usually with time-based data (such as logs, monitoring etc.) you might consider using other tools from the Elastic Stack such a Beats (multi-purpose lightweights data shippers) or/and Logstash for more sophisticated data pre-processing before indexing to Elasticsearch"
},
{
"code": null,
"e": 21595,
"s": 21217,
"text": "MEMORY/STORAGE: if you find yourself with growing amounts of indexed data running low on disk space you might consider Index Lifecycle Management that allows based on defined rules to change or delete indices. Or/and if you are low on memory you can consider index freezing that will move various overhead data structures off the heap. Or just buy more disk space and memory :)"
},
{
"code": null,
"e": 21656,
"s": 21595,
"text": "PERFORMANCE: tune for indexing speed or efficient disk usage"
},
{
"code": null,
"e": 22009,
"s": 21656,
"text": "Now that we have indexed our data we can finally search and browse through our data. Elasticsearch uses specific JSON-based language Query DSL (Domain Specific Language) to perform various complex queries across the indexed data. As there are many options in the Query DSL world of Elasticsearch we will just go through couple and let you try the rest."
},
{
"code": null,
"e": 22304,
"s": 22009,
"text": "The simplest way to search in Elasticsearch though is without the Query DSL just providing the searched string as a query parameter in URI Search which is useful for quick curl tests as Elastic itself says :). So let’s start with that and search for documents consisting the term impressionism."
},
{
"code": null,
"e": 22366,
"s": 22304,
"text": "curl localhost:9200/test-csv/_search?q=question:impressionism"
},
{
"code": null,
"e": 22375,
"s": 22366,
"text": "returns:"
},
{
"code": null,
"e": 23191,
"s": 22375,
"text": "{ \"took\": 10, \"timed_out\": false, \"_shards\": { \"total\": 3, \"successful\": 3, \"skipped\": 0, \"failed\": 0 }, \"hits\": { \"total\": { \"value\": 4, \"relation\": \"eq\" }, \"max_score\": 13.689855, \"hits\": [(...) { \"_index\": \"test-csv\", \"_type\": \"_doc\", \"_id\": \"68959\", \"_score\": 12.518969, \"_source\": { \"show-number\": \"4943\", \"air-date\": \"2006–02–22\", \"round\": \"Double Jeopardy!\", \"category\": \"ART & ARTISTS\", \"value\": \"$1200\", \"question\": \"Impressionism got its name thanks to his painting \\\"Impression: Sunrise\\\"\", \"answer\": \"(Claude) Monet\" } }(...)"
},
{
"code": null,
"e": 23553,
"s": 23191,
"text": "We can see that the query on our 216k documents took 10ms, has gone through all 3 shards successfully and 4 documents with the given term were found. The actual results are under the hits object in hits array. For each document ie hit we have received along with the actual contents in the _source field also the _score field which is a calculation of relevance"
},
{
"code": null,
"e": 24036,
"s": 23553,
"text": "Now let’s use the Query DSL to search across multiple fields. For this purpose we will use the Multi-match query that allows exactly that. As can be seen in the linked docs there are various options to play with conditions, relevance calculation and other params. Let’s keep the topic and search for Claude Monet. We will specify the phrase as a type as we want to match both, Elasticsearch would otherwise also return documents matching only one of the terms (Claude but no Monet)."
},
{
"code": null,
"e": 24291,
"s": 24036,
"text": "curl -X GET \\ http://localhost:9203/test-csv/_search \\ -H 'Content-Type: application/json' \\ -d '{ \"query\": { \"multi_match\" : { \"query\": \"Claude Monet\", \"fields\": [ \"category\", \"question\", \"answer\" ], \"type\": \"phrase\" } }}'"
},
{
"code": null,
"e": 24300,
"s": 24291,
"text": "returns:"
},
{
"code": null,
"e": 25068,
"s": 24300,
"text": "{\"took\": 16, \"timed_out\": false, \"_shards\": { \"total\": 1, \"successful\": 1, \"skipped\": 0, \"failed\": 0 }, \"hits\": { \"total\": { \"value\": 36, \"relation\": \"eq\" }, \"max_score\": 22.763008, \"hits\": [ { \"_index\": \"test-csv\", \"_type\": \"_doc\", \"_id\": \"171125\", \"_score\": 22.763008, \"_source\": { \"show-number\": \"2918\", \"air-date\": \"1997–04–16\", \"round\": \"Jeopardy!\", \"category\": \"CROSSWORD CLUES \\\"I\\\"\", \"value\": \"$400\", \"question\": \"Claude Monet or Rich Little (13)\", \"answer\": \"Impressionist\" } },(...)"
},
{
"code": null,
"e": 25227,
"s": 25068,
"text": "We have now 36 hits and the top 10 were returned under the hits field. Btw. the first result... I wonder what would Claude say to his fellow’s impressions :)."
},
{
"code": null,
"e": 25781,
"s": 25227,
"text": "For the third query let’s go even more complex and combine the above two searches in a way that we seek again for Claude Monet (that’s a MUST) but also we value more result matching also the term impressionism (that’s a SHOULD)... The must/should stuff might seem weird to you but as we are going to use the Boolean query for our search we will be using exactly these terms. Bool query is the default from so called Compound queries that allow combining multiple leaf queries (which are the actual queries matching some field) or other compound queries."
},
{
"code": null,
"e": 26184,
"s": 25781,
"text": "curl -X GET \\ http://localhost:9202/test-csv/_search \\ -H 'Content-Type: application/json' \\ -d '{ \"query\": { \"bool\" : { \"must\" : { \"multi_match\" : { \"query\": \"Claude Monet\", \"fields\": [ \"category\", \"question\", \"answer\" ], \"type\": \"phrase\" } }, \"should\" : { \"match\" : { \"question\" : \"impressionism\" } } } }}'"
},
{
"code": null,
"e": 26193,
"s": 26184,
"text": "returns:"
},
{
"code": null,
"e": 27486,
"s": 26193,
"text": "{ \"took\": 6, \"timed_out\": false, \"_shards\": { \"total\": 3, \"successful\": 3, \"skipped\": 0, \"failed\": 0 }, \"hits\": { \"total\": { \"value\": 36, \"relation\": \"eq\" }, \"max_score\": 28.663502, \"hits\": [ { \"_index\": \"test-csv\", \"_type\": \"_doc\", \"_id\": \"68959\", \"_score\": 28.663502, \"_source\": { \"show-number\": \"4943\", \"air-date\": \"2006–02–22\", \"round\": \"Double Jeopardy!\", \"category\": \"ART & ARTISTS\", \"value\": \"$1200\", \"question\": \"Impressionism got its name thanks to his painting \\\"Impression: Sunrise\\\"\", \"answer\": \"(Claude) Monet\" } }, { \"_index\": \"test-csv\", \"_type\": \"_doc\", \"_id\": \"171125\", \"_score\": 22.763008, \"_source\": { \"show-number\": \"2918\", \"air-date\": \"1997–04–16\", \"round\": \"Jeopardy!\", \"category\": \"CROSSWORD CLUES \\\"I\\\"\", \"value\": \"$400\", \"question\": \"Claude Monet or Rich Little (13)\", \"answer\": \"Impressionist\" } },(...)"
},
{
"code": null,
"e": 27621,
"s": 27486,
"text": "We can see that we have received as a top score the original result as it is the only one matching all of our terms in the exact form."
},
{
"code": null,
"e": 27688,
"s": 27621,
"text": "QUERY DSL: check all the various options for the full-text queries"
},
{
"code": null,
"e": 27777,
"s": 27688,
"text": "QUERY CONTEXT & FILTER CONTEXT: does the document match our query vs how well it matches"
},
{
"code": null,
"e": 28014,
"s": 27777,
"text": "LEAF QUERIES & COMPOUND QUERIES: with Leaf queries look for a particular value in a particular field, such as the match, term or range queries, on the other hand with Compound queries you can wrap other compound or leaf queries together"
},
{
"code": null,
"e": 28235,
"s": 28014,
"text": "AGGREGATIONS: instead of working with the data on a “document-level” basis you can aggregate your results to different types of aggregate outcomes such as buckets, metrices, matrixes, pipelines with wide range of options"
},
{
"code": null,
"e": 28360,
"s": 28235,
"text": "COMMON OPTIONS: see the various options that can be applied to all of the REST APIs or specifically to the search query body"
},
{
"code": null,
"e": 28403,
"s": 28360,
"text": "PERFORMANCE: tune for the max search speed"
},
{
"code": null,
"e": 28645,
"s": 28403,
"text": "SCORE TUNING: you can play with relevance score with Function score query or Script score query (allowing custom script for score calc) or check out other tunning options (such as rank_feature) to make the results more relevant for your case"
},
{
"code": null,
"e": 28883,
"s": 28645,
"text": "HIGHLIGHTING & SUGGESTERS: there is plentiful of other cool features such as Completion suggester for auto-complete/search-as-you-type functionality or Highlighting for wrapping the results in html tags to emphasise where the matches are"
},
{
"code": null,
"e": 29488,
"s": 28883,
"text": "Up until now we have been interacting directly with our Elasticsearch cluster. In the first chapter via python client but later mostly with simple terminal cURL commands. cURL is fine for quick tests and putting things together but when you want to perform some data exploration with plotting, filtering etc. or need some tool for administration checks and updates on your cluster and indexes you might want to choose some more convenient UI-based app. Which is exactly what Kibana is or as Elastic puts it window to Elasticsearch. Without further ado let’s add it to our setup and see what we are up to:"
},
{
"code": null,
"e": 29622,
"s": 29488,
"text": "docker run --rm --link esn01:elasticsearch --name kibana --network elastic-network -p 5601:5601 docker.elastic.co/kibana/kibana:7.3.0"
},
{
"code": null,
"e": 30308,
"s": 29622,
"text": "The Kibana docker params are quite simple. We basically need to do two things — add Kibana to our docker network (with — network) and link it with our Elasticsearch cluster (eg. with — link pointed towards our esn01 node), we also keep the default port 5601 and pick the same version 7.3. as we are running our Elasticsearch on — must do for compatibility purposes. Note: these can also be overridden with bind-mounted custom kibana.yml or via environment variables. After it loads up you have your Kibana instance running at: http://localhost:5601 so don’t waste your time and check it out :). It will take you to your Home section and you can start browsing the Kibana neighbourhood."
},
{
"code": null,
"e": 30869,
"s": 30308,
"text": "Our goal is to start working with the data quickly so we will head straight to Management -> Index Patterns and select create our first index pattern. From the Kibana usage perspective the index patterns are likely the most important concept. They represent a logical structure over the Elasticsearch indexes and which tells Kibana what indexes (and related fields) to work with. Index pattern can match the name of a single index, or include a wildcard (*) to match multiple indices. So let’s create test-* index pattern (that shall match our test-csv index)."
},
{
"code": null,
"e": 31597,
"s": 30869,
"text": "In the next step we will select a timestamp field which will be later used for time-based filtering. This can be omitted by selecting I don’t want to use Time Filter but if you have any timestamp field in your data I recommend not to so that we can do time-series visualizations. Select Create and we are done. It will take you to the index pattern overview page where you have list of all your fields (which can be refreshed in top-right corner if you added some more fields). You can change the formats of the individual fields and you can also add new Scripted (but as Elastic recommends for performance purposes Please familiarize yourself with script fields and with scripts in aggregations before using scripted fields.)."
},
{
"code": null,
"e": 32105,
"s": 31597,
"text": "We can do other sorts of Elasticsearch administration/configuration stuff in the Kibana Management application eg. we can check out Index management section with info/actions on our indices (eg. freeze, delete, merge etc.) or setup automatic jobs and rules for Index Lifecycle Management (that will do this for us). On a last note all Kibana settings gets stored to Elasticsearch in the .kibana system indices so thanks to our docker volumes these will be preserved after restarts along with our other data."
},
{
"code": null,
"e": 32338,
"s": 32105,
"text": "The go-to section when you want to browse, query and filter your data is the Discover application (first in the left menu). When you open it you will see our default index pattern that we have created and the individual data points."
},
{
"code": null,
"e": 32352,
"s": 32338,
"text": "Here you can:"
},
{
"code": null,
"e": 32421,
"s": 32352,
"text": "filter for required time range (remember our data is from 1984–2012)"
},
{
"code": null,
"e": 32515,
"s": 32421,
"text": "filter out for required field or value (tip: use magnifier symbol next to the field or value)"
},
{
"code": null,
"e": 32601,
"s": 32515,
"text": "use Kibana Query Language to perform searches on the data ie category: STUPID ANSWERS"
},
{
"code": null,
"e": 32628,
"s": 32601,
"text": "see basic field statistics"
},
{
"code": null,
"e": 32725,
"s": 32628,
"text": "view your single document data and list other document in its context (ie from time perspective)"
},
{
"code": null,
"e": 33240,
"s": 32725,
"text": "Kibana is also useful when you’re in need to visually present your data findings or to provide interactive performance/status/metrics/KIPs overviews of the area you are dealing with. For these purposes you can create visualizations in the Kibana Visualize app and group these visualizations on rich Dashboards that can be also provided with explanatory markdowns etc. All of this is built on top of your indexed data and allows in real-time for further filtering and customizable views eg. for specific time-range."
},
{
"code": null,
"e": 33564,
"s": 33240,
"text": "As our showcase dataset is not really numeric in its nature we can’t really utilize all the options but let’s crate at least couple of document-counts visualizations and put them on a dashboard to have the sense of what it is about. So let’s go to the Visualize app (second on the left) and select Create new visualization."
},
{
"code": null,
"e": 34050,
"s": 33564,
"text": "Let’ do a count of documents (ie Questions we have in our data) grouped by year. Pick a Vertical Bar and select our test-* index pattern through which the data will be pulled. Then let’s add to Buckets and X-axis bucket with Date Histogram Aggregation, pick our air-date field and select a Yearly interval. Optionally you can drop partial buckets and in the top-right corner you should see “play arrow” button which will apply defined settings to our visualization. And... you’re done."
},
{
"code": null,
"e": 34370,
"s": 34050,
"text": "To put this on a Dashboard go to the Dashboard app (bellow Visualize) and Create new dashboard. In the top menu you have an Add option so use it to add a panel with your visualization. And... you’re done. Now you can try couple of these and I’m sure you can do much better than I did with my simple dashboard bellow :)."
},
{
"code": null,
"e": 34499,
"s": 34370,
"text": "CONFIGURATION: at some point you will find the need to change other Kibana configurations so linked is a overview of the options"
},
{
"code": null,
"e": 34702,
"s": 34499,
"text": "SECURITY: see the first What next section and check the linked resources as these are obviously must apply also for Kibana (generally there are equivalent plugins or native-capabilities also for Kibana)"
},
{
"code": null,
"e": 34931,
"s": 34702,
"text": "VISUALISATION: create a visualization in the Visualize app, put multiple visualizations together with interactive Dashboard or share even more visually customizable reports with Canvas, if you have a GeoJSON data put the on Maps"
},
{
"code": null,
"e": 35001,
"s": 34931,
"text": "SPACES: uses spaces to separate out different data areas/domains etc."
},
{
"code": null,
"e": 35206,
"s": 35001,
"text": "MONITORING: Stack Monitoring app is very useful especially when dealing with higher number of instances of the stack tools (having loads of servers with Beats deployed, multiple nodes in the cluster etc.)"
},
{
"code": null,
"e": 35328,
"s": 35206,
"text": "OTHER KIBANA APPS: there are plenty depending on your stack setup eg. Uptime used with Heartbeats for endpoint monitoring"
},
{
"code": null,
"e": 35430,
"s": 35328,
"text": "DEV TOOLS: use Dev Tools when liking the Kibana UI but still want to perform some request-based stuff"
},
{
"code": null,
"e": 35684,
"s": 35430,
"text": "CSV FILE LOAD: you can perform the same CSV/NDJSON ingestion (we have done with our Python script) via still quite new Kibana tool (still with Experimental status) File Data Visualizer that allow index data up to 100MB — very good for quick data checks."
},
{
"code": null,
"e": 35759,
"s": 35684,
"text": "SAMPLE DATA: if you just want to play with Kibana use provided sample data"
},
{
"code": null,
"e": 36014,
"s": 35759,
"text": "It wouldn’t be a full (distributed) picture without seeing a master election. You can play with these easily in Docker, but remember to put all back up afterwards:). We check who is the current master (eg. /_cat/nodes remember) and to kill it we can run:"
},
{
"code": null,
"e": 36032,
"s": 36014,
"text": "docker stop esn01"
},
{
"code": null,
"e": 36467,
"s": 36032,
"text": "This will immediately cause an exception in our cluster and initiate a master elections. Except the apparent exception (about the failed connection to the master) you can see in the logs that both nodes became candidates for the master (both are master-eligible as we already know) and execution of the elections with two candidating nodes. Everything happened under 200ms (for real life scenario also add some network overhead etc.)."
},
{
"code": null,
"e": 37671,
"s": 36467,
"text": "{“type”: “server”, “timestamp”: “2019–08–18T18:31:15,485+0000”, “level”: “INFO”, “component”: “o.e.c.s.ClusterApplierService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn02”, “cluster.uuid”: “w16btQPhSQ-iE96DSM6PnQ”, “node.id”: “yPAolS5gTxes0mcltF5WvA”, “message”: “master node changed {previous [{esn01}{EHEDowSVRMenU2BaVM442g}{thFwnNprQs-QwOx75KUbUg}{172.18.0.2}{172.18.0.2:9300}], current []}, term: 1, version: 5, reason: becoming candidate: onLeaderFailure” }(...){“type”: “server”, “timestamp”: “2019–08–18T18:31:15,626+0000”, “level”: “INFO”, “component”: “o.e.c.s.MasterService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn03”, “cluster.uuid”: “w16btQPhSQ-iE96DSM6PnQ”, “node.id”: “rLAI506ATr6lvqw-aiKgHg”, “message”: “elected-as-master ([2] nodes joined)[{esn03}{rLAI506ATr6lvqw-aiKgHg}{pf-3B_9GTGayL4KzmGkqIQ}{172.18.0.4}{172.18.0.4:9300} elect leader, {esn02}{yPAolS5gTxes0mcltF5WvA}{kadMA9eFTO2WR4v0t4aXzQ}{172.18.0.3}{172.18.0.3:9300} elect leader, _BECOME_MASTER_TASK_, _FINISH_ELECTION_], term: 2, version: 6, reason: master node changed {previous [], current [{esn03}{rLAI506ATr6lvqw-aiKgHg}{pf-3B_9GTGayL4KzmGkqIQ}{172.18.0.4}{172.18.0.4:9300}]}” }"
},
{
"code": null,
"e": 37906,
"s": 37671,
"text": "Afterwards you can request the /_cat/nodes?v again to see who is the new boss. When you’re done you can clean things up for the fresh start with docker system prune — volumes which will remove unused containers, volumes, networks etc."
}
] |
Convert DataFrame to vector in R - GeeksforGeeks
|
16 Mar, 2021
In this article, we will discuss how a dataframe can be converted to a vector in R. For the Conversion of dataframe into a vector, we can simply pass the dataframe column name as [[index]].
Approach:
We are taking a column in the dataframe and passing it into another variable by the selection method. Selection method can be defined as choosing a column from a data frame using ” [[]]”.
Create a dataframe
Apply selection process on the columns in a dataframe which is created.
Verify the resultant variable.
Syntax:
convert_data = dataframe_name[[‘column_name’]]
Given below are implementations using this approach to produce this functionality.
Example 1:
R
# creating a vector for namesnames=c('sravan','bobby','ojaswi','gnanesh','rohith','satwik') # creating vector for marks 1marks1=c(96,76,82,89,100,94) # creating vector for marks 2marks2=c(98,79,98,78,98,89) # display all detailsprint(names)print(marks1)print(marks2)print("----------------------") # passing vectors to the data frameFinal_data = data.frame(names,marks1,marks2) # display data frameprint(Final_data)print("-------------------conversion---------------------") # converting marks1 dataframe column into vector# by passing as indexconvert_data1 = Final_data[['marks1']]print(convert_data1) # converting marks2 dataframe column into vector # by passing as indexconvert_data2 = Final_data[['marks2']]print(convert_data2)
Output:
Example 2:
R
# creating a vector for subjectssubjects=c('java','python','c/c++') # creating vector for teachersteachers=c('ravi','swapna','sai') # creating vector for pass percentagepass=c(98.11,90.45,95) # display all detailsprint(subjects)print(teachers)print(pass)print("----------------------") # passing vectors to the data frameFinal_data = data.frame(subjects,teachers,pass) # display data frameprint(Final_data)print("-------------------conversion---------------------") # converting subjects dataframe column into # vector by passing as indexconvert_data1 = Final_data[['subjects']]print(convert_data1) # converting teachers dataframe column into # vector by passing as indexconvert_data2 = Final_data[['teachers']]print(convert_data2) # converting pass dataframe column into vector# by passing as indexconvert_data2 = Final_data[['pass']]print(convert_data2)
Output:
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Remove rows with NA in one column of R DataFrame
Group by function in R using Dplyr
K-Means Clustering in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
|
[
{
"code": null,
"e": 24906,
"s": 24878,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 25096,
"s": 24906,
"text": "In this article, we will discuss how a dataframe can be converted to a vector in R. For the Conversion of dataframe into a vector, we can simply pass the dataframe column name as [[index]]."
},
{
"code": null,
"e": 25106,
"s": 25096,
"text": "Approach:"
},
{
"code": null,
"e": 25294,
"s": 25106,
"text": "We are taking a column in the dataframe and passing it into another variable by the selection method. Selection method can be defined as choosing a column from a data frame using ” [[]]”."
},
{
"code": null,
"e": 25313,
"s": 25294,
"text": "Create a dataframe"
},
{
"code": null,
"e": 25385,
"s": 25313,
"text": "Apply selection process on the columns in a dataframe which is created."
},
{
"code": null,
"e": 25416,
"s": 25385,
"text": "Verify the resultant variable."
},
{
"code": null,
"e": 25424,
"s": 25416,
"text": "Syntax:"
},
{
"code": null,
"e": 25471,
"s": 25424,
"text": "convert_data = dataframe_name[[‘column_name’]]"
},
{
"code": null,
"e": 25554,
"s": 25471,
"text": "Given below are implementations using this approach to produce this functionality."
},
{
"code": null,
"e": 25565,
"s": 25554,
"text": "Example 1:"
},
{
"code": null,
"e": 25567,
"s": 25565,
"text": "R"
},
{
"code": "# creating a vector for namesnames=c('sravan','bobby','ojaswi','gnanesh','rohith','satwik') # creating vector for marks 1marks1=c(96,76,82,89,100,94) # creating vector for marks 2marks2=c(98,79,98,78,98,89) # display all detailsprint(names)print(marks1)print(marks2)print(\"----------------------\") # passing vectors to the data frameFinal_data = data.frame(names,marks1,marks2) # display data frameprint(Final_data)print(\"-------------------conversion---------------------\") # converting marks1 dataframe column into vector# by passing as indexconvert_data1 = Final_data[['marks1']]print(convert_data1) # converting marks2 dataframe column into vector # by passing as indexconvert_data2 = Final_data[['marks2']]print(convert_data2)",
"e": 26306,
"s": 25567,
"text": null
},
{
"code": null,
"e": 26314,
"s": 26306,
"text": "Output:"
},
{
"code": null,
"e": 26325,
"s": 26314,
"text": "Example 2:"
},
{
"code": null,
"e": 26327,
"s": 26325,
"text": "R"
},
{
"code": "# creating a vector for subjectssubjects=c('java','python','c/c++') # creating vector for teachersteachers=c('ravi','swapna','sai') # creating vector for pass percentagepass=c(98.11,90.45,95) # display all detailsprint(subjects)print(teachers)print(pass)print(\"----------------------\") # passing vectors to the data frameFinal_data = data.frame(subjects,teachers,pass) # display data frameprint(Final_data)print(\"-------------------conversion---------------------\") # converting subjects dataframe column into # vector by passing as indexconvert_data1 = Final_data[['subjects']]print(convert_data1) # converting teachers dataframe column into # vector by passing as indexconvert_data2 = Final_data[['teachers']]print(convert_data2) # converting pass dataframe column into vector# by passing as indexconvert_data2 = Final_data[['pass']]print(convert_data2)",
"e": 27191,
"s": 26327,
"text": null
},
{
"code": null,
"e": 27199,
"s": 27191,
"text": "Output:"
},
{
"code": null,
"e": 27206,
"s": 27199,
"text": "Picked"
},
{
"code": null,
"e": 27217,
"s": 27206,
"text": "R Language"
},
{
"code": null,
"e": 27315,
"s": 27217,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27367,
"s": 27315,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27399,
"s": 27367,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27451,
"s": 27399,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27495,
"s": 27451,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27533,
"s": 27495,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27582,
"s": 27533,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 27617,
"s": 27582,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27653,
"s": 27617,
"text": "K-Means Clustering in R Programming"
},
{
"code": null,
"e": 27711,
"s": 27653,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
How to copy or clone a C# list?
|
To copy or clone a C# list, firstly set a list −
List < string > list1 = new List < string > ();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
Now declare a string array and use the CopyTo() method to copy.
string[] arr = new string[20];
list1.CopyTo(arr);
Let us see the complete code to copy a list into a one-dimensional array.
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List < string > list1 = new List < string > ();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
Console.WriteLine("First list...");
foreach(string value in list1) {
Console.WriteLine(value);
}
string[] arr = new string[20];
list1.CopyTo(arr);
Console.WriteLine("After copy...");
foreach(string value in arr) {
Console.WriteLine(value);
}
}
}
|
[
{
"code": null,
"e": 1111,
"s": 1062,
"text": "To copy or clone a C# list, firstly set a list −"
},
{
"code": null,
"e": 1234,
"s": 1111,
"text": "List < string > list1 = new List < string > ();\nlist1.Add(\"One\");\nlist1.Add(\"Two\");\nlist1.Add(\"Three\");\nlist1.Add(\"Four\");"
},
{
"code": null,
"e": 1298,
"s": 1234,
"text": "Now declare a string array and use the CopyTo() method to copy."
},
{
"code": null,
"e": 1348,
"s": 1298,
"text": "string[] arr = new string[20];\nlist1.CopyTo(arr);"
},
{
"code": null,
"e": 1422,
"s": 1348,
"text": "Let us see the complete code to copy a list into a one-dimensional array."
},
{
"code": null,
"e": 2013,
"s": 1422,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Demo {\n public static void Main() {\n List < string > list1 = new List < string > ();\n list1.Add(\"One\");\n list1.Add(\"Two\");\n list1.Add(\"Three\");\n list1.Add(\"Four\");\n\n Console.WriteLine(\"First list...\");\n foreach(string value in list1) {\n Console.WriteLine(value);\n }\n\n string[] arr = new string[20];\n list1.CopyTo(arr);\n\n Console.WriteLine(\"After copy...\");\n\n foreach(string value in arr) {\n Console.WriteLine(value);\n }\n }\n}"
}
] |
C# | Get the number of nodes contained in LinkedList<T> - GeeksforGeeks
|
01 Feb, 2019
LinkedList<T>.Count property is used to get the number of nodes actually contained in the LinkedList<T>.
Syntax:
public int Count { get; }
Return Value: The number of nodes actually contained in the LinkedList.
Note: Retrieving the value of this property is an O(1) operation.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to get the number// of nodes actually contained// in the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast("Geeks"); myList.AddLast("for"); myList.AddLast("Data Structures"); myList.AddLast("Noida"); // To get the number of nodes actually // contained in the LinkedList if (myList.Count > 0) Console.WriteLine(myList.Count); else Console.WriteLine("LinkedList is empty"); }}
Output:
4
Example 2 :
// C# code to get the number// of nodes actually contained// in the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // To get the number of nodes actually // contained in the LinkedList if (myList.Count > 0) Console.WriteLine(myList.Count); else Console.WriteLine("LinkedList is empty"); }}
Output :
LinkedList is empty
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.count?view=netframework-4.7.2
CSharp-Generic-Namespace
CSharp-LinkedList
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
C# | Data Types
C# | Encapsulation
|
[
{
"code": null,
"e": 24514,
"s": 24486,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24619,
"s": 24514,
"text": "LinkedList<T>.Count property is used to get the number of nodes actually contained in the LinkedList<T>."
},
{
"code": null,
"e": 24627,
"s": 24619,
"text": "Syntax:"
},
{
"code": null,
"e": 24654,
"s": 24627,
"text": "public int Count { get; }\n"
},
{
"code": null,
"e": 24726,
"s": 24654,
"text": "Return Value: The number of nodes actually contained in the LinkedList."
},
{
"code": null,
"e": 24792,
"s": 24726,
"text": "Note: Retrieving the value of this property is an O(1) operation."
},
{
"code": null,
"e": 24872,
"s": 24792,
"text": "Below given are some examples to understand the implementation in a better way:"
},
{
"code": null,
"e": 24883,
"s": 24872,
"text": "Example 1:"
},
{
"code": "// C# code to get the number// of nodes actually contained// in the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast(\"Geeks\"); myList.AddLast(\"for\"); myList.AddLast(\"Data Structures\"); myList.AddLast(\"Noida\"); // To get the number of nodes actually // contained in the LinkedList if (myList.Count > 0) Console.WriteLine(myList.Count); else Console.WriteLine(\"LinkedList is empty\"); }}",
"e": 25611,
"s": 24883,
"text": null
},
{
"code": null,
"e": 25619,
"s": 25611,
"text": "Output:"
},
{
"code": null,
"e": 25622,
"s": 25619,
"text": "4\n"
},
{
"code": null,
"e": 25634,
"s": 25622,
"text": "Example 2 :"
},
{
"code": "// C# code to get the number// of nodes actually contained// in the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // To get the number of nodes actually // contained in the LinkedList if (myList.Count > 0) Console.WriteLine(myList.Count); else Console.WriteLine(\"LinkedList is empty\"); }}",
"e": 26180,
"s": 25634,
"text": null
},
{
"code": null,
"e": 26189,
"s": 26180,
"text": "Output :"
},
{
"code": null,
"e": 26210,
"s": 26189,
"text": "LinkedList is empty\n"
},
{
"code": null,
"e": 26221,
"s": 26210,
"text": "Reference:"
},
{
"code": null,
"e": 26335,
"s": 26221,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.count?view=netframework-4.7.2"
},
{
"code": null,
"e": 26360,
"s": 26335,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 26378,
"s": 26360,
"text": "CSharp-LinkedList"
},
{
"code": null,
"e": 26381,
"s": 26378,
"text": "C#"
},
{
"code": null,
"e": 26479,
"s": 26381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26497,
"s": 26479,
"text": "Destructors in C#"
},
{
"code": null,
"e": 26543,
"s": 26497,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26558,
"s": 26543,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26581,
"s": 26558,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26599,
"s": 26581,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26630,
"s": 26599,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 26652,
"s": 26630,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 26674,
"s": 26652,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26690,
"s": 26674,
"text": "C# | Data Types"
}
] |
Generate all permutation of a set in Python?
|
In mathematics, arranging all the members of a set into some order or sequence and if the set is already ordered, rearranging (reordering) its elements is called permutation.
We can generate permutation using different technique. Below are some of them,
Python comes with dedicated module for permutations and combinations called itertools.
>>> import itertools
>>>
The permutation function allows us to get permutation of N values within a list, where order matters. For example, selection N = 2 values with [1,2,3,4] is done as follows −
Permutation (order matters):
>>> print(list(itertools.permutations([1,2,3,4],2)))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
>>> print(list(itertools.combinations('1234', 2)))
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
Below is the implementation on a list without creating new intermediate lists.
def permute(xs, low=0):
if low + 1 >= len(xs):
yield xs
else:
for p in permute(xs, low + 1):
yield p
for i in range(low + 1, len(xs)):
xs[low], xs[i] = xs[i], xs[low]
for p in permute(xs, low + 1):
yield p
xs[low], xs[i] = xs[i], xs[low]
for p in permute([1, 2, 3]):
print (p)
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
import copy
def perm(prefix,rest):
for e in rest:
new_rest=copy.copy(rest)
new_prefix=copy.copy(prefix)
new_prefix.append(e)
new_rest.remove(e)
if len(new_rest) == 0:
print (new_prefix + new_rest)
continue
perm(new_prefix,new_rest)
perm([],[1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
|
[
{
"code": null,
"e": 1316,
"s": 1062,
"text": "In mathematics, arranging all the members of a set into some order or sequence and if the set is already ordered, rearranging (reordering) its elements is called permutation.\nWe can generate permutation using different technique. Below are some of them,"
},
{
"code": null,
"e": 1403,
"s": 1316,
"text": "Python comes with dedicated module for permutations and combinations called itertools."
},
{
"code": null,
"e": 1428,
"s": 1403,
"text": ">>> import itertools\n>>>"
},
{
"code": null,
"e": 1602,
"s": 1428,
"text": "The permutation function allows us to get permutation of N values within a list, where order matters. For example, selection N = 2 values with [1,2,3,4] is done as follows −"
},
{
"code": null,
"e": 1781,
"s": 1602,
"text": "Permutation (order matters):\n>>> print(list(itertools.permutations([1,2,3,4],2)))\n[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]"
},
{
"code": null,
"e": 1905,
"s": 1781,
"text": ">>> print(list(itertools.combinations('1234', 2)))\n[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]"
},
{
"code": null,
"e": 1984,
"s": 1905,
"text": "Below is the implementation on a list without creating new intermediate lists."
},
{
"code": null,
"e": 2261,
"s": 1984,
"text": "def permute(xs, low=0):\nif low + 1 >= len(xs):\nyield xs\nelse:\nfor p in permute(xs, low + 1):\nyield p\nfor i in range(low + 1, len(xs)):\nxs[low], xs[i] = xs[i], xs[low]\nfor p in permute(xs, low + 1):\nyield p\nxs[low], xs[i] = xs[i], xs[low]\nfor p in permute([1, 2, 3]):\nprint (p)"
},
{
"code": null,
"e": 2321,
"s": 2261,
"text": "[1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 2, 1]\n[3, 1, 2]"
},
{
"code": null,
"e": 2572,
"s": 2321,
"text": "import copy\ndef perm(prefix,rest):\nfor e in rest:\nnew_rest=copy.copy(rest)\nnew_prefix=copy.copy(prefix)\nnew_prefix.append(e)\nnew_rest.remove(e)\nif len(new_rest) == 0:\nprint (new_prefix + new_rest)\ncontinue\nperm(new_prefix,new_rest)\nperm([],[1, 2, 3])"
},
{
"code": null,
"e": 2632,
"s": 2572,
"text": "[1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 1, 2]\n[3, 2, 1]"
}
] |
A Swift Introduction To VegaLite.jl — StatPlots For Julia | by Emmett Boudreau | Towards Data Science
|
Data visualization is an incredibly vital technique a Data Scientist or Analyst can do to find out a lot more about their data. Visualizing your data can make correlations significantly easier to spot, and just as well can give a good idea of other aspects of data, such as variation and sample counts. Needless to say, visualizing data is pretty important when it comes to scientific computing. If there is a programming language that wants to project an ecosystem onto Data Scientists who might want to use said language, then it is likely this ecosystem will need to contain some visualization libraries. One of the youngest languages targeted at this domain is Julia.
Julia is an awesome programming language, especially for science. It has multiple dispatch, it is fast, and it is very high-level. However, one region where Julia does have some short-comings when compared with similar options is in its ecosystem. I actually talked about this a lot in another article where I discussed the problems that are facing the Julia language and its respective ecosystem. If you are interested in such reading, you may check out that article here:
towardsdatascience.com
Given that Julia does have a rather immature ecosystem, does that mean that the options for data visualization in Julia is quite limited? The first answer to that question is no, but the second answer is that even if it were to be limited — Julia is a very good friend of LLVM compiler libraries and the C programming language, which means that most often it could call on an external library in any sort of case where a Julian package is not apt for an application.
While Julia is relatively immature, and it is true that one might get some better visualization and more robust API’s using a different language, there are still some formidable options written completely in Julia. One example of such a library is Vegalite.jl. Vegalite.jl is a modulated visualization library for Julia that I would say is most likely most similar to Plot.ly... Which really is not such a bad thing —
I love Plot.ly!
Another thing worth mentioning is that Julia also now has a Plot.ly port, so you could always use Plot.ly as well. Furthermore, they even have Plot.ly Dash for Julia. If you would like to learn more about some libraries that are not Plot.ly or Vegalite.jl for the Julia language, then I would highly suggest this article, where I discuss the Plots.jl package as well as my personal favorite for Julia, Gadfly.jl:
towardsdatascience.com
One last thing, before we dive into this package, those that might want to follow along or look at the source may view such inside of this notebook:
github.com
he first thing I would like to discuss about Vegalite is how inclusive the library actually is. Just looking at the documentation’s home page, we quickly get a grandiose reveal of just how much is included inside of the Vegalite.jl package. This package can be used for so many things, and this is not just limited to plotting.
Vegalite’s biggest strength is in data. The way Vegalite handles plotting and geometry data is a more modern software-engineering approach of using JSON data as arguments in order to make plotting more data-based and less session-based. The question with this assertion is of course whether or not this brings any benefit to the package.
The first thing that should be said about this method is that it likely out-performs most of the other packages it might end up competing with. This JSON-way of doing things is certainly very effective when it comes to CPU processing at least, however I might have a concern for my memory if I used this package a lot in my work. Another thing I would like to add is that the precompile was really fast. One thing I hate about a lot of Julia modules is that precompiling can take a disturbing amount of time, Plots.jl is a great example of this. That being said, it is a pretty cool method, but also there are certainly some oddities with this methodology.
In the world of data visualization, it is convention to use certain approaches to these sorts of scenarios. For example, most language’s code for such a thing would be something akin to this:
plt = plot(feature, other_feature, arguments)
In Vegalite, however, things get a little funky. The macro @vlplot is used for just about everything. This macro returns a type, which we will take a look at when we start plotting, and this type is also dispatched to work with some pretty cool things. The power of this package really lies within the inner constructor of that type.
Now that we have an understanding of Vegalite, let us take a dive in and get some plotting done in it!
import VegaLite: @vlplot
As touched on before, there really is not a lot in this package that we will actually need to import. That in mind, I will keep my environment clean by directly importing the macro. Now let us look at a basic scatter plot example. The data we need to provide for this will be of type Array(s). We provide respective arrays for key-word arguments. Vegalite also has a bunch of data-sets one may use to download some data, so I will do that and then assign the data to a new array that is then ready to be put into our macro call.
using VegaDatasetsdata = dataset("cars")
We can then use the right bitwise operator to basically “ inject” this data into our macro and create a new plot:
data |> @vlplot(:point)
Congratulations, you have just produced your first ever VegaLite plot! Well, I am not sure if we should be calling it a plot, it is more like a bullet point. VegaLite is actually drawing all of the data that we provided to the macro, the only problem is it does not have a maximum or a minimum. Allow to elaborate, whenever graphics math is done, we need to find a perfect pixel on the screen to put a given shape. The problem is that resolutions and screen sizes are constantly different. That being said, if I put a picture of myself 30px high on a 1080p screen, or in a graphic of that size, it would not be in anywhere near the same place if we were to change to 240p.
To mitigate this, a fraction is calculated by dividing the value by the resolution to get the percentage that the pixel is of the whole. After that, the product of that percentage and the resolution or image size is subtracted from the image size, and then that is our final location for the pixel. How do I know so much about this? I actually made my own weird little graphing library, and wrote articles about it here on Medium a while ago, you may view the last update I have posted on the package, which I might pick up work on soon!
towardsdatascience.com
In order to get our VegaLite plot to actually work, we will need to add in two new key-word arguments to our macro’s call. These are just our x and y values.
data |> @vlplot(:point, x=:Miles_per_Gallon, y=:Horsepower)
The last thing I wanted to do in this quick introduction to the amazing VegaLite.jl package is just go over some basic changes one could make to their plot. I did not want to go too far into detail about everything in Vegalite because there is simply too much there, at least for one article, perhaps I will return to talking more about this package in the future.
Firstly, scatter plots are a great thing, and an amazing tool, but they are not useful in every situation, so let us change the type of plot we are working with. The first argument, and the only positional argument, the symbol point is what we will want to replace. As an example, bar:
data |> @vlplot(:bar, x=:Miles_per_Gallon, y=:Horsepower)
There are all kinds of key-words we can provide here, but to name some of them:
parameters
width
opacity
transform
There are a lot of them, so we will just be focusing on the basics, with a little bit of flare. Let us now make some new data to work with:
arm_motion_data = [(; φ1 = cos(t), φ2 = sin(t), t) for t in 0:0.01:2pi]
Now lets create some arguments. Now let us create a basic plot, I am going to be using expressions to create shapes, which is ideal for things like animation, but here I will use it out of convenience.
arm_motion_data |>VegaLite.@vlplot( width = 500, height = 500, transform = [ {calculate = "cos(datum.φ1)", as = "px1"}, {calculate = "sin(datum.φ1)", as = "py1"}, {calculate = "datum.px1 + cos(datum.φ2)", as = "px2"}, {calculate = "datum.py1 + sin(datum.φ2)", as = "py2"}, ],)
Finally, I will use the addition, +, operator in order to add on some new marks:
+VegaLite.@vlplot( mark = :rule, x = {datum = 0, scale = {domain = [0, 2.8]}}, y = {datum = 0, scale = {domain = [-1.4, 1.4]}}, x2 = "px1:q", y2 = "py1:q") +VegaLite.@vlplot(mark = :point, x = "px1:q", y = "py1:q") +VegaLite.@vlplot(mark = :rule, x = "px1:q", y = "py1:q", x2 = "px2:q", y2 = "py2:q") +VegaLite.@vlplot(mark = :point, x = "px2:q", y = "py2:q")
The whole result looks something like this:
arm_motion_data = [(; φ1 = cos(t), φ2 = sin(t), t) for t in 0:0.01:2pi]arm_motion_data |>VegaLite.@vlplot( width = 500, height = 500, transform = [ {calculate = "cos(datum.φ1)", as = "px1"}, {calculate = "sin(datum.φ1)", as = "py1"}, {calculate = "datum.px1 + cos(datum.φ2)", as = "px2"}, {calculate = "datum.py1 + sin(datum.φ2)", as = "py2"}, ],) +VegaLite.@vlplot( mark = :rule, x = {datum = 0, scale = {domain = [0, 2.8]}}, y = {datum = 0, scale = {domain = [-1.4, 1.4]}}, x2 = "px1:q", y2 = "py1:q") +VegaLite.@vlplot(mark = :point, x = "px1:q", y = "py1:q") +VegaLite.@vlplot(mark = :rule, x = "px1:q", y = "py1:q", x2 = "px2:q", y2 = "py2:q") +VegaLite.@vlplot(mark = :point, x = "px2:q", y = "py2:q")
If you use the Julia programming language, or even if you happen to just be interested in it, I would highly recommend checking out the Vegalite package. The package has all sorts of awesome features, and a really cool and interesting methodology that I have not really seen before. Thank you very much for reading, and I hope that this neat little package and article peaked your interest when it comes to visualizing data in Julia!
|
[
{
"code": null,
"e": 844,
"s": 172,
"text": "Data visualization is an incredibly vital technique a Data Scientist or Analyst can do to find out a lot more about their data. Visualizing your data can make correlations significantly easier to spot, and just as well can give a good idea of other aspects of data, such as variation and sample counts. Needless to say, visualizing data is pretty important when it comes to scientific computing. If there is a programming language that wants to project an ecosystem onto Data Scientists who might want to use said language, then it is likely this ecosystem will need to contain some visualization libraries. One of the youngest languages targeted at this domain is Julia."
},
{
"code": null,
"e": 1318,
"s": 844,
"text": "Julia is an awesome programming language, especially for science. It has multiple dispatch, it is fast, and it is very high-level. However, one region where Julia does have some short-comings when compared with similar options is in its ecosystem. I actually talked about this a lot in another article where I discussed the problems that are facing the Julia language and its respective ecosystem. If you are interested in such reading, you may check out that article here:"
},
{
"code": null,
"e": 1341,
"s": 1318,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1808,
"s": 1341,
"text": "Given that Julia does have a rather immature ecosystem, does that mean that the options for data visualization in Julia is quite limited? The first answer to that question is no, but the second answer is that even if it were to be limited — Julia is a very good friend of LLVM compiler libraries and the C programming language, which means that most often it could call on an external library in any sort of case where a Julian package is not apt for an application."
},
{
"code": null,
"e": 2226,
"s": 1808,
"text": "While Julia is relatively immature, and it is true that one might get some better visualization and more robust API’s using a different language, there are still some formidable options written completely in Julia. One example of such a library is Vegalite.jl. Vegalite.jl is a modulated visualization library for Julia that I would say is most likely most similar to Plot.ly... Which really is not such a bad thing —"
},
{
"code": null,
"e": 2242,
"s": 2226,
"text": "I love Plot.ly!"
},
{
"code": null,
"e": 2655,
"s": 2242,
"text": "Another thing worth mentioning is that Julia also now has a Plot.ly port, so you could always use Plot.ly as well. Furthermore, they even have Plot.ly Dash for Julia. If you would like to learn more about some libraries that are not Plot.ly or Vegalite.jl for the Julia language, then I would highly suggest this article, where I discuss the Plots.jl package as well as my personal favorite for Julia, Gadfly.jl:"
},
{
"code": null,
"e": 2678,
"s": 2655,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2827,
"s": 2678,
"text": "One last thing, before we dive into this package, those that might want to follow along or look at the source may view such inside of this notebook:"
},
{
"code": null,
"e": 2838,
"s": 2827,
"text": "github.com"
},
{
"code": null,
"e": 3166,
"s": 2838,
"text": "he first thing I would like to discuss about Vegalite is how inclusive the library actually is. Just looking at the documentation’s home page, we quickly get a grandiose reveal of just how much is included inside of the Vegalite.jl package. This package can be used for so many things, and this is not just limited to plotting."
},
{
"code": null,
"e": 3504,
"s": 3166,
"text": "Vegalite’s biggest strength is in data. The way Vegalite handles plotting and geometry data is a more modern software-engineering approach of using JSON data as arguments in order to make plotting more data-based and less session-based. The question with this assertion is of course whether or not this brings any benefit to the package."
},
{
"code": null,
"e": 4161,
"s": 3504,
"text": "The first thing that should be said about this method is that it likely out-performs most of the other packages it might end up competing with. This JSON-way of doing things is certainly very effective when it comes to CPU processing at least, however I might have a concern for my memory if I used this package a lot in my work. Another thing I would like to add is that the precompile was really fast. One thing I hate about a lot of Julia modules is that precompiling can take a disturbing amount of time, Plots.jl is a great example of this. That being said, it is a pretty cool method, but also there are certainly some oddities with this methodology."
},
{
"code": null,
"e": 4353,
"s": 4161,
"text": "In the world of data visualization, it is convention to use certain approaches to these sorts of scenarios. For example, most language’s code for such a thing would be something akin to this:"
},
{
"code": null,
"e": 4399,
"s": 4353,
"text": "plt = plot(feature, other_feature, arguments)"
},
{
"code": null,
"e": 4733,
"s": 4399,
"text": "In Vegalite, however, things get a little funky. The macro @vlplot is used for just about everything. This macro returns a type, which we will take a look at when we start plotting, and this type is also dispatched to work with some pretty cool things. The power of this package really lies within the inner constructor of that type."
},
{
"code": null,
"e": 4836,
"s": 4733,
"text": "Now that we have an understanding of Vegalite, let us take a dive in and get some plotting done in it!"
},
{
"code": null,
"e": 4861,
"s": 4836,
"text": "import VegaLite: @vlplot"
},
{
"code": null,
"e": 5390,
"s": 4861,
"text": "As touched on before, there really is not a lot in this package that we will actually need to import. That in mind, I will keep my environment clean by directly importing the macro. Now let us look at a basic scatter plot example. The data we need to provide for this will be of type Array(s). We provide respective arrays for key-word arguments. Vegalite also has a bunch of data-sets one may use to download some data, so I will do that and then assign the data to a new array that is then ready to be put into our macro call."
},
{
"code": null,
"e": 5431,
"s": 5390,
"text": "using VegaDatasetsdata = dataset(\"cars\")"
},
{
"code": null,
"e": 5545,
"s": 5431,
"text": "We can then use the right bitwise operator to basically “ inject” this data into our macro and create a new plot:"
},
{
"code": null,
"e": 5569,
"s": 5545,
"text": "data |> @vlplot(:point)"
},
{
"code": null,
"e": 6242,
"s": 5569,
"text": "Congratulations, you have just produced your first ever VegaLite plot! Well, I am not sure if we should be calling it a plot, it is more like a bullet point. VegaLite is actually drawing all of the data that we provided to the macro, the only problem is it does not have a maximum or a minimum. Allow to elaborate, whenever graphics math is done, we need to find a perfect pixel on the screen to put a given shape. The problem is that resolutions and screen sizes are constantly different. That being said, if I put a picture of myself 30px high on a 1080p screen, or in a graphic of that size, it would not be in anywhere near the same place if we were to change to 240p."
},
{
"code": null,
"e": 6780,
"s": 6242,
"text": "To mitigate this, a fraction is calculated by dividing the value by the resolution to get the percentage that the pixel is of the whole. After that, the product of that percentage and the resolution or image size is subtracted from the image size, and then that is our final location for the pixel. How do I know so much about this? I actually made my own weird little graphing library, and wrote articles about it here on Medium a while ago, you may view the last update I have posted on the package, which I might pick up work on soon!"
},
{
"code": null,
"e": 6803,
"s": 6780,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6961,
"s": 6803,
"text": "In order to get our VegaLite plot to actually work, we will need to add in two new key-word arguments to our macro’s call. These are just our x and y values."
},
{
"code": null,
"e": 7021,
"s": 6961,
"text": "data |> @vlplot(:point, x=:Miles_per_Gallon, y=:Horsepower)"
},
{
"code": null,
"e": 7386,
"s": 7021,
"text": "The last thing I wanted to do in this quick introduction to the amazing VegaLite.jl package is just go over some basic changes one could make to their plot. I did not want to go too far into detail about everything in Vegalite because there is simply too much there, at least for one article, perhaps I will return to talking more about this package in the future."
},
{
"code": null,
"e": 7672,
"s": 7386,
"text": "Firstly, scatter plots are a great thing, and an amazing tool, but they are not useful in every situation, so let us change the type of plot we are working with. The first argument, and the only positional argument, the symbol point is what we will want to replace. As an example, bar:"
},
{
"code": null,
"e": 7730,
"s": 7672,
"text": "data |> @vlplot(:bar, x=:Miles_per_Gallon, y=:Horsepower)"
},
{
"code": null,
"e": 7810,
"s": 7730,
"text": "There are all kinds of key-words we can provide here, but to name some of them:"
},
{
"code": null,
"e": 7821,
"s": 7810,
"text": "parameters"
},
{
"code": null,
"e": 7827,
"s": 7821,
"text": "width"
},
{
"code": null,
"e": 7835,
"s": 7827,
"text": "opacity"
},
{
"code": null,
"e": 7845,
"s": 7835,
"text": "transform"
},
{
"code": null,
"e": 7985,
"s": 7845,
"text": "There are a lot of them, so we will just be focusing on the basics, with a little bit of flare. Let us now make some new data to work with:"
},
{
"code": null,
"e": 8057,
"s": 7985,
"text": "arm_motion_data = [(; φ1 = cos(t), φ2 = sin(t), t) for t in 0:0.01:2pi]"
},
{
"code": null,
"e": 8259,
"s": 8057,
"text": "Now lets create some arguments. Now let us create a basic plot, I am going to be using expressions to create shapes, which is ideal for things like animation, but here I will use it out of convenience."
},
{
"code": null,
"e": 8576,
"s": 8259,
"text": "arm_motion_data |>VegaLite.@vlplot( width = 500, height = 500, transform = [ {calculate = \"cos(datum.φ1)\", as = \"px1\"}, {calculate = \"sin(datum.φ1)\", as = \"py1\"}, {calculate = \"datum.px1 + cos(datum.φ2)\", as = \"px2\"}, {calculate = \"datum.py1 + sin(datum.φ2)\", as = \"py2\"}, ],)"
},
{
"code": null,
"e": 8657,
"s": 8576,
"text": "Finally, I will use the addition, +, operator in order to add on some new marks:"
},
{
"code": null,
"e": 9032,
"s": 8657,
"text": "+VegaLite.@vlplot( mark = :rule, x = {datum = 0, scale = {domain = [0, 2.8]}}, y = {datum = 0, scale = {domain = [-1.4, 1.4]}}, x2 = \"px1:q\", y2 = \"py1:q\") +VegaLite.@vlplot(mark = :point, x = \"px1:q\", y = \"py1:q\") +VegaLite.@vlplot(mark = :rule, x = \"px1:q\", y = \"py1:q\", x2 = \"px2:q\", y2 = \"py2:q\") +VegaLite.@vlplot(mark = :point, x = \"px2:q\", y = \"py2:q\")"
},
{
"code": null,
"e": 9076,
"s": 9032,
"text": "The whole result looks something like this:"
},
{
"code": null,
"e": 9839,
"s": 9076,
"text": "arm_motion_data = [(; φ1 = cos(t), φ2 = sin(t), t) for t in 0:0.01:2pi]arm_motion_data |>VegaLite.@vlplot( width = 500, height = 500, transform = [ {calculate = \"cos(datum.φ1)\", as = \"px1\"}, {calculate = \"sin(datum.φ1)\", as = \"py1\"}, {calculate = \"datum.px1 + cos(datum.φ2)\", as = \"px2\"}, {calculate = \"datum.py1 + sin(datum.φ2)\", as = \"py2\"}, ],) +VegaLite.@vlplot( mark = :rule, x = {datum = 0, scale = {domain = [0, 2.8]}}, y = {datum = 0, scale = {domain = [-1.4, 1.4]}}, x2 = \"px1:q\", y2 = \"py1:q\") +VegaLite.@vlplot(mark = :point, x = \"px1:q\", y = \"py1:q\") +VegaLite.@vlplot(mark = :rule, x = \"px1:q\", y = \"py1:q\", x2 = \"px2:q\", y2 = \"py2:q\") +VegaLite.@vlplot(mark = :point, x = \"px2:q\", y = \"py2:q\")"
}
] |
Deploying Models to Production with Mlflow and Amazon Sagemaker | by Kyle Gallatin | Towards Data Science
|
Update 8/21/19: Changed arguments and some hardcoded variables to work with mlflow 1.2.0
As data science continues to mature in 2019, there is increasing demand for data scientists to move beyond the notebook. matplotlib and some performance metrics are no longer enough to deliver business value. Models need to be deployed and consumable in a scalable manner, and real-time model inference should be both fault tolerant and efficient.
Traditionally, model deployment is handled by an engineering team. Data scientists pass models to engineers for code refactoring and deployment. However, lack of standardization and good dev/ops by data scientists creates friction between the two teams, making deployment cumbersome and inefficient. As a response to this trend, the company Databricks (founded by the creators of Apache Spark) have been working on mlflow — an open source machine learning platform for model tracking, evaluation and deployment. See the introductory release post.
Mlflow plays well with managed deployment services like Amazon SageMaker or AzureML. You can even use it to build custom open-source deployment pipelines like this one at Comcast. Given the recent release of mlflow 1.0.0, I wanted to provide some minimalist guidance for data scientists on deploying and managing their own models.
For this tutorial you need:
An AWS account
Docker installed on your local machine
Python 3.6 with mlflow>=1.0.0 installed
Let’s get started.
The first thing you’ll need to do is configure the AWS CLI on your local machine so that you interact with your account programatically. Create an account here if you haven’t already, then run the commands below from a terminal.
pip install awscli --upgrade --useraws configure
The second command will prompt you for your keys and region, which you can obtain from your account when signed into the console. See the full guide here. You can also create IAM users with more specific and limited permissions if you prefer, just make sure to set the AWS_DEFAULT_PROFILE environment variable to the correct account if you have more than 1 set of credentials.
Lastly, you’ll need a role with access to SageMaker. On AWS, go to the IAM management console and create a new role. Then, attach the “AmazonSageMakerFullAccess” policy to the role, you’ll need this later to interact with SageMaker.
Follow the proper procedure for installing Docker on your OS. Then make sure you start the Docker daemon (check the fun little whale in your menu bar).
Not going to bother explaining how to install Python — we have to be beyond that right? Just make sure you’ve installed the latest mlflow with pip install mlflow. You can also run a remote mlflow server if you’re working with a team, just make sure you specify a location for mlflow to log models to (an S3 bucket). See the server command below:
mlflow server --default-artifact-root s3://bucket --host 0.0.0.0
The service should start on port 5000. Just make sure both the host you started mlflow on and your local machine have write access to the S3 bucket. If you’re just working locally, you don’t need to start mlflow.
Cool, now we’re ready to dive into the actual modeling. Mlflow let’s you log parameters and metrics which is incredibly convenient for model comparison. Creating an experiment in your code will create a directory called “mlruns” in which all the information from your experiments is stored.
Don’t hate me, but I’m going to use the iris dataset because it’s stupidly easy and the purpose here is to illustrate how mlflow plays with SageMaker. Below, we can see an example of logging our hyperparameters, metrics of model performance, and the actual model itself.
It isn’t immediately clear what’s going on, but if you open up another terminal and type mlflow ui in your current working directory, you can inspect everything we just logged in a convenient application. Mlflow allows you to filter by parameters and metrics, and look at any artifacts you may have logged like models, environments, metadata, etc...
When mlflow logs the model, it also generates a conda.yaml file. This is the environment your model needs to run, and it can be heavily customized based on your needs. There is way more you can do with mlflow models, including custom preprocessing and deep learning. The library comes with a variety of model “flavors”, so that you aren’t stuck with sklearn but can also use Pytorch or TF. Check the docs here.
Now that we’ve saved our model artifact, we need to start thinking about deployment. The first step is to provide a Docker image to Amazon’s Elastic Container Registry which we can use to serve our model. If you’re unfamiliar with Docker check out the documentation.
The mlflow Python library has functions for this part, but I was having some issues with them at time of writing so I used the CLI. Open a new terminal, and type the following into the command line:
mlflow sagemaker build-and-push-container
If you’ve set up AWS correctly with the proper permissions, this will build an image locally and push it to your image registry on AWS. To check that it worked, go to the AWS console and click the “ECR” service listed under compute in the services drop down menu. You should see a single repository called mlflow-pyfunc, and there should be one image listed inside.
Now we only have a limited amount of things left to set up before deploying our model endpoint for consumption. Basically, all we have to do is provide mlflow our image url and desired model and then we can deploy these models to SageMaker.
You’ll need is your AWS ID which you can get from the console or by typing aws sts get-caller-identity --query Account --output text into a terminal. Additionally, you’ll need the ARN for the SageMakerFullAccess role you created when setting up Amazon. Go to the IAM management console, click on the role and copy the ARN. If your models are hosted somewhere other than you’re local system, you’ll also have to edit the model path.
If your AWS credentials are set up properly, this should connect to SageMaker and deploy a model! It just may take a little bit to reach the “InService” state. Once it is, you can programmatically check to see if your model is up and running using the boto3 library or by going to the console. This code was adapted from the Databricks tutorial here.
Output should look something like below:
Application status is: InServiceReceived response: [2.0]
Now that you’re making calls to your endpoint, you can view stats on usage through the AWS console by going to the SageMaker service. There is much more you can do with SageMaker, but I’ll leave that to the numerous other tutorials available. Once you’re done playing with your new machine learning model, you can delete the endpoint.
mfs.delete(app_name=app_name, region_name=region)
And that’s it! This was a very minimal tutorial, but hopefully this gives you a glimpse into the wide variety of possibilities in terms of production grade machine learning. Remember, never release or upload AWS keys to someplace like Github — someone will steal them and mine a bunch of bitcoin on your dime. Have fun!
|
[
{
"code": null,
"e": 261,
"s": 172,
"text": "Update 8/21/19: Changed arguments and some hardcoded variables to work with mlflow 1.2.0"
},
{
"code": null,
"e": 609,
"s": 261,
"text": "As data science continues to mature in 2019, there is increasing demand for data scientists to move beyond the notebook. matplotlib and some performance metrics are no longer enough to deliver business value. Models need to be deployed and consumable in a scalable manner, and real-time model inference should be both fault tolerant and efficient."
},
{
"code": null,
"e": 1156,
"s": 609,
"text": "Traditionally, model deployment is handled by an engineering team. Data scientists pass models to engineers for code refactoring and deployment. However, lack of standardization and good dev/ops by data scientists creates friction between the two teams, making deployment cumbersome and inefficient. As a response to this trend, the company Databricks (founded by the creators of Apache Spark) have been working on mlflow — an open source machine learning platform for model tracking, evaluation and deployment. See the introductory release post."
},
{
"code": null,
"e": 1487,
"s": 1156,
"text": "Mlflow plays well with managed deployment services like Amazon SageMaker or AzureML. You can even use it to build custom open-source deployment pipelines like this one at Comcast. Given the recent release of mlflow 1.0.0, I wanted to provide some minimalist guidance for data scientists on deploying and managing their own models."
},
{
"code": null,
"e": 1515,
"s": 1487,
"text": "For this tutorial you need:"
},
{
"code": null,
"e": 1530,
"s": 1515,
"text": "An AWS account"
},
{
"code": null,
"e": 1569,
"s": 1530,
"text": "Docker installed on your local machine"
},
{
"code": null,
"e": 1609,
"s": 1569,
"text": "Python 3.6 with mlflow>=1.0.0 installed"
},
{
"code": null,
"e": 1628,
"s": 1609,
"text": "Let’s get started."
},
{
"code": null,
"e": 1857,
"s": 1628,
"text": "The first thing you’ll need to do is configure the AWS CLI on your local machine so that you interact with your account programatically. Create an account here if you haven’t already, then run the commands below from a terminal."
},
{
"code": null,
"e": 1906,
"s": 1857,
"text": "pip install awscli --upgrade --useraws configure"
},
{
"code": null,
"e": 2283,
"s": 1906,
"text": "The second command will prompt you for your keys and region, which you can obtain from your account when signed into the console. See the full guide here. You can also create IAM users with more specific and limited permissions if you prefer, just make sure to set the AWS_DEFAULT_PROFILE environment variable to the correct account if you have more than 1 set of credentials."
},
{
"code": null,
"e": 2516,
"s": 2283,
"text": "Lastly, you’ll need a role with access to SageMaker. On AWS, go to the IAM management console and create a new role. Then, attach the “AmazonSageMakerFullAccess” policy to the role, you’ll need this later to interact with SageMaker."
},
{
"code": null,
"e": 2668,
"s": 2516,
"text": "Follow the proper procedure for installing Docker on your OS. Then make sure you start the Docker daemon (check the fun little whale in your menu bar)."
},
{
"code": null,
"e": 3014,
"s": 2668,
"text": "Not going to bother explaining how to install Python — we have to be beyond that right? Just make sure you’ve installed the latest mlflow with pip install mlflow. You can also run a remote mlflow server if you’re working with a team, just make sure you specify a location for mlflow to log models to (an S3 bucket). See the server command below:"
},
{
"code": null,
"e": 3079,
"s": 3014,
"text": "mlflow server --default-artifact-root s3://bucket --host 0.0.0.0"
},
{
"code": null,
"e": 3292,
"s": 3079,
"text": "The service should start on port 5000. Just make sure both the host you started mlflow on and your local machine have write access to the S3 bucket. If you’re just working locally, you don’t need to start mlflow."
},
{
"code": null,
"e": 3583,
"s": 3292,
"text": "Cool, now we’re ready to dive into the actual modeling. Mlflow let’s you log parameters and metrics which is incredibly convenient for model comparison. Creating an experiment in your code will create a directory called “mlruns” in which all the information from your experiments is stored."
},
{
"code": null,
"e": 3854,
"s": 3583,
"text": "Don’t hate me, but I’m going to use the iris dataset because it’s stupidly easy and the purpose here is to illustrate how mlflow plays with SageMaker. Below, we can see an example of logging our hyperparameters, metrics of model performance, and the actual model itself."
},
{
"code": null,
"e": 4204,
"s": 3854,
"text": "It isn’t immediately clear what’s going on, but if you open up another terminal and type mlflow ui in your current working directory, you can inspect everything we just logged in a convenient application. Mlflow allows you to filter by parameters and metrics, and look at any artifacts you may have logged like models, environments, metadata, etc..."
},
{
"code": null,
"e": 4615,
"s": 4204,
"text": "When mlflow logs the model, it also generates a conda.yaml file. This is the environment your model needs to run, and it can be heavily customized based on your needs. There is way more you can do with mlflow models, including custom preprocessing and deep learning. The library comes with a variety of model “flavors”, so that you aren’t stuck with sklearn but can also use Pytorch or TF. Check the docs here."
},
{
"code": null,
"e": 4882,
"s": 4615,
"text": "Now that we’ve saved our model artifact, we need to start thinking about deployment. The first step is to provide a Docker image to Amazon’s Elastic Container Registry which we can use to serve our model. If you’re unfamiliar with Docker check out the documentation."
},
{
"code": null,
"e": 5081,
"s": 4882,
"text": "The mlflow Python library has functions for this part, but I was having some issues with them at time of writing so I used the CLI. Open a new terminal, and type the following into the command line:"
},
{
"code": null,
"e": 5123,
"s": 5081,
"text": "mlflow sagemaker build-and-push-container"
},
{
"code": null,
"e": 5489,
"s": 5123,
"text": "If you’ve set up AWS correctly with the proper permissions, this will build an image locally and push it to your image registry on AWS. To check that it worked, go to the AWS console and click the “ECR” service listed under compute in the services drop down menu. You should see a single repository called mlflow-pyfunc, and there should be one image listed inside."
},
{
"code": null,
"e": 5730,
"s": 5489,
"text": "Now we only have a limited amount of things left to set up before deploying our model endpoint for consumption. Basically, all we have to do is provide mlflow our image url and desired model and then we can deploy these models to SageMaker."
},
{
"code": null,
"e": 6162,
"s": 5730,
"text": "You’ll need is your AWS ID which you can get from the console or by typing aws sts get-caller-identity --query Account --output text into a terminal. Additionally, you’ll need the ARN for the SageMakerFullAccess role you created when setting up Amazon. Go to the IAM management console, click on the role and copy the ARN. If your models are hosted somewhere other than you’re local system, you’ll also have to edit the model path."
},
{
"code": null,
"e": 6513,
"s": 6162,
"text": "If your AWS credentials are set up properly, this should connect to SageMaker and deploy a model! It just may take a little bit to reach the “InService” state. Once it is, you can programmatically check to see if your model is up and running using the boto3 library or by going to the console. This code was adapted from the Databricks tutorial here."
},
{
"code": null,
"e": 6554,
"s": 6513,
"text": "Output should look something like below:"
},
{
"code": null,
"e": 6611,
"s": 6554,
"text": "Application status is: InServiceReceived response: [2.0]"
},
{
"code": null,
"e": 6946,
"s": 6611,
"text": "Now that you’re making calls to your endpoint, you can view stats on usage through the AWS console by going to the SageMaker service. There is much more you can do with SageMaker, but I’ll leave that to the numerous other tutorials available. Once you’re done playing with your new machine learning model, you can delete the endpoint."
},
{
"code": null,
"e": 6996,
"s": 6946,
"text": "mfs.delete(app_name=app_name, region_name=region)"
}
] |
C library function - strstr()
|
The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared.
Following is the declaration for strstr() function.
char *strstr(const char *haystack, const char *needle)
haystack − This is the main C string to be scanned.
haystack − This is the main C string to be scanned.
needle − This is the small string to be searched with-in haystack string.
needle − This is the small string to be searched with-in haystack string.
This function returns a pointer to the first occurrence in haystack of any of the entire sequence of characters specified in needle, or a null pointer if the sequence is not present in haystack.
The following example shows the usage of strstr() function.
#include <stdio.h>
#include <string.h>
int main () {
const char haystack[20] = "TutorialsPoint";
const char needle[10] = "Point";
char *ret;
ret = strstr(haystack, needle);
printf("The substring is: %s\n", ret);
return(0);
}
Let us compile and run the above program that will produce the following result −
The substring is: Point
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2219,
"s": 2007,
"text": "The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\\0' characters are not compared."
},
{
"code": null,
"e": 2271,
"s": 2219,
"text": "Following is the declaration for strstr() function."
},
{
"code": null,
"e": 2326,
"s": 2271,
"text": "char *strstr(const char *haystack, const char *needle)"
},
{
"code": null,
"e": 2378,
"s": 2326,
"text": "haystack − This is the main C string to be scanned."
},
{
"code": null,
"e": 2430,
"s": 2378,
"text": "haystack − This is the main C string to be scanned."
},
{
"code": null,
"e": 2504,
"s": 2430,
"text": "needle − This is the small string to be searched with-in haystack string."
},
{
"code": null,
"e": 2578,
"s": 2504,
"text": "needle − This is the small string to be searched with-in haystack string."
},
{
"code": null,
"e": 2773,
"s": 2578,
"text": "This function returns a pointer to the first occurrence in haystack of any of the entire sequence of characters specified in needle, or a null pointer if the sequence is not present in haystack."
},
{
"code": null,
"e": 2833,
"s": 2773,
"text": "The following example shows the usage of strstr() function."
},
{
"code": null,
"e": 3084,
"s": 2833,
"text": "#include <stdio.h>\n#include <string.h>\n\n\nint main () {\n const char haystack[20] = \"TutorialsPoint\";\n const char needle[10] = \"Point\";\n char *ret;\n\n ret = strstr(haystack, needle);\n\n printf(\"The substring is: %s\\n\", ret);\n \n return(0);\n}"
},
{
"code": null,
"e": 3166,
"s": 3084,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 3191,
"s": 3166,
"text": "The substring is: Point\n"
},
{
"code": null,
"e": 3224,
"s": 3191,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3239,
"s": 3224,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3274,
"s": 3239,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3289,
"s": 3274,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3324,
"s": 3289,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3338,
"s": 3324,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3371,
"s": 3338,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3389,
"s": 3371,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3424,
"s": 3389,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3443,
"s": 3424,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3476,
"s": 3443,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3488,
"s": 3476,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3495,
"s": 3488,
"text": " Print"
},
{
"code": null,
"e": 3506,
"s": 3495,
"text": " Add Notes"
}
] |
Data Visualization Using Statistical Charts by Plotly | by Himanshu Sharma | Towards Data Science
|
Data Visualization plays an important role in data analysis because as soon as the human eyes see some charts or graphs they try finding the patterns in that graph.
Data Visualization is visually representing the data using different plots/graphs/charts to find out the pattern, outliers, and relation between different attributes of a dataset. It is a graphical representation of data.
Statistical data analysis is a procedure for performing various statistical operations. It is a kind of quantitative research, which is performed on the data to find out the statistical properties of the data.
Python provides different libraries/packages for visualization like Matplotlib, Seaborn, ggplot, etc. But my personal favorite is Plotly because not only helps us visualize the data it creates highly interactive and visually appealing charts/bars/graphs etc.
A box plot helps us visualize the data and its quartile, one of the major benefits of a box plot is we can clearly identify the outliers. Let us plot a box plot, the data set used here is a Car Design Dataset which contains different attributes of car manufacturing companies.
import pandas as pdimport plotly.express as pxdf = pd.read_csv('car_design.csv')fig = px.box(df, x="body-style", y="price")fig.show()
Histograms are used to identify the approximate distribution of the data. In histograms, different bins are created and count for each bin is represented. Histograms are based on area, not the height of bars. In a histogram, it is the area of the bar that indicates the frequency of occurrences for each bin.
fig = px.histogram(df, x="city-mpg")fig.show()
Heatmap is a 2-D graphical representation of the data where represents the correlation between different data attributes and differentiates it on the basis of color.
fig = px.density_heatmap(df.corr())fig.show()
A Scatter plot is a type of visualization in which dots are used for displaying different values of two variables in a dataset. It is used to find the relationship between two variables.
fig = px.scatter(df, x="city-mpg", y="highway-mpg", trendline="ols")fig.show()
A violin plot is a statistical representation of numerical data. It is similar to a box plot, with the addition of a rotated kernel density plot on each side.
fig = px.violin(df, y="price")fig.show()
A 2D density plot or 2D histogram is an extension of the well-known histogram. It shows the distribution of values in a data set across the range of two quantitative variables. It is really useful to avoid overplotting in a scatterplot.
fig = px.density_contour(df, x="city-mpg", y="highway-mpg", marginal_x="histogram", marginal_y="histogram")fig.show()
In this article, we saw different statistical plots and how to plot them using Plotly, a python library used to visualization.
These plots will give you a basic idea behind statistical data visualization, you can change parameters accordingly and visualize data according to your requirement.
analyticsindiamag.com
towardsdatascience.com
towardsdatascience.com
Thanks for reading! If you want to get in touch with me, feel free to reach me on hmix13@gmail.com or my LinkedIn Profile. You can also view the code and data I have used here in my Github.
|
[
{
"code": null,
"e": 212,
"s": 47,
"text": "Data Visualization plays an important role in data analysis because as soon as the human eyes see some charts or graphs they try finding the patterns in that graph."
},
{
"code": null,
"e": 434,
"s": 212,
"text": "Data Visualization is visually representing the data using different plots/graphs/charts to find out the pattern, outliers, and relation between different attributes of a dataset. It is a graphical representation of data."
},
{
"code": null,
"e": 644,
"s": 434,
"text": "Statistical data analysis is a procedure for performing various statistical operations. It is a kind of quantitative research, which is performed on the data to find out the statistical properties of the data."
},
{
"code": null,
"e": 903,
"s": 644,
"text": "Python provides different libraries/packages for visualization like Matplotlib, Seaborn, ggplot, etc. But my personal favorite is Plotly because not only helps us visualize the data it creates highly interactive and visually appealing charts/bars/graphs etc."
},
{
"code": null,
"e": 1180,
"s": 903,
"text": "A box plot helps us visualize the data and its quartile, one of the major benefits of a box plot is we can clearly identify the outliers. Let us plot a box plot, the data set used here is a Car Design Dataset which contains different attributes of car manufacturing companies."
},
{
"code": null,
"e": 1314,
"s": 1180,
"text": "import pandas as pdimport plotly.express as pxdf = pd.read_csv('car_design.csv')fig = px.box(df, x=\"body-style\", y=\"price\")fig.show()"
},
{
"code": null,
"e": 1623,
"s": 1314,
"text": "Histograms are used to identify the approximate distribution of the data. In histograms, different bins are created and count for each bin is represented. Histograms are based on area, not the height of bars. In a histogram, it is the area of the bar that indicates the frequency of occurrences for each bin."
},
{
"code": null,
"e": 1670,
"s": 1623,
"text": "fig = px.histogram(df, x=\"city-mpg\")fig.show()"
},
{
"code": null,
"e": 1836,
"s": 1670,
"text": "Heatmap is a 2-D graphical representation of the data where represents the correlation between different data attributes and differentiates it on the basis of color."
},
{
"code": null,
"e": 1882,
"s": 1836,
"text": "fig = px.density_heatmap(df.corr())fig.show()"
},
{
"code": null,
"e": 2069,
"s": 1882,
"text": "A Scatter plot is a type of visualization in which dots are used for displaying different values of two variables in a dataset. It is used to find the relationship between two variables."
},
{
"code": null,
"e": 2148,
"s": 2069,
"text": "fig = px.scatter(df, x=\"city-mpg\", y=\"highway-mpg\", trendline=\"ols\")fig.show()"
},
{
"code": null,
"e": 2307,
"s": 2148,
"text": "A violin plot is a statistical representation of numerical data. It is similar to a box plot, with the addition of a rotated kernel density plot on each side."
},
{
"code": null,
"e": 2348,
"s": 2307,
"text": "fig = px.violin(df, y=\"price\")fig.show()"
},
{
"code": null,
"e": 2585,
"s": 2348,
"text": "A 2D density plot or 2D histogram is an extension of the well-known histogram. It shows the distribution of values in a data set across the range of two quantitative variables. It is really useful to avoid overplotting in a scatterplot."
},
{
"code": null,
"e": 2703,
"s": 2585,
"text": "fig = px.density_contour(df, x=\"city-mpg\", y=\"highway-mpg\", marginal_x=\"histogram\", marginal_y=\"histogram\")fig.show()"
},
{
"code": null,
"e": 2830,
"s": 2703,
"text": "In this article, we saw different statistical plots and how to plot them using Plotly, a python library used to visualization."
},
{
"code": null,
"e": 2996,
"s": 2830,
"text": "These plots will give you a basic idea behind statistical data visualization, you can change parameters accordingly and visualize data according to your requirement."
},
{
"code": null,
"e": 3018,
"s": 2996,
"text": "analyticsindiamag.com"
},
{
"code": null,
"e": 3041,
"s": 3018,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3064,
"s": 3041,
"text": "towardsdatascience.com"
}
] |
Implementing Transfer Learning from RGB to Multi-channel Imagery | by Sijuade Oguntayo | Towards Data Science
|
I very recently had the privilege and opportunity to participate in a computer vision challenge in partnership with Omdena and WeedBot, an impact-driven startup developing a laser weeding machinery for farmers to find and remove weeds with a laser beam.
We explored Image Segmentation techniques for crops vs weeds classification and explored both Semantic and Instance Segmentation approaches. In this article, we shall be exploring two distinct concepts implemented within the Semantic Segmentation part of the project —
Transfer learning is a machine learning technique for the re-use of a pre-trained model on a new problem.
In transfer learning, a machine leverages knowledge gained from a different task to improve generalization by extracting useful features from new samples for a new but related task.
For example, in training a classifier to predict a dog’s breed, one could use the knowledge gained during training to distinguish animals in general.
There are many advantages to using transfer learning. The benefits are it saves time, gives better performance, and requires much less data.
Deep learning models for Natural Language Processing and Computer Vision problems typically require huge amounts of data for the model to learn. This can both be time-consuming as well as costly and can be a huge barrier to machine learning adoption for individuals and small organizations.
Transfer Learning reduces this barrier by allowing one to take a model already trained and applying it to a different but related problem. Because the model is pre-trained, this means we are not entirely training from scratch and get to take advantage of what the model already has learned.
Provided for the challenge was 775 images with a resolution of 3008x3008. Given the small number of images, transfer learning seemed like a good path to explore.
Available publicly are open-source models trained on publicly available datasets like ResNet, AlexNet, VGG to name a few. Two such common datasets are the ImageNet and Coco datasets. These datasets consist of over 14M and 330K images respectively.
Our exploration suggested three methods we could employ to convert a model trained on 3 channels to more channels. These methods range across different levels of complexity. We shall briefly discuss the methods —
One method was to simply expand the weight dimensions to account for the additional number of channels and randomly initialize the values.
A second method is similar to the first, except rather than filling the values with randomly initialized values, we fill it with the mean of the other values. We came across this method in a scientific paper (referenced below) that described this method as working better than the first method. This is the method we shall be exploring in this article.
The final method theoretically, should offer the best performance. This method, however, would take longer with regard to training time. This method suggests that the previous methods discussed would be biased towards the first three channels since this is what the pre-trained model was originally trained on. What this method proposes instead is that we create a second parallel network that performs feature extraction on the remaining channels, we then concatenate the output with the output of the original pre-trained model. This way the second model learns the representation specific to the additional channels and we still taking advantage of using the pre-trained model as is. This method will be explored in a different article.
The backbone model chosen for this problem is ResNet50. ResNet50 short for “Residual Networks” is a 50-layer deep convolutional neural network that leverages residual learning.
It bears mentioning, one characteristic of using pre-trained models is that the model expects the input dimensions of the new task to be the same as the input dimensions of the old task it was pre-trained on.
The resnet50 model was pre-trained on an input dimension of 224x224 for the height and width, with 3 channels for RGB.
For this segmentation task, we are using a number of feature generation techniques adding an additional 12 channels to the original 3 channel RGB image. See this article for more information on how the additional channels were generated.
The challenge then was getting a pre-trained resnet50 model to take as input the new image dimension of 480x400 with 15 channels for the third dimension.
We shall be doing a code walkthrough of how this was achieved. First, we download and import the resnet50 model using Keras —
Here, we specify that we wish to download the pre-trained weights for imagenet. Typically with transfer learning, we exclude the final layer and replace it with layers more specific to the new task. Setting “include_top=False” allows us to exclude the final layer. This should be set to true if we’re making inference with the pre-trained model as opposed to implementing transfer learning.
At this point, we need to change both the resolution (height & width) from 224x224 to 480x400 and the number of channels from 3 to 15. Since changing the input height and width does not affect the dimensions of the weights, this is more straightforward to change.
Changing the number of input channels, on the other hand, does affect the dimensions of the weights. Let us look into this in more detail.
For comparison purposes, we shall be using a modified uNet architecture, we can compare the model summary for a 224x224x3 input and a 480x400x15 input by first changing the height-width, and then the number of channels.
semantic_segmentation(224, 224, 3).summary()
semantic_segmentation(400, 480, 3).summary()
We notice that the total number of parameters stays the same. This confirms that the input height and width do not affect the weight dimensions. Now, let us look into changing the number of channels —
semantic_segmentation(400, 480, 15).summary()
We see the notice the number of parameters increases from 18,515 to 20,243. we also notice this is only as a result of the parameters of the first convolutional layer increasing from 448 to 2,176 and the number of parameters for subsequent layers remain the same.
Without having to try this out in Keras, this is confirmed theoretically by recalling that the weight dimensions of a convolutional layer are determined by the height and width of the filter, the input depth, and output depth. The height and width of the image play no part in this.
The first step to changing the input dimensions involves copying the config information of the model. This gives us the composition of the model in dictionary format. We can edit this dictionary by changing the input dimensions, and create a new model with the edited config dictionary —
We have now created a new model with the same network structure as ResNet50. It is important to note that this doesn’t automatically copy over the weights of the resnet50 model which is the main point of doing this.
To do this, we would need to loop through the layers of both the resnet50 model and the newly created model and copy over the weights.
We would run into a problem, however, as the dimensions won’t match. We confirmed earlier changing the number of channels affects the dimensions of the weights. To get around this, we expand the weight dimensions to more accurately represent the increase in channels and copy over the mean of the weights. This is done as follows —
This takes care of the ResNet50 backbone of the Semantic Segmentation model.
In a different article, I discussed that while exploring Semantic Segmentation, we split into multiple teams to explore different segmentation models. While exploring PSPNet, we noticed that while the model wasn’t completely accurate, it produced smooth segmentations.
We theorized that this might be as a result of the Pyramid Pooling Module leveraged by the model. For the final model. we resolved to use this in combination with resnet50 as the backbone.
The pyramid pooling works by observing the whole feature map with sub-regions in different locations. The pooling kernel covers the whole, half of, 1/4th, and 1/8th of the image and is fused as the global prior. This is then combined with the original feature map from the backbone.
Lin T, Maire M, Belongie S, Bourdev L, Girshick R, Hays J, Perona P, Ramanan D, Zitnick L, Dollár P 2014 Microsoft COCO: Common Objects in Context https://arxiv.org/abs/1405.0312
Jia Deng; Wei Dong; Richard Socher; Li-Jia Li; Kai Li; Li Fei-Fei 2009 ImageNet: A large-scale hierarchical image database https://ieeexplore.ieee.org/document/5206848
Donges N 2019 WHAT IS TRANSFER LEARNING? EXPLORING THE POPULAR DEEP LEARNING APPROACH https://builtin.com/data-science/transfer-learning
He K, Zhang X, Ren S, Sun J 2015 Deep Residual Learning for Image Recognition https://arxiv.org/pdf/1512.03385.pdf
Zhao et al 2016 Pyramid Pooling Module https://arxiv.org/abs/1612.01105v2
|
[
{
"code": null,
"e": 426,
"s": 172,
"text": "I very recently had the privilege and opportunity to participate in a computer vision challenge in partnership with Omdena and WeedBot, an impact-driven startup developing a laser weeding machinery for farmers to find and remove weeds with a laser beam."
},
{
"code": null,
"e": 695,
"s": 426,
"text": "We explored Image Segmentation techniques for crops vs weeds classification and explored both Semantic and Instance Segmentation approaches. In this article, we shall be exploring two distinct concepts implemented within the Semantic Segmentation part of the project —"
},
{
"code": null,
"e": 801,
"s": 695,
"text": "Transfer learning is a machine learning technique for the re-use of a pre-trained model on a new problem."
},
{
"code": null,
"e": 983,
"s": 801,
"text": "In transfer learning, a machine leverages knowledge gained from a different task to improve generalization by extracting useful features from new samples for a new but related task."
},
{
"code": null,
"e": 1133,
"s": 983,
"text": "For example, in training a classifier to predict a dog’s breed, one could use the knowledge gained during training to distinguish animals in general."
},
{
"code": null,
"e": 1274,
"s": 1133,
"text": "There are many advantages to using transfer learning. The benefits are it saves time, gives better performance, and requires much less data."
},
{
"code": null,
"e": 1565,
"s": 1274,
"text": "Deep learning models for Natural Language Processing and Computer Vision problems typically require huge amounts of data for the model to learn. This can both be time-consuming as well as costly and can be a huge barrier to machine learning adoption for individuals and small organizations."
},
{
"code": null,
"e": 1856,
"s": 1565,
"text": "Transfer Learning reduces this barrier by allowing one to take a model already trained and applying it to a different but related problem. Because the model is pre-trained, this means we are not entirely training from scratch and get to take advantage of what the model already has learned."
},
{
"code": null,
"e": 2018,
"s": 1856,
"text": "Provided for the challenge was 775 images with a resolution of 3008x3008. Given the small number of images, transfer learning seemed like a good path to explore."
},
{
"code": null,
"e": 2266,
"s": 2018,
"text": "Available publicly are open-source models trained on publicly available datasets like ResNet, AlexNet, VGG to name a few. Two such common datasets are the ImageNet and Coco datasets. These datasets consist of over 14M and 330K images respectively."
},
{
"code": null,
"e": 2479,
"s": 2266,
"text": "Our exploration suggested three methods we could employ to convert a model trained on 3 channels to more channels. These methods range across different levels of complexity. We shall briefly discuss the methods —"
},
{
"code": null,
"e": 2618,
"s": 2479,
"text": "One method was to simply expand the weight dimensions to account for the additional number of channels and randomly initialize the values."
},
{
"code": null,
"e": 2971,
"s": 2618,
"text": "A second method is similar to the first, except rather than filling the values with randomly initialized values, we fill it with the mean of the other values. We came across this method in a scientific paper (referenced below) that described this method as working better than the first method. This is the method we shall be exploring in this article."
},
{
"code": null,
"e": 3711,
"s": 2971,
"text": "The final method theoretically, should offer the best performance. This method, however, would take longer with regard to training time. This method suggests that the previous methods discussed would be biased towards the first three channels since this is what the pre-trained model was originally trained on. What this method proposes instead is that we create a second parallel network that performs feature extraction on the remaining channels, we then concatenate the output with the output of the original pre-trained model. This way the second model learns the representation specific to the additional channels and we still taking advantage of using the pre-trained model as is. This method will be explored in a different article."
},
{
"code": null,
"e": 3888,
"s": 3711,
"text": "The backbone model chosen for this problem is ResNet50. ResNet50 short for “Residual Networks” is a 50-layer deep convolutional neural network that leverages residual learning."
},
{
"code": null,
"e": 4097,
"s": 3888,
"text": "It bears mentioning, one characteristic of using pre-trained models is that the model expects the input dimensions of the new task to be the same as the input dimensions of the old task it was pre-trained on."
},
{
"code": null,
"e": 4216,
"s": 4097,
"text": "The resnet50 model was pre-trained on an input dimension of 224x224 for the height and width, with 3 channels for RGB."
},
{
"code": null,
"e": 4454,
"s": 4216,
"text": "For this segmentation task, we are using a number of feature generation techniques adding an additional 12 channels to the original 3 channel RGB image. See this article for more information on how the additional channels were generated."
},
{
"code": null,
"e": 4608,
"s": 4454,
"text": "The challenge then was getting a pre-trained resnet50 model to take as input the new image dimension of 480x400 with 15 channels for the third dimension."
},
{
"code": null,
"e": 4734,
"s": 4608,
"text": "We shall be doing a code walkthrough of how this was achieved. First, we download and import the resnet50 model using Keras —"
},
{
"code": null,
"e": 5125,
"s": 4734,
"text": "Here, we specify that we wish to download the pre-trained weights for imagenet. Typically with transfer learning, we exclude the final layer and replace it with layers more specific to the new task. Setting “include_top=False” allows us to exclude the final layer. This should be set to true if we’re making inference with the pre-trained model as opposed to implementing transfer learning."
},
{
"code": null,
"e": 5389,
"s": 5125,
"text": "At this point, we need to change both the resolution (height & width) from 224x224 to 480x400 and the number of channels from 3 to 15. Since changing the input height and width does not affect the dimensions of the weights, this is more straightforward to change."
},
{
"code": null,
"e": 5528,
"s": 5389,
"text": "Changing the number of input channels, on the other hand, does affect the dimensions of the weights. Let us look into this in more detail."
},
{
"code": null,
"e": 5748,
"s": 5528,
"text": "For comparison purposes, we shall be using a modified uNet architecture, we can compare the model summary for a 224x224x3 input and a 480x400x15 input by first changing the height-width, and then the number of channels."
},
{
"code": null,
"e": 5793,
"s": 5748,
"text": "semantic_segmentation(224, 224, 3).summary()"
},
{
"code": null,
"e": 5838,
"s": 5793,
"text": "semantic_segmentation(400, 480, 3).summary()"
},
{
"code": null,
"e": 6039,
"s": 5838,
"text": "We notice that the total number of parameters stays the same. This confirms that the input height and width do not affect the weight dimensions. Now, let us look into changing the number of channels —"
},
{
"code": null,
"e": 6085,
"s": 6039,
"text": "semantic_segmentation(400, 480, 15).summary()"
},
{
"code": null,
"e": 6349,
"s": 6085,
"text": "We see the notice the number of parameters increases from 18,515 to 20,243. we also notice this is only as a result of the parameters of the first convolutional layer increasing from 448 to 2,176 and the number of parameters for subsequent layers remain the same."
},
{
"code": null,
"e": 6632,
"s": 6349,
"text": "Without having to try this out in Keras, this is confirmed theoretically by recalling that the weight dimensions of a convolutional layer are determined by the height and width of the filter, the input depth, and output depth. The height and width of the image play no part in this."
},
{
"code": null,
"e": 6920,
"s": 6632,
"text": "The first step to changing the input dimensions involves copying the config information of the model. This gives us the composition of the model in dictionary format. We can edit this dictionary by changing the input dimensions, and create a new model with the edited config dictionary —"
},
{
"code": null,
"e": 7136,
"s": 6920,
"text": "We have now created a new model with the same network structure as ResNet50. It is important to note that this doesn’t automatically copy over the weights of the resnet50 model which is the main point of doing this."
},
{
"code": null,
"e": 7271,
"s": 7136,
"text": "To do this, we would need to loop through the layers of both the resnet50 model and the newly created model and copy over the weights."
},
{
"code": null,
"e": 7603,
"s": 7271,
"text": "We would run into a problem, however, as the dimensions won’t match. We confirmed earlier changing the number of channels affects the dimensions of the weights. To get around this, we expand the weight dimensions to more accurately represent the increase in channels and copy over the mean of the weights. This is done as follows —"
},
{
"code": null,
"e": 7680,
"s": 7603,
"text": "This takes care of the ResNet50 backbone of the Semantic Segmentation model."
},
{
"code": null,
"e": 7949,
"s": 7680,
"text": "In a different article, I discussed that while exploring Semantic Segmentation, we split into multiple teams to explore different segmentation models. While exploring PSPNet, we noticed that while the model wasn’t completely accurate, it produced smooth segmentations."
},
{
"code": null,
"e": 8138,
"s": 7949,
"text": "We theorized that this might be as a result of the Pyramid Pooling Module leveraged by the model. For the final model. we resolved to use this in combination with resnet50 as the backbone."
},
{
"code": null,
"e": 8421,
"s": 8138,
"text": "The pyramid pooling works by observing the whole feature map with sub-regions in different locations. The pooling kernel covers the whole, half of, 1/4th, and 1/8th of the image and is fused as the global prior. This is then combined with the original feature map from the backbone."
},
{
"code": null,
"e": 8601,
"s": 8421,
"text": "Lin T, Maire M, Belongie S, Bourdev L, Girshick R, Hays J, Perona P, Ramanan D, Zitnick L, Dollár P 2014 Microsoft COCO: Common Objects in Context https://arxiv.org/abs/1405.0312"
},
{
"code": null,
"e": 8769,
"s": 8601,
"text": "Jia Deng; Wei Dong; Richard Socher; Li-Jia Li; Kai Li; Li Fei-Fei 2009 ImageNet: A large-scale hierarchical image database https://ieeexplore.ieee.org/document/5206848"
},
{
"code": null,
"e": 8906,
"s": 8769,
"text": "Donges N 2019 WHAT IS TRANSFER LEARNING? EXPLORING THE POPULAR DEEP LEARNING APPROACH https://builtin.com/data-science/transfer-learning"
},
{
"code": null,
"e": 9021,
"s": 8906,
"text": "He K, Zhang X, Ren S, Sun J 2015 Deep Residual Learning for Image Recognition https://arxiv.org/pdf/1512.03385.pdf"
}
] |
Output of C programs | Set 65 (If-Else) - GeeksforGeeks
|
07 Sep, 2021
Prerequisite : Decision making in CQuestion 1
C
#include"stdio.h"#include"stdlib.h"void reverse(int i){ if (i > 5) exit(0); printf("%d\n", i); return reverse(i++);}int main(){ reverse(1);}
OPTIONS: a)Segmenation fault b)Compilation error c)Print 1 Infinite time d)Both a & c
OUTPUT: (d)Both a & c
Explanation: We call the main method again and again by 1 because we use post-increment. At certain time stack frame will full means segmentation fault occurs.Question 2
C
#include"stdio.h"int main(){ if(-1L>1UL) printf("paul is crazy"); else printf("mannu is Crazy");}
OPTIONS: a)mannu is Crazy b)paul is crazy
OUTPUT: (b)paul is crazy
Explanation: Here ,comparison between long int and unsigned long int generally which is not possible. Now,long int is promoted to unsigned long int whose value will be (2^size_of_unsigned_long_int)-1.Question 3
C
#include"stdio.h"int main(){ int i; if(i=0,2,3) printf("Geeksforgeeks "); else printf("Hello "); printf("%d\n",i);}
OPTIONS: a)Hello 3 b)Hello 0 c)Geeksforgeeks 0 d)Geeksforgeeks 3
OUTPUT: (c) Geeksforgeeks 0
Explanation: At first zero will assign in ‘i’ then comma operator returns the last value which is 3 and condition becomes true.Question 4
CPP
#include"stdio.h"int main(){ int i; if(i=(2,1,0)) printf("Geeksforgeeks "); else printf("Hello "); printf("%d\n",i);}
OPTIONS: a)Hello 3 b)Geeksforgeeks 0 c)Hello 0 d)Geeksforgeeks 3
OUTPUT: (c) Hello 0
Explanation: Priority of parenthesis bracket is greater than equal to(=) operator , So atfirst comma operator return the last value which is zero(0) and then equal to(=) operator assign 0 to ‘i’ and condition becomes false.Question 5
C
#include"stdio.h"int main(){ float a=0.7d; if(a<0.7) printf("C"); else printf("C++"); return 0;}
OPTIONS: a)Compilation error b)C++ c)C
OUTPUT: (C)C
Explanation: a = 0.7 is rounded to 0.699999988 and the constant 0.7 is as 0.69999999999 so a<0.7 is true so it print “c” but in case of 0.8 a = 0.800000011 and constant 0.8 is 0.8000000000000000 This article is contributed by Abhishek kurmi. 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.
Avesh_Agrawal
Akanksha_Rai
sumitgumber28
C Basics
Program Output
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to copy a string in C/C++
Output of Python Program | Set 1
Runtime Errors
Output of python program | Set 2
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Python Dictionary
Inheritance in C++
Overriding in Java
Arrays in C/C++
Copy Constructor in C++
|
[
{
"code": null,
"e": 24245,
"s": 24217,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 24293,
"s": 24245,
"text": "Prerequisite : Decision making in CQuestion 1 "
},
{
"code": null,
"e": 24295,
"s": 24293,
"text": "C"
},
{
"code": "#include\"stdio.h\"#include\"stdlib.h\"void reverse(int i){ if (i > 5) exit(0); printf(\"%d\\n\", i); return reverse(i++);}int main(){ reverse(1);}",
"e": 24458,
"s": 24295,
"text": null
},
{
"code": null,
"e": 24545,
"s": 24458,
"text": "OPTIONS: a)Segmenation fault b)Compilation error c)Print 1 Infinite time d)Both a & c "
},
{
"code": null,
"e": 24568,
"s": 24545,
"text": "OUTPUT: (d)Both a & c"
},
{
"code": null,
"e": 24740,
"s": 24568,
"text": "Explanation: We call the main method again and again by 1 because we use post-increment. At certain time stack frame will full means segmentation fault occurs.Question 2 "
},
{
"code": null,
"e": 24742,
"s": 24740,
"text": "C"
},
{
"code": "#include\"stdio.h\"int main(){ if(-1L>1UL) printf(\"paul is crazy\"); else printf(\"mannu is Crazy\");}",
"e": 24860,
"s": 24742,
"text": null
},
{
"code": null,
"e": 24904,
"s": 24860,
"text": "OPTIONS: a)mannu is Crazy b)paul is crazy "
},
{
"code": null,
"e": 24931,
"s": 24904,
"text": "OUTPUT: (b)paul is crazy "
},
{
"code": null,
"e": 25144,
"s": 24931,
"text": "Explanation: Here ,comparison between long int and unsigned long int generally which is not possible. Now,long int is promoted to unsigned long int whose value will be (2^size_of_unsigned_long_int)-1.Question 3 "
},
{
"code": null,
"e": 25146,
"s": 25144,
"text": "C"
},
{
"code": "#include\"stdio.h\"int main(){ int i; if(i=0,2,3) printf(\"Geeksforgeeks \"); else printf(\"Hello \"); printf(\"%d\\n\",i);}",
"e": 25288,
"s": 25146,
"text": null
},
{
"code": null,
"e": 25354,
"s": 25288,
"text": "OPTIONS: a)Hello 3 b)Hello 0 c)Geeksforgeeks 0 d)Geeksforgeeks 3 "
},
{
"code": null,
"e": 25383,
"s": 25354,
"text": "OUTPUT: (c) Geeksforgeeks 0"
},
{
"code": null,
"e": 25523,
"s": 25383,
"text": "Explanation: At first zero will assign in ‘i’ then comma operator returns the last value which is 3 and condition becomes true.Question 4 "
},
{
"code": null,
"e": 25527,
"s": 25523,
"text": "CPP"
},
{
"code": "#include\"stdio.h\"int main(){ int i; if(i=(2,1,0)) printf(\"Geeksforgeeks \"); else printf(\"Hello \"); printf(\"%d\\n\",i);}",
"e": 25671,
"s": 25527,
"text": null
},
{
"code": null,
"e": 25737,
"s": 25671,
"text": "OPTIONS: a)Hello 3 b)Geeksforgeeks 0 c)Hello 0 d)Geeksforgeeks 3 "
},
{
"code": null,
"e": 25758,
"s": 25737,
"text": "OUTPUT: (c) Hello 0"
},
{
"code": null,
"e": 25994,
"s": 25758,
"text": "Explanation: Priority of parenthesis bracket is greater than equal to(=) operator , So atfirst comma operator return the last value which is zero(0) and then equal to(=) operator assign 0 to ‘i’ and condition becomes false.Question 5 "
},
{
"code": null,
"e": 25996,
"s": 25994,
"text": "C"
},
{
"code": "#include\"stdio.h\"int main(){ float a=0.7d; if(a<0.7) printf(\"C\"); else printf(\"C++\"); return 0;}",
"e": 26125,
"s": 25996,
"text": null
},
{
"code": null,
"e": 26165,
"s": 26125,
"text": "OPTIONS: a)Compilation error b)C++ c)C "
},
{
"code": null,
"e": 26180,
"s": 26165,
"text": "OUTPUT: (C)C "
},
{
"code": null,
"e": 26798,
"s": 26180,
"text": "Explanation: a = 0.7 is rounded to 0.699999988 and the constant 0.7 is as 0.69999999999 so a<0.7 is true so it print “c” but in case of 0.8 a = 0.800000011 and constant 0.8 is 0.8000000000000000 This article is contributed by Abhishek kurmi. 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": 26812,
"s": 26798,
"text": "Avesh_Agrawal"
},
{
"code": null,
"e": 26825,
"s": 26812,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26839,
"s": 26825,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26848,
"s": 26839,
"text": "C Basics"
},
{
"code": null,
"e": 26863,
"s": 26848,
"text": "Program Output"
},
{
"code": null,
"e": 26882,
"s": 26863,
"text": "School Programming"
},
{
"code": null,
"e": 26980,
"s": 26882,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26989,
"s": 26980,
"text": "Comments"
},
{
"code": null,
"e": 27002,
"s": 26989,
"text": "Old Comments"
},
{
"code": null,
"e": 27043,
"s": 27002,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 27076,
"s": 27043,
"text": "Output of Python Program | Set 1"
},
{
"code": null,
"e": 27091,
"s": 27076,
"text": "Runtime Errors"
},
{
"code": null,
"e": 27124,
"s": 27091,
"text": "Output of python program | Set 2"
},
{
"code": null,
"e": 27220,
"s": 27124,
"text": "error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++"
},
{
"code": null,
"e": 27238,
"s": 27220,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27257,
"s": 27238,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27276,
"s": 27257,
"text": "Overriding in Java"
},
{
"code": null,
"e": 27292,
"s": 27276,
"text": "Arrays in C/C++"
}
] |
Python | Multiply Integer in Mixed List of string and numbers - GeeksforGeeks
|
11 Dec, 2019
Sometimes, while working with Python, we can come across a problem in which we require to find the product of list. This problem is easier to solve. But this can get complex in case we have mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using Type casting + Exception HandlingWe can employ a brute force method to type caste each element and catch the exception if any occurs. This can ensure that only integers are multiplied to product and hence can solve the problem.
# Python3 code to demonstrate working of# Mixed List Integer Multiplication# using type caste and exception handling # initializing listtest_list = [5, 8, "gfg", 8, (5, 7), 'is', 2] # printing original listprint("The original list is : " + str(test_list)) # Mixed List Integer Multiplication# using type caste and exception handlingres = 1for ele in test_list: try: res *= int(ele) except : pass # printing result print("Product of integers in list : " + str(res))
The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640
Method #2 : Using loop + isinstance()This is brute force way in which this task can be performed. In this, we run a loop over all the elements and perform multiplication only when we find an integer using isinstance().
# Python3 code to demonstrate working of# Mixed List Integer Multiplication# using loop + isinstance() # initializing listtest_list = [5, 8, "gfg", 8, (5, 7), 'is', 2] # printing original listprint("The original list is : " + str(test_list)) # Mixed List Integer Multiplication# using loop + isinstance()res = 1for ele in test_list: if(isinstance(ele, int)): res *= ele # printing result print("Product of integers in list : " + str(res))
The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24149,
"s": 24121,
"text": "\n11 Dec, 2019"
},
{
"code": null,
"e": 24446,
"s": 24149,
"text": "Sometimes, while working with Python, we can come across a problem in which we require to find the product of list. This problem is easier to solve. But this can get complex in case we have mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24692,
"s": 24446,
"text": "Method #1 : Using Type casting + Exception HandlingWe can employ a brute force method to type caste each element and catch the exception if any occurs. This can ensure that only integers are multiplied to product and hence can solve the problem."
},
{
"code": "# Python3 code to demonstrate working of# Mixed List Integer Multiplication# using type caste and exception handling # initializing listtest_list = [5, 8, \"gfg\", 8, (5, 7), 'is', 2] # printing original listprint(\"The original list is : \" + str(test_list)) # Mixed List Integer Multiplication# using type caste and exception handlingres = 1for ele in test_list: try: res *= int(ele) except : pass # printing result print(\"Product of integers in list : \" + str(res))",
"e": 25181,
"s": 24692,
"text": null
},
{
"code": null,
"e": 25273,
"s": 25181,
"text": "The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]\nProduct of integers in list : 640\n"
},
{
"code": null,
"e": 25494,
"s": 25275,
"text": "Method #2 : Using loop + isinstance()This is brute force way in which this task can be performed. In this, we run a loop over all the elements and perform multiplication only when we find an integer using isinstance()."
},
{
"code": "# Python3 code to demonstrate working of# Mixed List Integer Multiplication# using loop + isinstance() # initializing listtest_list = [5, 8, \"gfg\", 8, (5, 7), 'is', 2] # printing original listprint(\"The original list is : \" + str(test_list)) # Mixed List Integer Multiplication# using loop + isinstance()res = 1for ele in test_list: if(isinstance(ele, int)): res *= ele # printing result print(\"Product of integers in list : \" + str(res))",
"e": 25947,
"s": 25494,
"text": null
},
{
"code": null,
"e": 26039,
"s": 25947,
"text": "The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]\nProduct of integers in list : 640\n"
},
{
"code": null,
"e": 26060,
"s": 26039,
"text": "Python list-programs"
},
{
"code": null,
"e": 26067,
"s": 26060,
"text": "Python"
},
{
"code": null,
"e": 26083,
"s": 26067,
"text": "Python Programs"
},
{
"code": null,
"e": 26181,
"s": 26083,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26190,
"s": 26181,
"text": "Comments"
},
{
"code": null,
"e": 26203,
"s": 26190,
"text": "Old Comments"
},
{
"code": null,
"e": 26221,
"s": 26203,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26256,
"s": 26221,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26278,
"s": 26256,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26310,
"s": 26278,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26340,
"s": 26310,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26362,
"s": 26340,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26401,
"s": 26362,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26447,
"s": 26401,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26504,
"s": 26447,
"text": "Python program to check whether a number is Prime or not"
}
] |
Check if a given graph is Bipartite using DFS - GeeksforGeeks
|
09 Feb, 2022
Given a connected graph, check if the graph is bipartite or not. A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with an even cycle using two colors. For example, see the following graph.
It is not possible to color a cycle graph with an odd cycle using two colors.
In the previous post, an approach using BFS has been discussed. In this post, an approach using DFS has been implemented.
Given below is the algorithm to check for bipartiteness of a graph.
Use a color[] array which stores 0 or 1 for every node which denotes opposite colors.
Call the function DFS from any node.
If the node u has not been visited previously, then assign !color[v] to color[u] and call DFS again to visit nodes connected to u.
If at any point, color[u] is equal to color[v], then the node is not bipartite.
Modify the DFS function such that it returns a boolean value at the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if a connected// graph is bipartite or not using DFS#include <bits/stdc++.h>using namespace std; // function to store the connected nodesvoid addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // function to check whether a graph is bipartite or notbool isBipartite(vector<int> adj[], int v, vector<bool>& visited, vector<int>& color){ for (int u : adj[v]) { // if vertex u is not explored before if (visited[u] == false) { // mark present vertic as visited visited[u] = true; // mark its color opposite to its parent color[u] = !color[v]; // if the subtree rooted at vertex v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // if two adjacent are colored with same color then // the graph is not bipartite else if (color[u] == color[v]) return false; } return true;} // Driver Codeint main(){ // no of nodes int N = 6; // to maintain the adjacency list of graph vector<int> adj[N + 1]; // to keep a check on whether // a node is discovered or not vector<bool> visited(N + 1); // to color the vertices // of graph with 2 color vector<int> color(N + 1); // adding edges to the graph addEdge(adj, 1, 2); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 4, 5); addEdge(adj, 5, 6); addEdge(adj, 6, 1); // marking the source node as visited visited[1] = true; // marking the source node with a color color[1] = 0; // Function to check if the graph // is Bipartite or not if (isBipartite(adj, 1, visited, color)) { cout << "Graph is Bipartite"; } else { cout << "Graph is not Bipartite"; } return 0;}
// Java program to check if a connected// graph is bipartite or not using DFSimport java.util.*; class GFG{ // Function to store the connected nodesstatic void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v){ adj.get(u).add(v); adj.get(v).add(u);} // Function to check whether a// graph is bipartite or notstatic boolean isBipartite(ArrayList<ArrayList<Integer>> adj, int v, boolean visited[], int color[]){ for(int u : adj.get(v)) { // If vertex u is not explored before if (visited[u] == false) { // Mark present vertic as visited visited[u] = true; // Mark its color opposite to its parent color[u] = 1 - color[v]; // If the subtree rooted at vertex // v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // If two adjacent are colored with // same color then the graph is // not bipartite else if (color[u] == color[v]) return false; } return true;} // Driver Codepublic static void main(String args[]){ // No of nodes int N = 6; // To maintain the adjacency list of graph ArrayList< ArrayList<Integer>> adj = new ArrayList< ArrayList<Integer>>(N + 1); // Initialize all the vertex for(int i = 0; i <= N; i++) { adj.add(new ArrayList<Integer>()); } // To keep a check on whether // a node is discovered or not boolean visited[] = new boolean[N + 1]; // To color the vertices // of graph with 2 color int color[] = new int[N + 1]; // The value '-1' of colorArr[i] is // used to indicate that no color is // assigned to vertex 'i'. The value // 1 is used to indicate first color // is assigned and value 0 indicates // second color is assigned. Arrays.fill(color, -1); // Adding edges to the graph addEdge(adj, 1, 2); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 4, 5); addEdge(adj, 5, 6); addEdge(adj, 6, 1); // Marking the source node as visited visited[1] = true; // Marking the source node with a color color[1] = 0; // Function to check if the graph // is Bipartite or not if (isBipartite(adj, 1, visited, color)) { System.out.println("Graph is Bipartite"); } else { System.out.println("Graph is not Bipartite"); }}} // This code is contributed by adityapande88
# Python3 program to check if a connected# graph is bipartite or not using DFS # Function to store the connected nodesdef addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # Function to check whether a graph is# bipartite or notdef isBipartite(adj, v, visited, color): for u in adj[v]: # If vertex u is not explored before if (visited[u] == False): # Mark present vertic as visited visited[u] = True # Mark its color opposite to its parent color[u] = not color[v] # If the subtree rooted at vertex v # is not bipartite if (not isBipartite(adj, u, visited, color)): return false # If two adjacent are colored with # same color then the graph is not # bipartite elif (color[u] == color[v]): return Talse return True # Driver Codeif __name__=='__main__': # No of nodes N = 6 # To maintain the adjacency list of graph adj = [[] for i in range(N + 1)] # To keep a check on whether # a node is discovered or not visited = [0 for i in range(N + 1)] # To color the vertices # of graph with 2 color color = [0 for i in range(N + 1)] # Adding edges to the graph addEdge(adj, 1, 2) addEdge(adj, 2, 3) addEdge(adj, 3, 4) addEdge(adj, 4, 5) addEdge(adj, 5, 6) addEdge(adj, 6, 1) # Marking the source node as visited visited[1] = True # Marking the source node with a color color[1] = 0 # Function to check if the graph # is Bipartite or not if (isBipartite(adj, 1, visited, color)): print("Graph is Bipartite") else: print("Graph is not Bipartite") # This code is contributed by rutvik_56
// C# program to check if a connected// graph is bipartite or not using DFSusing System;using System.Collections.Generic; class GFG{ // Function to store the connected nodesstatic void addEdge(List<List<int>> adj, int u, int v){ adj[u].Add(v); adj[v].Add(u);} // Function to check whether a// graph is bipartite or notstatic bool isBipartite(List<List<int>> adj, int v, bool []visited, int []color){ foreach(int u in adj[v]) { // If vertex u is not explored before if (visited[u] == false) { // Mark present vertic as visited visited[u] = true; // Mark its color opposite to its parent color[u] = 1 - color[v]; // If the subtree rooted at vertex // v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // If two adjacent are colored with // same color then the graph is // not bipartite else if (color[u] == color[v]) return false; } return true;} // Driver Codepublic static void Main(String []args){ // No of nodes int N = 6; // To maintain the adjacency list of graph List<List<int>> adj = new List<List<int>>(N + 1); // Initialize all the vertex for(int i = 0; i <= N; i++) { adj.Add(new List<int>()); } // To keep a check on whether // a node is discovered or not bool []visited = new bool[N + 1]; // To color the vertices // of graph with 2 color int []color = new int[N + 1]; // The value '-1' of colorArr[i] is // used to indicate that no color is // assigned to vertex 'i'. The value // 1 is used to indicate first color // is assigned and value 0 indicates // second color is assigned. for(int i = 0; i <= N; i++) color[i] = -1; // Adding edges to the graph addEdge(adj, 1, 2); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 4, 5); addEdge(adj, 5, 6); addEdge(adj, 6, 1); // Marking the source node as visited visited[1] = true; // Marking the source node with a color color[1] = 0; // Function to check if the graph // is Bipartite or not if (isBipartite(adj, 1, visited, color)) { Console.WriteLine("Graph is Bipartite"); } else { Console.WriteLine("Graph is not Bipartite"); }}} // This code is contributed by Princi Singh
<script> // Javascript program to check if a connected// graph is bipartite or not using DFS // function to store the connected nodesfunction addEdge(adj, u, v){ adj[u].push(v); adj[v].push(u);} // function to check whether a graph is bipartite or notfunction isBipartite(adj, v, visited, color){ adj[v].forEach(u => { // if vertex u is not explored before if (visited[u] == false) { // mark present vertic as visited visited[u] = true; // mark its color opposite to its parent color[u] = !color[v]; // if the subtree rooted at vertex v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // if two adjacent are colored with same color then // the graph is not bipartite else if (color[u] == color[v]) return false; }); return true;} // Driver Code// no of nodesvar N = 6;// to maintain the adjacency list of graphvar adj = Array.from(Array(N+1), ()=>Array());// to keep a check on whether// a node is discovered or notvar visited = Array(N+1);;// to color the vertices// of graph with 2 colorvar color = Array(N+1);// adding edges to the graphaddEdge(adj, 1, 2);addEdge(adj, 2, 3);addEdge(adj, 3, 4);addEdge(adj, 4, 5);addEdge(adj, 5, 6);addEdge(adj, 6, 1);// marking the source node as visitedvisited[1] = true;// marking the source node with a colorcolor[1] = 0;// Function to check if the graph// is Bipartite or notif (isBipartite(adj, 1, visited, color)) { document.write( "Graph is Bipartite");}else { document.write( "Graph is not Bipartite");} </script>
Graph is Bipartite
Time Complexity: O(N) Auxiliary Space: O(N)
RishiAgrawal
adityapande88
princi singh
rutvik_56
harpreet8168
rrrtnx
alokmaurya87368
varshagumber28
cpp-vector
DFS
C++
Graph
DFS
Graph
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Socket Programming in C/C++
Operator Overloading in C++
Iterators in C++ STL
Map in C++ Standard Template Library (STL)
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
|
[
{
"code": null,
"e": 24984,
"s": 24956,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 25315,
"s": 24984,
"text": "Given a connected graph, check if the graph is bipartite or not. A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with an even cycle using two colors. For example, see the following graph. "
},
{
"code": null,
"e": 25393,
"s": 25315,
"text": "It is not possible to color a cycle graph with an odd cycle using two colors."
},
{
"code": null,
"e": 25516,
"s": 25393,
"text": "In the previous post, an approach using BFS has been discussed. In this post, an approach using DFS has been implemented. "
},
{
"code": null,
"e": 25585,
"s": 25516,
"text": "Given below is the algorithm to check for bipartiteness of a graph. "
},
{
"code": null,
"e": 25671,
"s": 25585,
"text": "Use a color[] array which stores 0 or 1 for every node which denotes opposite colors."
},
{
"code": null,
"e": 25708,
"s": 25671,
"text": "Call the function DFS from any node."
},
{
"code": null,
"e": 25839,
"s": 25708,
"text": "If the node u has not been visited previously, then assign !color[v] to color[u] and call DFS again to visit nodes connected to u."
},
{
"code": null,
"e": 25919,
"s": 25839,
"text": "If at any point, color[u] is equal to color[v], then the node is not bipartite."
},
{
"code": null,
"e": 25992,
"s": 25919,
"text": "Modify the DFS function such that it returns a boolean value at the end."
},
{
"code": null,
"e": 26044,
"s": 25992,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26048,
"s": 26044,
"text": "C++"
},
{
"code": null,
"e": 26053,
"s": 26048,
"text": "Java"
},
{
"code": null,
"e": 26061,
"s": 26053,
"text": "Python3"
},
{
"code": null,
"e": 26064,
"s": 26061,
"text": "C#"
},
{
"code": null,
"e": 26075,
"s": 26064,
"text": "Javascript"
},
{
"code": "// C++ program to check if a connected// graph is bipartite or not using DFS#include <bits/stdc++.h>using namespace std; // function to store the connected nodesvoid addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // function to check whether a graph is bipartite or notbool isBipartite(vector<int> adj[], int v, vector<bool>& visited, vector<int>& color){ for (int u : adj[v]) { // if vertex u is not explored before if (visited[u] == false) { // mark present vertic as visited visited[u] = true; // mark its color opposite to its parent color[u] = !color[v]; // if the subtree rooted at vertex v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // if two adjacent are colored with same color then // the graph is not bipartite else if (color[u] == color[v]) return false; } return true;} // Driver Codeint main(){ // no of nodes int N = 6; // to maintain the adjacency list of graph vector<int> adj[N + 1]; // to keep a check on whether // a node is discovered or not vector<bool> visited(N + 1); // to color the vertices // of graph with 2 color vector<int> color(N + 1); // adding edges to the graph addEdge(adj, 1, 2); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 4, 5); addEdge(adj, 5, 6); addEdge(adj, 6, 1); // marking the source node as visited visited[1] = true; // marking the source node with a color color[1] = 0; // Function to check if the graph // is Bipartite or not if (isBipartite(adj, 1, visited, color)) { cout << \"Graph is Bipartite\"; } else { cout << \"Graph is not Bipartite\"; } return 0;}",
"e": 27936,
"s": 26075,
"text": null
},
{
"code": "// Java program to check if a connected// graph is bipartite or not using DFSimport java.util.*; class GFG{ // Function to store the connected nodesstatic void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v){ adj.get(u).add(v); adj.get(v).add(u);} // Function to check whether a// graph is bipartite or notstatic boolean isBipartite(ArrayList<ArrayList<Integer>> adj, int v, boolean visited[], int color[]){ for(int u : adj.get(v)) { // If vertex u is not explored before if (visited[u] == false) { // Mark present vertic as visited visited[u] = true; // Mark its color opposite to its parent color[u] = 1 - color[v]; // If the subtree rooted at vertex // v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // If two adjacent are colored with // same color then the graph is // not bipartite else if (color[u] == color[v]) return false; } return true;} // Driver Codepublic static void main(String args[]){ // No of nodes int N = 6; // To maintain the adjacency list of graph ArrayList< ArrayList<Integer>> adj = new ArrayList< ArrayList<Integer>>(N + 1); // Initialize all the vertex for(int i = 0; i <= N; i++) { adj.add(new ArrayList<Integer>()); } // To keep a check on whether // a node is discovered or not boolean visited[] = new boolean[N + 1]; // To color the vertices // of graph with 2 color int color[] = new int[N + 1]; // The value '-1' of colorArr[i] is // used to indicate that no color is // assigned to vertex 'i'. The value // 1 is used to indicate first color // is assigned and value 0 indicates // second color is assigned. Arrays.fill(color, -1); // Adding edges to the graph addEdge(adj, 1, 2); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 4, 5); addEdge(adj, 5, 6); addEdge(adj, 6, 1); // Marking the source node as visited visited[1] = true; // Marking the source node with a color color[1] = 0; // Function to check if the graph // is Bipartite or not if (isBipartite(adj, 1, visited, color)) { System.out.println(\"Graph is Bipartite\"); } else { System.out.println(\"Graph is not Bipartite\"); }}} // This code is contributed by adityapande88",
"e": 30528,
"s": 27936,
"text": null
},
{
"code": "# Python3 program to check if a connected# graph is bipartite or not using DFS # Function to store the connected nodesdef addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # Function to check whether a graph is# bipartite or notdef isBipartite(adj, v, visited, color): for u in adj[v]: # If vertex u is not explored before if (visited[u] == False): # Mark present vertic as visited visited[u] = True # Mark its color opposite to its parent color[u] = not color[v] # If the subtree rooted at vertex v # is not bipartite if (not isBipartite(adj, u, visited, color)): return false # If two adjacent are colored with # same color then the graph is not # bipartite elif (color[u] == color[v]): return Talse return True # Driver Codeif __name__=='__main__': # No of nodes N = 6 # To maintain the adjacency list of graph adj = [[] for i in range(N + 1)] # To keep a check on whether # a node is discovered or not visited = [0 for i in range(N + 1)] # To color the vertices # of graph with 2 color color = [0 for i in range(N + 1)] # Adding edges to the graph addEdge(adj, 1, 2) addEdge(adj, 2, 3) addEdge(adj, 3, 4) addEdge(adj, 4, 5) addEdge(adj, 5, 6) addEdge(adj, 6, 1) # Marking the source node as visited visited[1] = True # Marking the source node with a color color[1] = 0 # Function to check if the graph # is Bipartite or not if (isBipartite(adj, 1, visited, color)): print(\"Graph is Bipartite\") else: print(\"Graph is not Bipartite\") # This code is contributed by rutvik_56",
"e": 32341,
"s": 30528,
"text": null
},
{
"code": "// C# program to check if a connected// graph is bipartite or not using DFSusing System;using System.Collections.Generic; class GFG{ // Function to store the connected nodesstatic void addEdge(List<List<int>> adj, int u, int v){ adj[u].Add(v); adj[v].Add(u);} // Function to check whether a// graph is bipartite or notstatic bool isBipartite(List<List<int>> adj, int v, bool []visited, int []color){ foreach(int u in adj[v]) { // If vertex u is not explored before if (visited[u] == false) { // Mark present vertic as visited visited[u] = true; // Mark its color opposite to its parent color[u] = 1 - color[v]; // If the subtree rooted at vertex // v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // If two adjacent are colored with // same color then the graph is // not bipartite else if (color[u] == color[v]) return false; } return true;} // Driver Codepublic static void Main(String []args){ // No of nodes int N = 6; // To maintain the adjacency list of graph List<List<int>> adj = new List<List<int>>(N + 1); // Initialize all the vertex for(int i = 0; i <= N; i++) { adj.Add(new List<int>()); } // To keep a check on whether // a node is discovered or not bool []visited = new bool[N + 1]; // To color the vertices // of graph with 2 color int []color = new int[N + 1]; // The value '-1' of colorArr[i] is // used to indicate that no color is // assigned to vertex 'i'. The value // 1 is used to indicate first color // is assigned and value 0 indicates // second color is assigned. for(int i = 0; i <= N; i++) color[i] = -1; // Adding edges to the graph addEdge(adj, 1, 2); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 4, 5); addEdge(adj, 5, 6); addEdge(adj, 6, 1); // Marking the source node as visited visited[1] = true; // Marking the source node with a color color[1] = 0; // Function to check if the graph // is Bipartite or not if (isBipartite(adj, 1, visited, color)) { Console.WriteLine(\"Graph is Bipartite\"); } else { Console.WriteLine(\"Graph is not Bipartite\"); }}} // This code is contributed by Princi Singh",
"e": 34867,
"s": 32341,
"text": null
},
{
"code": "<script> // Javascript program to check if a connected// graph is bipartite or not using DFS // function to store the connected nodesfunction addEdge(adj, u, v){ adj[u].push(v); adj[v].push(u);} // function to check whether a graph is bipartite or notfunction isBipartite(adj, v, visited, color){ adj[v].forEach(u => { // if vertex u is not explored before if (visited[u] == false) { // mark present vertic as visited visited[u] = true; // mark its color opposite to its parent color[u] = !color[v]; // if the subtree rooted at vertex v is not bipartite if (!isBipartite(adj, u, visited, color)) return false; } // if two adjacent are colored with same color then // the graph is not bipartite else if (color[u] == color[v]) return false; }); return true;} // Driver Code// no of nodesvar N = 6;// to maintain the adjacency list of graphvar adj = Array.from(Array(N+1), ()=>Array());// to keep a check on whether// a node is discovered or notvar visited = Array(N+1);;// to color the vertices// of graph with 2 colorvar color = Array(N+1);// adding edges to the graphaddEdge(adj, 1, 2);addEdge(adj, 2, 3);addEdge(adj, 3, 4);addEdge(adj, 4, 5);addEdge(adj, 5, 6);addEdge(adj, 6, 1);// marking the source node as visitedvisited[1] = true;// marking the source node with a colorcolor[1] = 0;// Function to check if the graph// is Bipartite or notif (isBipartite(adj, 1, visited, color)) { document.write( \"Graph is Bipartite\");}else { document.write( \"Graph is not Bipartite\");} </script>",
"e": 36524,
"s": 34867,
"text": null
},
{
"code": null,
"e": 36543,
"s": 36524,
"text": "Graph is Bipartite"
},
{
"code": null,
"e": 36591,
"s": 36545,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 36604,
"s": 36591,
"text": "RishiAgrawal"
},
{
"code": null,
"e": 36618,
"s": 36604,
"text": "adityapande88"
},
{
"code": null,
"e": 36631,
"s": 36618,
"text": "princi singh"
},
{
"code": null,
"e": 36641,
"s": 36631,
"text": "rutvik_56"
},
{
"code": null,
"e": 36654,
"s": 36641,
"text": "harpreet8168"
},
{
"code": null,
"e": 36661,
"s": 36654,
"text": "rrrtnx"
},
{
"code": null,
"e": 36677,
"s": 36661,
"text": "alokmaurya87368"
},
{
"code": null,
"e": 36692,
"s": 36677,
"text": "varshagumber28"
},
{
"code": null,
"e": 36703,
"s": 36692,
"text": "cpp-vector"
},
{
"code": null,
"e": 36707,
"s": 36703,
"text": "DFS"
},
{
"code": null,
"e": 36711,
"s": 36707,
"text": "C++"
},
{
"code": null,
"e": 36717,
"s": 36711,
"text": "Graph"
},
{
"code": null,
"e": 36721,
"s": 36717,
"text": "DFS"
},
{
"code": null,
"e": 36727,
"s": 36721,
"text": "Graph"
},
{
"code": null,
"e": 36731,
"s": 36727,
"text": "CPP"
},
{
"code": null,
"e": 36829,
"s": 36731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36838,
"s": 36829,
"text": "Comments"
},
{
"code": null,
"e": 36851,
"s": 36838,
"text": "Old Comments"
},
{
"code": null,
"e": 36870,
"s": 36851,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 36898,
"s": 36870,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 36926,
"s": 36898,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 36947,
"s": 36926,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 36990,
"s": 36947,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 37041,
"s": 36990,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 37092,
"s": 37041,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 37122,
"s": 37092,
"text": "Graph and its representations"
}
] |
Kotlin Inheritance
|
In Kotlin, it is possible to inherit class properties and functions from one class to another. We group the "inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
In the example below, MyChildClass (subclass) inherits the
properties from the
MyParentClass class
(superclass):
// Superclassopen class MyParentClass {
val x = 5
}
// Subclass
class MyChildClass: MyParentClass() {
fun myFunction() {
println(x) // x is now inherited from the superclass
}
}
// Create an object of MyChildClass and call myFunction
fun main() {
val myObj = MyChildClass()
myObj.myFunction()
}
Use the open keyword in front of the superclass/parent,
to make this the class other classes should inherit properties and functions from.
To inherit from a class, specify the name of the subclass, followed by a colon :,
and then the name of the superclass.
- It is useful for code reusability: reuse properties and functions of an existing class when you create a new class.
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": 151,
"s": 0,
"text": "In Kotlin, it is possible to inherit class properties and functions from one class to another. We group the \"inheritance concept\" into two categories:"
},
{
"code": null,
"e": 213,
"s": 151,
"text": "subclass (child) - the class that inherits from another class"
},
{
"code": null,
"e": 266,
"s": 213,
"text": "superclass (parent) - the class being inherited from"
},
{
"code": null,
"e": 382,
"s": 266,
"text": "In the example below, MyChildClass (subclass) inherits the \nproperties from the \nMyParentClass class \n(superclass):"
},
{
"code": null,
"e": 694,
"s": 382,
"text": "// Superclassopen class MyParentClass {\n val x = 5\n}\n\n// Subclass\nclass MyChildClass: MyParentClass() {\n fun myFunction() {\n println(x) // x is now inherited from the superclass\n }\n}\n\n// Create an object of MyChildClass and call myFunction\nfun main() {\n val myObj = MyChildClass()\n myObj.myFunction()\n} "
},
{
"code": null,
"e": 834,
"s": 694,
"text": "Use the open keyword in front of the superclass/parent, \nto make this the class other classes should inherit properties and functions from."
},
{
"code": null,
"e": 954,
"s": 834,
"text": "To inherit from a class, specify the name of the subclass, followed by a colon :, \nand then the name of the superclass."
},
{
"code": null,
"e": 1072,
"s": 954,
"text": "- It is useful for code reusability: reuse properties and functions of an existing class when you create a new class."
},
{
"code": null,
"e": 1105,
"s": 1072,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1147,
"s": 1105,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1254,
"s": 1147,
"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": 1273,
"s": 1254,
"text": "help@w3schools.com"
}
] |
Improving Deep Neural Networks. In this story, I have explained... | by Rochak Agrawal | Towards Data Science
|
Deep Neural Networks are the solution to complex tasks like Natural Language Processing, Computer Vision, Speech Synthesis etc. Improving their performance is as important as understanding how they work. To understand how they work, you can refer to my previous posts. In this post, I will be explaining various terminologies and methods related to improving the neural networks.
Bias and Variance are two essential terminologies that explain how well the network performs on the Training set and the Test set. Let us understand Bias and Variance easily and intuitively using a 2 class problem. The blue line indicates the decision boundary computed by the neural network.
The leftmost figure shows that the neural network has the problem of High Bias. In this case, the network has learned a simple hypothesis and is therefore not able to train properly on the training data. As a result, it is not able to differentiate between the examples of different classes and will perform poorly on the training set and test set both. We can also say that the network is Underfitting.The rightmost figure shows that the neural network has the problem of High Variance. In this case, the network has learned a very complex hypothesis and therefore is not able to generalise. As a result, it will perform great on training data, whereas poor on the test data. We can also say that the network is Overfitting.The centre figure shows a “Just Right” neural network. It has learned the ideal hypothesis, which helps the network to filter out the anomalies and also generalise on the data. Our goal should be to achieve such type of network.
The leftmost figure shows that the neural network has the problem of High Bias. In this case, the network has learned a simple hypothesis and is therefore not able to train properly on the training data. As a result, it is not able to differentiate between the examples of different classes and will perform poorly on the training set and test set both. We can also say that the network is Underfitting.
The rightmost figure shows that the neural network has the problem of High Variance. In this case, the network has learned a very complex hypothesis and therefore is not able to generalise. As a result, it will perform great on training data, whereas poor on the test data. We can also say that the network is Overfitting.
The centre figure shows a “Just Right” neural network. It has learned the ideal hypothesis, which helps the network to filter out the anomalies and also generalise on the data. Our goal should be to achieve such type of network.
Now that we know what kind of neural network is desirable; let us see how we can achieve our goal. The steps first tackle the bias problem and then the variance problem.
The first question that we should ask is “Is there a High Bias?” If the answer is YES, then we should try the following steps:
Train a bigger network. It includes increasing the number of hidden layers and the number of neurons in the hidden layers.
Train the network for an extended period of time. It may be the case that the full training has not been completed yet and will take more iterations.
Try a different optimisation algorithm. These algorithms include Adam, Momentum, AdaDelta etc.
Perform the above steps iteratively until the bias problem is solved and then move on to the second question.
If the answer is NO, it means that we have overcome the bias problem, and it is time to focus on the variance problem. The second question that we should ask now is “Is there a High Variance?” If the answer is YES, then we should try the following steps:
Gather more training data. As we gather more data, we will get more variation in the data, and the complexity of the learned hypothesis from the less varied data will break.
Try Regularization. I will speak about it in the next section.
Perform the above steps iteratively until the variance problem is solved.
If the answer is NO, it means that we have overcome the variance problem, and now our Neural Network is “Just Right”.
Regularization is a logical technique which helps to reduce overfitting in a neural network. When we add regularization to our network, we add a new regularization term, and the loss function is modified. The modified cost function J is mathematically formulated as:
The second term with lambda is known as the regularization term. The term ||W|| is known as Frobenius Norm (sum of squares of elements in a matrix). With the inclusion of regularization, lambda becomes a new hyperparameter that can be modified to improve the performance of the neural network. The above regularization is also known as L-2 regularization.
Earlier, we used the following update rule to update the weights:
Since there is a new regularization term in the modified Cost Function J, which includes regularization, we will update the weights in the following manner:
Here we can see that the Weight value decreases by a small number which is less than 1. Therefore, we also call this type of regularization as Weight Decay. The decay value depends on the learning rate alpha and the regularization term lambda.
The end goal of training a neural network is to minimize Cost Function J and hence the regularization term. Now that we know what regularization is, let us try to understand why it works.
The first intuition is that if we increase the value of lambda, the Frobenius Norm becomes small, and the weight values become close to 0. This methodology mainly wipes out certain neurons making the network a shallow one. It may be thought of as converting the deep network which learns complex hypothesis into a shallow network which learns simple hypothesis. As we know that simple hypothesis leads to fewer complex features, the overfitting will be reduced, and we will obtain a “Just Right” Neural Network.
Another intuition can be gained from the way the activation of a neuron works when regularization is applied. For this, let us consider tanh(x) activation.
If we increase the value of lambda, then the Frobenius Norm becomes small, i.e. the Weights W become small. Due to this, the output of that layer will become small and will lie in the blue region of the activation function. As we can see, the activation of the blue area is almost linear, the network will behave similar to a shallow network, i.e. the network will not learn complex hypothesis (sharp curves will be avoided) and the overfitting will eventually reduce, and we will obtain a “Just Right” Neural Network.
Therefore, a too small value of lambda will result in Overfitting as the Frobenius Norm will be large, and neurons will not be wiped out, and output of the layer will not be in the linear region. Similarly, an excessively large value of lambda will result in underfitting. Therefore, finding the perfect value of lambda is a crucial task in improving the performance of the neural network.
Dropout regularization is another regularization technique in which we drop certain neurons along with their connections present in the neural network. The probability keep_prob determines the neurons that will be dropped. After the neurons are removed, the network is trained on the remaining neurons. It is important to note that during the test time/ inference time, all the neurons are taken into consideration for determining the output. Let us try to understand the concept with the help of an example:
# Define the probablity that a neuron stays.keep_prob = 0.5# Create a probability mask for a layer eg. layer 2. The mask should # have same dimensions as the weight matrix so that the connections # can be removed.d2 = np.random.rand(a2.shape[0],a2.shape[1]) < keep_prob# Obtain the new output matrix.a2 = np.multiply(a2,d2)# Since few neurons are removed, we need to boost the weights of # remaining neurons to avoid weight imbalance during test time.a2 = a2/keep_prob
Since we first drop the neurons with the probability keep_prob and then boost the remaining neurons with keep_prob, this type of Dropout is known as Inverted Dropout.
The intuition between dropout is that it prohibits the neurons from relying only on certain features, and therefore, the weights are spread out. It may be the case that the neuron becomes dependent on certain input features to determine the output. With the help of dropout regularization, a particular neuron gets only a few features as input every time for different training examples during training. Eventually, the weights are spread out amongst all the inputs, and the network uses all the input features to determine the output and does not rely on any single one, thus making the network more robust. It is also known as Adaptive form of L2 Regularization.
We can also set keep_prob individually for each layer. Since the number of neurons that are dropped is inversely proportional to the keep_prob; the general criteria for establishing the keep_prob is that the dense connections should have relatively less keep_prob so that more neurons are dropped and vice versa.
Another intuition is that with Dropout Regularization, the deep network mimics the working of a shallow network during the training phase. This, in turn, leads to reducing overfitting, and we obtain a “Just Right” Neural Network.
Early Stopping is a training methodology in which we stop training the neural network at an earlier stage of time to prevent it from overfitting. We keep track of train_loss and dev_loss to determine when to stop the training.
Just the dev_loss starts to overshoot; we stop the training process. This methodology is known as Early Stopping. However, early stopping is not a recommended method for training a network because of the following two reasons:
The loss is not minimum when we stop the training process.We are trying to reduce overfitting on the improperly trained network.
The loss is not minimum when we stop the training process.
We are trying to reduce overfitting on the improperly trained network.
Early stopping makes things complicated, and we are not able to obtain the “Just Right” Neural Network.
Wikipedia — Activation FunctionsCoursera — Deep Learning Course 2
Wikipedia — Activation Functions
Coursera — Deep Learning Course 2
I want to thank the readers for reading the story. If you have any questions or doubts, feel free to ask them in the comments section below. I’ll be more than happy to answer them and help you out. If you like the story, please follow me to get regular updates when I publish a new story. I welcome any suggestions that will improve my stories.
|
[
{
"code": null,
"e": 552,
"s": 172,
"text": "Deep Neural Networks are the solution to complex tasks like Natural Language Processing, Computer Vision, Speech Synthesis etc. Improving their performance is as important as understanding how they work. To understand how they work, you can refer to my previous posts. In this post, I will be explaining various terminologies and methods related to improving the neural networks."
},
{
"code": null,
"e": 845,
"s": 552,
"text": "Bias and Variance are two essential terminologies that explain how well the network performs on the Training set and the Test set. Let us understand Bias and Variance easily and intuitively using a 2 class problem. The blue line indicates the decision boundary computed by the neural network."
},
{
"code": null,
"e": 1799,
"s": 845,
"text": "The leftmost figure shows that the neural network has the problem of High Bias. In this case, the network has learned a simple hypothesis and is therefore not able to train properly on the training data. As a result, it is not able to differentiate between the examples of different classes and will perform poorly on the training set and test set both. We can also say that the network is Underfitting.The rightmost figure shows that the neural network has the problem of High Variance. In this case, the network has learned a very complex hypothesis and therefore is not able to generalise. As a result, it will perform great on training data, whereas poor on the test data. We can also say that the network is Overfitting.The centre figure shows a “Just Right” neural network. It has learned the ideal hypothesis, which helps the network to filter out the anomalies and also generalise on the data. Our goal should be to achieve such type of network."
},
{
"code": null,
"e": 2203,
"s": 1799,
"text": "The leftmost figure shows that the neural network has the problem of High Bias. In this case, the network has learned a simple hypothesis and is therefore not able to train properly on the training data. As a result, it is not able to differentiate between the examples of different classes and will perform poorly on the training set and test set both. We can also say that the network is Underfitting."
},
{
"code": null,
"e": 2526,
"s": 2203,
"text": "The rightmost figure shows that the neural network has the problem of High Variance. In this case, the network has learned a very complex hypothesis and therefore is not able to generalise. As a result, it will perform great on training data, whereas poor on the test data. We can also say that the network is Overfitting."
},
{
"code": null,
"e": 2755,
"s": 2526,
"text": "The centre figure shows a “Just Right” neural network. It has learned the ideal hypothesis, which helps the network to filter out the anomalies and also generalise on the data. Our goal should be to achieve such type of network."
},
{
"code": null,
"e": 2925,
"s": 2755,
"text": "Now that we know what kind of neural network is desirable; let us see how we can achieve our goal. The steps first tackle the bias problem and then the variance problem."
},
{
"code": null,
"e": 3052,
"s": 2925,
"text": "The first question that we should ask is “Is there a High Bias?” If the answer is YES, then we should try the following steps:"
},
{
"code": null,
"e": 3175,
"s": 3052,
"text": "Train a bigger network. It includes increasing the number of hidden layers and the number of neurons in the hidden layers."
},
{
"code": null,
"e": 3325,
"s": 3175,
"text": "Train the network for an extended period of time. It may be the case that the full training has not been completed yet and will take more iterations."
},
{
"code": null,
"e": 3420,
"s": 3325,
"text": "Try a different optimisation algorithm. These algorithms include Adam, Momentum, AdaDelta etc."
},
{
"code": null,
"e": 3530,
"s": 3420,
"text": "Perform the above steps iteratively until the bias problem is solved and then move on to the second question."
},
{
"code": null,
"e": 3785,
"s": 3530,
"text": "If the answer is NO, it means that we have overcome the bias problem, and it is time to focus on the variance problem. The second question that we should ask now is “Is there a High Variance?” If the answer is YES, then we should try the following steps:"
},
{
"code": null,
"e": 3959,
"s": 3785,
"text": "Gather more training data. As we gather more data, we will get more variation in the data, and the complexity of the learned hypothesis from the less varied data will break."
},
{
"code": null,
"e": 4022,
"s": 3959,
"text": "Try Regularization. I will speak about it in the next section."
},
{
"code": null,
"e": 4096,
"s": 4022,
"text": "Perform the above steps iteratively until the variance problem is solved."
},
{
"code": null,
"e": 4214,
"s": 4096,
"text": "If the answer is NO, it means that we have overcome the variance problem, and now our Neural Network is “Just Right”."
},
{
"code": null,
"e": 4481,
"s": 4214,
"text": "Regularization is a logical technique which helps to reduce overfitting in a neural network. When we add regularization to our network, we add a new regularization term, and the loss function is modified. The modified cost function J is mathematically formulated as:"
},
{
"code": null,
"e": 4837,
"s": 4481,
"text": "The second term with lambda is known as the regularization term. The term ||W|| is known as Frobenius Norm (sum of squares of elements in a matrix). With the inclusion of regularization, lambda becomes a new hyperparameter that can be modified to improve the performance of the neural network. The above regularization is also known as L-2 regularization."
},
{
"code": null,
"e": 4903,
"s": 4837,
"text": "Earlier, we used the following update rule to update the weights:"
},
{
"code": null,
"e": 5060,
"s": 4903,
"text": "Since there is a new regularization term in the modified Cost Function J, which includes regularization, we will update the weights in the following manner:"
},
{
"code": null,
"e": 5304,
"s": 5060,
"text": "Here we can see that the Weight value decreases by a small number which is less than 1. Therefore, we also call this type of regularization as Weight Decay. The decay value depends on the learning rate alpha and the regularization term lambda."
},
{
"code": null,
"e": 5492,
"s": 5304,
"text": "The end goal of training a neural network is to minimize Cost Function J and hence the regularization term. Now that we know what regularization is, let us try to understand why it works."
},
{
"code": null,
"e": 6004,
"s": 5492,
"text": "The first intuition is that if we increase the value of lambda, the Frobenius Norm becomes small, and the weight values become close to 0. This methodology mainly wipes out certain neurons making the network a shallow one. It may be thought of as converting the deep network which learns complex hypothesis into a shallow network which learns simple hypothesis. As we know that simple hypothesis leads to fewer complex features, the overfitting will be reduced, and we will obtain a “Just Right” Neural Network."
},
{
"code": null,
"e": 6160,
"s": 6004,
"text": "Another intuition can be gained from the way the activation of a neuron works when regularization is applied. For this, let us consider tanh(x) activation."
},
{
"code": null,
"e": 6679,
"s": 6160,
"text": "If we increase the value of lambda, then the Frobenius Norm becomes small, i.e. the Weights W become small. Due to this, the output of that layer will become small and will lie in the blue region of the activation function. As we can see, the activation of the blue area is almost linear, the network will behave similar to a shallow network, i.e. the network will not learn complex hypothesis (sharp curves will be avoided) and the overfitting will eventually reduce, and we will obtain a “Just Right” Neural Network."
},
{
"code": null,
"e": 7069,
"s": 6679,
"text": "Therefore, a too small value of lambda will result in Overfitting as the Frobenius Norm will be large, and neurons will not be wiped out, and output of the layer will not be in the linear region. Similarly, an excessively large value of lambda will result in underfitting. Therefore, finding the perfect value of lambda is a crucial task in improving the performance of the neural network."
},
{
"code": null,
"e": 7578,
"s": 7069,
"text": "Dropout regularization is another regularization technique in which we drop certain neurons along with their connections present in the neural network. The probability keep_prob determines the neurons that will be dropped. After the neurons are removed, the network is trained on the remaining neurons. It is important to note that during the test time/ inference time, all the neurons are taken into consideration for determining the output. Let us try to understand the concept with the help of an example:"
},
{
"code": null,
"e": 8050,
"s": 7578,
"text": "# Define the probablity that a neuron stays.keep_prob = 0.5# Create a probability mask for a layer eg. layer 2. The mask should # have same dimensions as the weight matrix so that the connections # can be removed.d2 = np.random.rand(a2.shape[0],a2.shape[1]) < keep_prob# Obtain the new output matrix.a2 = np.multiply(a2,d2)# Since few neurons are removed, we need to boost the weights of # remaining neurons to avoid weight imbalance during test time.a2 = a2/keep_prob"
},
{
"code": null,
"e": 8217,
"s": 8050,
"text": "Since we first drop the neurons with the probability keep_prob and then boost the remaining neurons with keep_prob, this type of Dropout is known as Inverted Dropout."
},
{
"code": null,
"e": 8882,
"s": 8217,
"text": "The intuition between dropout is that it prohibits the neurons from relying only on certain features, and therefore, the weights are spread out. It may be the case that the neuron becomes dependent on certain input features to determine the output. With the help of dropout regularization, a particular neuron gets only a few features as input every time for different training examples during training. Eventually, the weights are spread out amongst all the inputs, and the network uses all the input features to determine the output and does not rely on any single one, thus making the network more robust. It is also known as Adaptive form of L2 Regularization."
},
{
"code": null,
"e": 9195,
"s": 8882,
"text": "We can also set keep_prob individually for each layer. Since the number of neurons that are dropped is inversely proportional to the keep_prob; the general criteria for establishing the keep_prob is that the dense connections should have relatively less keep_prob so that more neurons are dropped and vice versa."
},
{
"code": null,
"e": 9425,
"s": 9195,
"text": "Another intuition is that with Dropout Regularization, the deep network mimics the working of a shallow network during the training phase. This, in turn, leads to reducing overfitting, and we obtain a “Just Right” Neural Network."
},
{
"code": null,
"e": 9652,
"s": 9425,
"text": "Early Stopping is a training methodology in which we stop training the neural network at an earlier stage of time to prevent it from overfitting. We keep track of train_loss and dev_loss to determine when to stop the training."
},
{
"code": null,
"e": 9879,
"s": 9652,
"text": "Just the dev_loss starts to overshoot; we stop the training process. This methodology is known as Early Stopping. However, early stopping is not a recommended method for training a network because of the following two reasons:"
},
{
"code": null,
"e": 10008,
"s": 9879,
"text": "The loss is not minimum when we stop the training process.We are trying to reduce overfitting on the improperly trained network."
},
{
"code": null,
"e": 10067,
"s": 10008,
"text": "The loss is not minimum when we stop the training process."
},
{
"code": null,
"e": 10138,
"s": 10067,
"text": "We are trying to reduce overfitting on the improperly trained network."
},
{
"code": null,
"e": 10242,
"s": 10138,
"text": "Early stopping makes things complicated, and we are not able to obtain the “Just Right” Neural Network."
},
{
"code": null,
"e": 10308,
"s": 10242,
"text": "Wikipedia — Activation FunctionsCoursera — Deep Learning Course 2"
},
{
"code": null,
"e": 10341,
"s": 10308,
"text": "Wikipedia — Activation Functions"
},
{
"code": null,
"e": 10375,
"s": 10341,
"text": "Coursera — Deep Learning Course 2"
}
] |
Java program to remove nulls from a List Container
|
11 Dec, 2018
List is an ordered collection of objects which allows to store duplicate values or null values, in the insertion order. So it is very important to remove null values in many scenarios.
Examples:
Input: [Geeks, null, forGeeks, null, A computer portal]
Output: [Geeks, forGeeks, A computer portal]
Input: [1, null, 2, 3, null, 4]
Output: [1, 2, 3, 4]
Below are the methods to remove nulls from a List in Java:
Using List.remove() List interface provides a pre-defined method remove(element) which is used to remove a single occurrence of the element passed, from the List, if found.Algorithm:Get the list with null values.Repeatedly call remove(null) on the list, until all null values are removed.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using List.remove() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using List.remove() // Repeatedly call remove() till all null are removed while (list.remove(null)) { } // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using List.removeAll(): List interface provides another pre-defined method removeAll(Collection) which is used to remove all occurrences of the elements of the Collection passed, from the List, if found.Algorithm:Get the list with null values.Create a Collection with only null as element using Collections.singletonList(null)Call removeAll(Collection) on the list once.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using List.removeAll() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using List.removeAll() // passing a collection with single element "null" list.removeAll(Collections.singletonList(null)); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using iterator: Iterator is an interface which belongs to collection framework. It allows user to traverse the collection, access the data element and remove the data elements of the collection.Algorithm:Get the list with null values.Create an iterator from the listTraverse through each element of the List with the of created IteratorCheck, for each element, if it is null. If found null, call IteratorElement.remove() on that element.Return/Print the list (now with all null values removed).Program:// Java Program to remove nulls// from a List using iterator import java.util.*; class GFG { // Generic function to remove Null Using Iterator public static <T> List<T> removeNullUsingIterator(List<T> list) { // Create an iterator from the list Iterator<T> itr = list.iterator(); // Find and remove all null while (itr.hasNext()) { if (itr.next() == null) itr.remove(); // remove nulls } // Return the null return list; } public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using iterator list = removeNullUsingIterator(list); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using Guava Iterables removeIf(): Guava Iterables class provides Iterables.removeIf(Iterable, Predicate) that removes every element from a specified Iterable (or Collections that implements Iterable) that satisfies the provided predicate.Algorithm:Get the list with null values.Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using Guava Iterables import com.google.common.base.Predicates;import com.google.common.collect.Iterables;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Guava Iterables // using Predicate condition isNull() Iterables.removeIf(list, Predicates.isNull()); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using Apache Commons Collections filter(): Apache Commons Collections CollectionUtils class provides filter(Iterable, Predicate) that removes every element from a specified iterable that do not satisfies the provided predicate.Algorithm:Get the list with null values.Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered.Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance.Return/Print the list (now with all null values removed).Program:// Java Program to remove nulls// from a List using Apache Common COllection Filter()import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.collections4.PredicateUtils;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Apache Common filter() // using Predicate condition notNullPredicate() CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using Lambdas (Java 8): Stream.filter() method can be used in Java 8 that returns a stream consisting of the elementsthat match the given predicate condition.Algorithm:Get the list with null values.Create a Stream from the list using list.stream()Filter the stream of elements that are not null using list.filter(x -> x != null)Collect back the Stream as List using .collect(Collectors.toList()Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using Apache Common COllection Filter() import java.util.stream.Collectors;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Java Stream // using Predicate condition in lambda expression list = list.stream() .filter(x -> x != null) .collect(Collectors.toList()); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
My Personal Notes
arrow_drop_upSave
Using List.remove() List interface provides a pre-defined method remove(element) which is used to remove a single occurrence of the element passed, from the List, if found.Algorithm:Get the list with null values.Repeatedly call remove(null) on the list, until all null values are removed.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using List.remove() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using List.remove() // Repeatedly call remove() till all null are removed while (list.remove(null)) { } // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Algorithm:
Get the list with null values.Repeatedly call remove(null) on the list, until all null values are removed.Return/Print the list (now with all null values removed).
Get the list with null values.
Repeatedly call remove(null) on the list, until all null values are removed.
Return/Print the list (now with all null values removed).
// Java Program to remove nulls// from a List using List.remove() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using List.remove() // Repeatedly call remove() till all null are removed while (list.remove(null)) { } // Print the list System.out.println("Modified List: " + list); }}
Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using List.removeAll(): List interface provides another pre-defined method removeAll(Collection) which is used to remove all occurrences of the elements of the Collection passed, from the List, if found.Algorithm:Get the list with null values.Create a Collection with only null as element using Collections.singletonList(null)Call removeAll(Collection) on the list once.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using List.removeAll() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using List.removeAll() // passing a collection with single element "null" list.removeAll(Collections.singletonList(null)); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Algorithm:
Get the list with null values.Create a Collection with only null as element using Collections.singletonList(null)Call removeAll(Collection) on the list once.Return/Print the list (now with all null values removed).
Get the list with null values.
Create a Collection with only null as element using Collections.singletonList(null)
Call removeAll(Collection) on the list once.
Return/Print the list (now with all null values removed).
// Java Program to remove nulls// from a List using List.removeAll() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using List.removeAll() // passing a collection with single element "null" list.removeAll(Collections.singletonList(null)); // Print the list System.out.println("Modified List: " + list); }}
Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using iterator: Iterator is an interface which belongs to collection framework. It allows user to traverse the collection, access the data element and remove the data elements of the collection.Algorithm:Get the list with null values.Create an iterator from the listTraverse through each element of the List with the of created IteratorCheck, for each element, if it is null. If found null, call IteratorElement.remove() on that element.Return/Print the list (now with all null values removed).Program:// Java Program to remove nulls// from a List using iterator import java.util.*; class GFG { // Generic function to remove Null Using Iterator public static <T> List<T> removeNullUsingIterator(List<T> list) { // Create an iterator from the list Iterator<T> itr = list.iterator(); // Find and remove all null while (itr.hasNext()) { if (itr.next() == null) itr.remove(); // remove nulls } // Return the null return list; } public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using iterator list = removeNullUsingIterator(list); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Algorithm:
Get the list with null values.Create an iterator from the listTraverse through each element of the List with the of created IteratorCheck, for each element, if it is null. If found null, call IteratorElement.remove() on that element.Return/Print the list (now with all null values removed).
Get the list with null values.
Create an iterator from the list
Traverse through each element of the List with the of created Iterator
Check, for each element, if it is null. If found null, call IteratorElement.remove() on that element.
Return/Print the list (now with all null values removed).
Program:
// Java Program to remove nulls// from a List using iterator import java.util.*; class GFG { // Generic function to remove Null Using Iterator public static <T> List<T> removeNullUsingIterator(List<T> list) { // Create an iterator from the list Iterator<T> itr = list.iterator(); // Find and remove all null while (itr.hasNext()) { if (itr.next() == null) itr.remove(); // remove nulls } // Return the null return list; } public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using iterator list = removeNullUsingIterator(list); // Print the list System.out.println("Modified List: " + list); }}
Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using Guava Iterables removeIf(): Guava Iterables class provides Iterables.removeIf(Iterable, Predicate) that removes every element from a specified Iterable (or Collections that implements Iterable) that satisfies the provided predicate.Algorithm:Get the list with null values.Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using Guava Iterables import com.google.common.base.Predicates;import com.google.common.collect.Iterables;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Guava Iterables // using Predicate condition isNull() Iterables.removeIf(list, Predicates.isNull()); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Algorithm:
Get the list with null values.Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance.Return/Print the list (now with all null values removed).
Get the list with null values.
Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()
Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance.
Return/Print the list (now with all null values removed).
// Java Program to remove nulls// from a List using Guava Iterables import com.google.common.base.Predicates;import com.google.common.collect.Iterables;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Guava Iterables // using Predicate condition isNull() Iterables.removeIf(list, Predicates.isNull()); // Print the list System.out.println("Modified List: " + list); }}
Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using Apache Commons Collections filter(): Apache Commons Collections CollectionUtils class provides filter(Iterable, Predicate) that removes every element from a specified iterable that do not satisfies the provided predicate.Algorithm:Get the list with null values.Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered.Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance.Return/Print the list (now with all null values removed).Program:// Java Program to remove nulls// from a List using Apache Common COllection Filter()import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.collections4.PredicateUtils;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Apache Common filter() // using Predicate condition notNullPredicate() CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Algorithm:
Get the list with null values.Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered.Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance.Return/Print the list (now with all null values removed).
Get the list with null values.
Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered.
Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance.
Return/Print the list (now with all null values removed).
Program:
// Java Program to remove nulls// from a List using Apache Common COllection Filter()import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.collections4.PredicateUtils;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Apache Common filter() // using Predicate condition notNullPredicate() CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); // Print the list System.out.println("Modified List: " + list); }}
Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Using Lambdas (Java 8): Stream.filter() method can be used in Java 8 that returns a stream consisting of the elementsthat match the given predicate condition.Algorithm:Get the list with null values.Create a Stream from the list using list.stream()Filter the stream of elements that are not null using list.filter(x -> x != null)Collect back the Stream as List using .collect(Collectors.toList()Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using Apache Common COllection Filter() import java.util.stream.Collectors;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Java Stream // using Predicate condition in lambda expression list = list.stream() .filter(x -> x != null) .collect(Collectors.toList()); // Print the list System.out.println("Modified List: " + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
My Personal Notes
arrow_drop_upSave
Algorithm:
Get the list with null values.Create a Stream from the list using list.stream()Filter the stream of elements that are not null using list.filter(x -> x != null)Collect back the Stream as List using .collect(Collectors.toList()Return/Print the list (now with all null values removed).
Get the list with null values.
Create a Stream from the list using list.stream()
Filter the stream of elements that are not null using list.filter(x -> x != null)
Collect back the Stream as List using .collect(Collectors.toList()
Return/Print the list (now with all null values removed).
// Java Program to remove nulls// from a List using Apache Common COllection Filter() import java.util.stream.Collectors;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("Initial List: " + list); // Removing nulls using Java Stream // using Predicate condition in lambda expression list = list.stream() .filter(x -> x != null) .collect(Collectors.toList()); // Print the list System.out.println("Modified List: " + list); }}
Initial List: [Geeks, null, forGeeks, null, A computer portal]
Modified List: [Geeks, forGeeks, A computer portal]
Java-ArrayList
java-guava
java-list
Java-List-Programs
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "List is an ordered collection of objects which allows to store duplicate values or null values, in the insertion order. So it is very important to remove null values in many scenarios."
},
{
"code": null,
"e": 223,
"s": 213,
"text": "Examples:"
},
{
"code": null,
"e": 381,
"s": 223,
"text": "Input: [Geeks, null, forGeeks, null, A computer portal]\nOutput: [Geeks, forGeeks, A computer portal]\n\nInput: [1, null, 2, 3, null, 4]\nOutput: [1, 2, 3, 4]\n"
},
{
"code": null,
"e": 440,
"s": 381,
"text": "Below are the methods to remove nulls from a List in Java:"
},
{
"code": null,
"e": 9353,
"s": 440,
"text": "Using List.remove() List interface provides a pre-defined method remove(element) which is used to remove a single occurrence of the element passed, from the List, if found.Algorithm:Get the list with null values.Repeatedly call remove(null) on the list, until all null values are removed.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using List.remove() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using List.remove() // Repeatedly call remove() till all null are removed while (list.remove(null)) { } // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\nUsing List.removeAll(): List interface provides another pre-defined method removeAll(Collection) which is used to remove all occurrences of the elements of the Collection passed, from the List, if found.Algorithm:Get the list with null values.Create a Collection with only null as element using Collections.singletonList(null)Call removeAll(Collection) on the list once.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using List.removeAll() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using List.removeAll() // passing a collection with single element \"null\" list.removeAll(Collections.singletonList(null)); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\nUsing iterator: Iterator is an interface which belongs to collection framework. It allows user to traverse the collection, access the data element and remove the data elements of the collection.Algorithm:Get the list with null values.Create an iterator from the listTraverse through each element of the List with the of created IteratorCheck, for each element, if it is null. If found null, call IteratorElement.remove() on that element.Return/Print the list (now with all null values removed).Program:// Java Program to remove nulls// from a List using iterator import java.util.*; class GFG { // Generic function to remove Null Using Iterator public static <T> List<T> removeNullUsingIterator(List<T> list) { // Create an iterator from the list Iterator<T> itr = list.iterator(); // Find and remove all null while (itr.hasNext()) { if (itr.next() == null) itr.remove(); // remove nulls } // Return the null return list; } public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using iterator list = removeNullUsingIterator(list); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\nUsing Guava Iterables removeIf(): Guava Iterables class provides Iterables.removeIf(Iterable, Predicate) that removes every element from a specified Iterable (or Collections that implements Iterable) that satisfies the provided predicate.Algorithm:Get the list with null values.Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using Guava Iterables import com.google.common.base.Predicates;import com.google.common.collect.Iterables;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Guava Iterables // using Predicate condition isNull() Iterables.removeIf(list, Predicates.isNull()); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\nUsing Apache Commons Collections filter(): Apache Commons Collections CollectionUtils class provides filter(Iterable, Predicate) that removes every element from a specified iterable that do not satisfies the provided predicate.Algorithm:Get the list with null values.Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered.Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance.Return/Print the list (now with all null values removed).Program:// Java Program to remove nulls// from a List using Apache Common COllection Filter()import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.collections4.PredicateUtils;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Apache Common filter() // using Predicate condition notNullPredicate() CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\nUsing Lambdas (Java 8): Stream.filter() method can be used in Java 8 that returns a stream consisting of the elementsthat match the given predicate condition.Algorithm:Get the list with null values.Create a Stream from the list using list.stream()Filter the stream of elements that are not null using list.filter(x -> x != null)Collect back the Stream as List using .collect(Collectors.toList()Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using Apache Common COllection Filter() import java.util.stream.Collectors;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Java Stream // using Predicate condition in lambda expression list = list.stream() .filter(x -> x != null) .collect(Collectors.toList()); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 10554,
"s": 9353,
"text": "Using List.remove() List interface provides a pre-defined method remove(element) which is used to remove a single occurrence of the element passed, from the List, if found.Algorithm:Get the list with null values.Repeatedly call remove(null) on the list, until all null values are removed.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using List.remove() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using List.remove() // Repeatedly call remove() till all null are removed while (list.remove(null)) { } // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 10565,
"s": 10554,
"text": "Algorithm:"
},
{
"code": null,
"e": 10729,
"s": 10565,
"text": "Get the list with null values.Repeatedly call remove(null) on the list, until all null values are removed.Return/Print the list (now with all null values removed)."
},
{
"code": null,
"e": 10760,
"s": 10729,
"text": "Get the list with null values."
},
{
"code": null,
"e": 10837,
"s": 10760,
"text": "Repeatedly call remove(null) on the list, until all null values are removed."
},
{
"code": null,
"e": 10895,
"s": 10837,
"text": "Return/Print the list (now with all null values removed)."
},
{
"code": "// Java Program to remove nulls// from a List using List.remove() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using List.remove() // Repeatedly call remove() till all null are removed while (list.remove(null)) { } // Print the list System.out.println(\"Modified List: \" + list); }}",
"e": 11629,
"s": 10895,
"text": null
},
{
"code": null,
"e": 11745,
"s": 11629,
"text": "Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 13043,
"s": 11745,
"text": "Using List.removeAll(): List interface provides another pre-defined method removeAll(Collection) which is used to remove all occurrences of the elements of the Collection passed, from the List, if found.Algorithm:Get the list with null values.Create a Collection with only null as element using Collections.singletonList(null)Call removeAll(Collection) on the list once.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using List.removeAll() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using List.removeAll() // passing a collection with single element \"null\" list.removeAll(Collections.singletonList(null)); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 13054,
"s": 13043,
"text": "Algorithm:"
},
{
"code": null,
"e": 13269,
"s": 13054,
"text": "Get the list with null values.Create a Collection with only null as element using Collections.singletonList(null)Call removeAll(Collection) on the list once.Return/Print the list (now with all null values removed)."
},
{
"code": null,
"e": 13300,
"s": 13269,
"text": "Get the list with null values."
},
{
"code": null,
"e": 13384,
"s": 13300,
"text": "Create a Collection with only null as element using Collections.singletonList(null)"
},
{
"code": null,
"e": 13429,
"s": 13384,
"text": "Call removeAll(Collection) on the list once."
},
{
"code": null,
"e": 13487,
"s": 13429,
"text": "Return/Print the list (now with all null values removed)."
},
{
"code": "// Java Program to remove nulls// from a List using List.removeAll() import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using List.removeAll() // passing a collection with single element \"null\" list.removeAll(Collections.singletonList(null)); // Print the list System.out.println(\"Modified List: \" + list); }}",
"e": 14236,
"s": 13487,
"text": null
},
{
"code": null,
"e": 14352,
"s": 14236,
"text": "Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 16068,
"s": 14352,
"text": "Using iterator: Iterator is an interface which belongs to collection framework. It allows user to traverse the collection, access the data element and remove the data elements of the collection.Algorithm:Get the list with null values.Create an iterator from the listTraverse through each element of the List with the of created IteratorCheck, for each element, if it is null. If found null, call IteratorElement.remove() on that element.Return/Print the list (now with all null values removed).Program:// Java Program to remove nulls// from a List using iterator import java.util.*; class GFG { // Generic function to remove Null Using Iterator public static <T> List<T> removeNullUsingIterator(List<T> list) { // Create an iterator from the list Iterator<T> itr = list.iterator(); // Find and remove all null while (itr.hasNext()) { if (itr.next() == null) itr.remove(); // remove nulls } // Return the null return list; } public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using iterator list = removeNullUsingIterator(list); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 16079,
"s": 16068,
"text": "Algorithm:"
},
{
"code": null,
"e": 16370,
"s": 16079,
"text": "Get the list with null values.Create an iterator from the listTraverse through each element of the List with the of created IteratorCheck, for each element, if it is null. If found null, call IteratorElement.remove() on that element.Return/Print the list (now with all null values removed)."
},
{
"code": null,
"e": 16401,
"s": 16370,
"text": "Get the list with null values."
},
{
"code": null,
"e": 16434,
"s": 16401,
"text": "Create an iterator from the list"
},
{
"code": null,
"e": 16505,
"s": 16434,
"text": "Traverse through each element of the List with the of created Iterator"
},
{
"code": null,
"e": 16607,
"s": 16505,
"text": "Check, for each element, if it is null. If found null, call IteratorElement.remove() on that element."
},
{
"code": null,
"e": 16665,
"s": 16607,
"text": "Return/Print the list (now with all null values removed)."
},
{
"code": null,
"e": 16674,
"s": 16665,
"text": "Program:"
},
{
"code": "// Java Program to remove nulls// from a List using iterator import java.util.*; class GFG { // Generic function to remove Null Using Iterator public static <T> List<T> removeNullUsingIterator(List<T> list) { // Create an iterator from the list Iterator<T> itr = list.iterator(); // Find and remove all null while (itr.hasNext()) { if (itr.next() == null) itr.remove(); // remove nulls } // Return the null return list; } public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using iterator list = removeNullUsingIterator(list); // Print the list System.out.println(\"Modified List: \" + list); }}",
"e": 17765,
"s": 16674,
"text": null
},
{
"code": null,
"e": 17882,
"s": 17765,
"text": "Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 19384,
"s": 17882,
"text": "Using Guava Iterables removeIf(): Guava Iterables class provides Iterables.removeIf(Iterable, Predicate) that removes every element from a specified Iterable (or Collections that implements Iterable) that satisfies the provided predicate.Algorithm:Get the list with null values.Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance.Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using Guava Iterables import com.google.common.base.Predicates;import com.google.common.collect.Iterables;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Guava Iterables // using Predicate condition isNull() Iterables.removeIf(list, Predicates.isNull()); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 19395,
"s": 19384,
"text": "Algorithm:"
},
{
"code": null,
"e": 19712,
"s": 19395,
"text": "Get the list with null values.Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance.Return/Print the list (now with all null values removed)."
},
{
"code": null,
"e": 19743,
"s": 19712,
"text": "Get the list with null values."
},
{
"code": null,
"e": 19829,
"s": 19743,
"text": "Get the Predicate condition Predicates.isNull() to pass in the argument of removeIf()"
},
{
"code": null,
"e": 19974,
"s": 19829,
"text": "Call Iterables.removeIf(List, Predicate) where List is the original list with null values and the Predicate is the Predicates.isNull() instance."
},
{
"code": null,
"e": 20032,
"s": 19974,
"text": "Return/Print the list (now with all null values removed)."
},
{
"code": "// Java Program to remove nulls// from a List using Guava Iterables import com.google.common.base.Predicates;import com.google.common.collect.Iterables;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Guava Iterables // using Predicate condition isNull() Iterables.removeIf(list, Predicates.isNull()); // Print the list System.out.println(\"Modified List: \" + list); }}",
"e": 20848,
"s": 20032,
"text": null
},
{
"code": null,
"e": 20964,
"s": 20848,
"text": "Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 22699,
"s": 20964,
"text": "Using Apache Commons Collections filter(): Apache Commons Collections CollectionUtils class provides filter(Iterable, Predicate) that removes every element from a specified iterable that do not satisfies the provided predicate.Algorithm:Get the list with null values.Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered.Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance.Return/Print the list (now with all null values removed).Program:// Java Program to remove nulls// from a List using Apache Common COllection Filter()import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.collections4.PredicateUtils;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Apache Common filter() // using Predicate condition notNullPredicate() CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 22710,
"s": 22699,
"text": "Algorithm:"
},
{
"code": null,
"e": 23187,
"s": 22710,
"text": "Get the list with null values.Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered.Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance.Return/Print the list (now with all null values removed)."
},
{
"code": null,
"e": 23218,
"s": 23187,
"text": "Get the list with null values."
},
{
"code": null,
"e": 23422,
"s": 23218,
"text": "Get the Predicate condition PredicateUtils.notNullPredicate() to pass in the argument of filter() such that the elements passing the condition of NotNull remain in the list, while all other get filtered."
},
{
"code": null,
"e": 23609,
"s": 23422,
"text": "Call CollectionUtils.filter(list, PredicateUtils.notNullPredicate()) where List is the original list with null values and the Predicate is the PredicateUtils.notNullPredicate() instance."
},
{
"code": null,
"e": 23667,
"s": 23609,
"text": "Return/Print the list (now with all null values removed)."
},
{
"code": null,
"e": 23676,
"s": 23667,
"text": "Program:"
},
{
"code": "// Java Program to remove nulls// from a List using Apache Common COllection Filter()import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.collections4.PredicateUtils;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Apache Common filter() // using Predicate condition notNullPredicate() CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); // Print the list System.out.println(\"Modified List: \" + list); }}",
"e": 24568,
"s": 23676,
"text": null
},
{
"code": null,
"e": 24684,
"s": 24568,
"text": "Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 26150,
"s": 24684,
"text": "Using Lambdas (Java 8): Stream.filter() method can be used in Java 8 that returns a stream consisting of the elementsthat match the given predicate condition.Algorithm:Get the list with null values.Create a Stream from the list using list.stream()Filter the stream of elements that are not null using list.filter(x -> x != null)Collect back the Stream as List using .collect(Collectors.toList()Return/Print the list (now with all null values removed).// Java Program to remove nulls// from a List using Apache Common COllection Filter() import java.util.stream.Collectors;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Java Stream // using Predicate condition in lambda expression list = list.stream() .filter(x -> x != null) .collect(Collectors.toList()); // Print the list System.out.println(\"Modified List: \" + list); }}Output:Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 26161,
"s": 26150,
"text": "Algorithm:"
},
{
"code": null,
"e": 26445,
"s": 26161,
"text": "Get the list with null values.Create a Stream from the list using list.stream()Filter the stream of elements that are not null using list.filter(x -> x != null)Collect back the Stream as List using .collect(Collectors.toList()Return/Print the list (now with all null values removed)."
},
{
"code": null,
"e": 26476,
"s": 26445,
"text": "Get the list with null values."
},
{
"code": null,
"e": 26526,
"s": 26476,
"text": "Create a Stream from the list using list.stream()"
},
{
"code": null,
"e": 26608,
"s": 26526,
"text": "Filter the stream of elements that are not null using list.filter(x -> x != null)"
},
{
"code": null,
"e": 26675,
"s": 26608,
"text": "Collect back the Stream as List using .collect(Collectors.toList()"
},
{
"code": null,
"e": 26733,
"s": 26675,
"text": "Return/Print the list (now with all null values removed)."
},
{
"code": "// Java Program to remove nulls// from a List using Apache Common COllection Filter() import java.util.stream.Collectors;import java.util.*; class GFG { public static void main(String[] args) { // Create the list with null values List<String> list = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"Initial List: \" + list); // Removing nulls using Java Stream // using Predicate condition in lambda expression list = list.stream() .filter(x -> x != null) .collect(Collectors.toList()); // Print the list System.out.println(\"Modified List: \" + list); }}",
"e": 27591,
"s": 26733,
"text": null
},
{
"code": null,
"e": 27707,
"s": 27591,
"text": "Initial List: [Geeks, null, forGeeks, null, A computer portal]\nModified List: [Geeks, forGeeks, A computer portal]\n"
},
{
"code": null,
"e": 27722,
"s": 27707,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 27733,
"s": 27722,
"text": "java-guava"
},
{
"code": null,
"e": 27743,
"s": 27733,
"text": "java-list"
},
{
"code": null,
"e": 27762,
"s": 27743,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 27767,
"s": 27762,
"text": "Java"
},
{
"code": null,
"e": 27772,
"s": 27767,
"text": "Java"
}
] |
Java Program to Create an Object for Class and Assign Value in the Object Using Constructor
|
11 Nov, 2020
Java is one of the most popular programming languages. It is an object-oriented programming language which means that we can create classes, objects, and many more. It also supports inheritance, polymorphism, encapsulation, and many more. It is used in all applications starting from mobile applications to web-based applications. Classes are defined as the blue-print or template from which we can create objects and objects are the instances of the class which consist of states and behaviors.
Approach:
First, define a class with any name ‘SampleClass’ and define a constructor method.
The constructor will always have the same name as the class name and it does not have a return type.
Constructors are used to instantiating variables of the class.
Now, using the constructors we can assign values.
After the constructor method, implement a function that returns the value of any variables.
Now in the main function create an object using the ‘new’ keyword. If there is no user-defined constructor of the class, then the default constructor of the class is called else when the object is created the user-defined constructor is called as per the type and number of parameters matched with the constructor of the class.
We can call the above-declared function using the object.
At last print the value from the function using the System.out.println() statement.
Once you are done with the implementation run the program and will get the output.
Example 1:
Java
// Java program to show the class declaration // and how to create an instance of this class // Class Declaration public class Student{ // Instance Variables String name; String course; int age; // Constructor Declaration of Class public Student(String name, String course,int age) { this.name = name; this.course = course; this.age = age; } // method 1 public String getName() { return name; } public static void main(String[] args) { // creating object using new operator Student s1 = new Student("Ravi","CSE",23); System.out.println(s1.getName()); }}
Output:
Ravi
Example 2:
Java
// Java program to show the class declaration // and how to create an instance of this class // Class Declaration public class Computer{ // Instance Variables String name; String config; int cost; String os; // Constructor Declaration of Class public Computer(String name, String config, int cost, String os) { this.name = name; this.config = config; this.cost = cost; this.os = os; } // method 1 public String getName() { return name; } // method 2 public String getConfig() { return config; } // method 3 public int getCost() { return cost; } // method 4 public String getOs() { return os; } public static void main(String[] args) { // creating object using new operator Computer c1 = new Computer("Apple","i5", 50000, "IOS"); System.out.println("The company name is "+ c1.getName()); System.out.println("The configuration is "+ c1.getConfig()); System.out.println("Its Cost is "+ c1.getCost()); System.out.println("Its operating System "+ c1.getOs()); }}
Output:
The company name is Apple
The configuration is i5
Its Cost is 50000
Its operating System IOS
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Nov, 2020"
},
{
"code": null,
"e": 549,
"s": 53,
"text": "Java is one of the most popular programming languages. It is an object-oriented programming language which means that we can create classes, objects, and many more. It also supports inheritance, polymorphism, encapsulation, and many more. It is used in all applications starting from mobile applications to web-based applications. Classes are defined as the blue-print or template from which we can create objects and objects are the instances of the class which consist of states and behaviors."
},
{
"code": null,
"e": 559,
"s": 549,
"text": "Approach:"
},
{
"code": null,
"e": 642,
"s": 559,
"text": "First, define a class with any name ‘SampleClass’ and define a constructor method."
},
{
"code": null,
"e": 743,
"s": 642,
"text": "The constructor will always have the same name as the class name and it does not have a return type."
},
{
"code": null,
"e": 806,
"s": 743,
"text": "Constructors are used to instantiating variables of the class."
},
{
"code": null,
"e": 856,
"s": 806,
"text": "Now, using the constructors we can assign values."
},
{
"code": null,
"e": 948,
"s": 856,
"text": "After the constructor method, implement a function that returns the value of any variables."
},
{
"code": null,
"e": 1278,
"s": 948,
"text": "Now in the main function create an object using the ‘new’ keyword. If there is no user-defined constructor of the class, then the default constructor of the class is called else when the object is created the user-defined constructor is called as per the type and number of parameters matched with the constructor of the class. "
},
{
"code": null,
"e": 1336,
"s": 1278,
"text": "We can call the above-declared function using the object."
},
{
"code": null,
"e": 1420,
"s": 1336,
"text": "At last print the value from the function using the System.out.println() statement."
},
{
"code": null,
"e": 1503,
"s": 1420,
"text": "Once you are done with the implementation run the program and will get the output."
},
{
"code": null,
"e": 1514,
"s": 1503,
"text": "Example 1:"
},
{
"code": null,
"e": 1519,
"s": 1514,
"text": "Java"
},
{
"code": "// Java program to show the class declaration // and how to create an instance of this class // Class Declaration public class Student{ // Instance Variables String name; String course; int age; // Constructor Declaration of Class public Student(String name, String course,int age) { this.name = name; this.course = course; this.age = age; } // method 1 public String getName() { return name; } public static void main(String[] args) { // creating object using new operator Student s1 = new Student(\"Ravi\",\"CSE\",23); System.out.println(s1.getName()); }}",
"e": 2187,
"s": 1519,
"text": null
},
{
"code": null,
"e": 2195,
"s": 2187,
"text": "Output:"
},
{
"code": null,
"e": 2201,
"s": 2195,
"text": "Ravi\n"
},
{
"code": null,
"e": 2212,
"s": 2201,
"text": "Example 2:"
},
{
"code": null,
"e": 2217,
"s": 2212,
"text": "Java"
},
{
"code": "// Java program to show the class declaration // and how to create an instance of this class // Class Declaration public class Computer{ // Instance Variables String name; String config; int cost; String os; // Constructor Declaration of Class public Computer(String name, String config, int cost, String os) { this.name = name; this.config = config; this.cost = cost; this.os = os; } // method 1 public String getName() { return name; } // method 2 public String getConfig() { return config; } // method 3 public int getCost() { return cost; } // method 4 public String getOs() { return os; } public static void main(String[] args) { // creating object using new operator Computer c1 = new Computer(\"Apple\",\"i5\", 50000, \"IOS\"); System.out.println(\"The company name is \"+ c1.getName()); System.out.println(\"The configuration is \"+ c1.getConfig()); System.out.println(\"Its Cost is \"+ c1.getCost()); System.out.println(\"Its operating System \"+ c1.getOs()); }}",
"e": 3397,
"s": 2217,
"text": null
},
{
"code": null,
"e": 3405,
"s": 3397,
"text": "Output:"
},
{
"code": null,
"e": 3501,
"s": 3405,
"text": "The company name is Apple\nThe configuration is i5\nIts Cost is 50000\nIts operating System IOS\n"
},
{
"code": null,
"e": 3506,
"s": 3501,
"text": "Java"
},
{
"code": null,
"e": 3520,
"s": 3506,
"text": "Java Programs"
},
{
"code": null,
"e": 3525,
"s": 3520,
"text": "Java"
}
] |
Median of Stream of Running Integers using STL
|
21 Jun, 2022
Given that integers are being read from a data stream. Find the median of all the elements read so far starting from the first integer till the last integer. This is also called the Median of Running Integers. The data stream can be any source of data, for example, a file, an array of integers, input stream etc.
What is Median?
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Median can be defined as the element in the data set which separates the higher half of the data sample from the lower half. In other words, we can get the median element as, when the input size is odd, we take the middle element of sorted data. If the input size is even, we pick an average of middle two elements in the sorted stream.Examples:
Input: 5 10 15 Output: 5, 7.5, 10 Explanation: Given the input stream as an array of integers [5,10,15]. Read integers one by one and print the median correspondingly. So, after reading first element 5,median is 5. After reading 10,median is 7.5 After reading 15 ,median is 10.Input: 1, 2, 3, 4 Output: 1, 1.5, 2, 2.5 Explanation: Given the input stream as an array of integers [1, 2, 3, 4]. Read integers one by one and print the median correspondingly. So, after reading first element 1,median is 1. After reading 2,median is 1.5 After reading 3 ,median is 2.After reading 4 ,median is 2.5.
Approach: The idea is to use max heap and min heap to store the elements of higher half and lower half. Max heap and min heap can be implemented using priority_queue in C++ STL. Below is the step by step algorithm to solve this problem.Algorithm:
Create two heaps. One max heap to maintain elements of lower half and one min heap to maintain elements of higher half at any point of time..Take initial value of median as 0.For every newly read element, insert it into either max heap or min-heap and calculate the median based on the following conditions: If the size of max heap is greater than the size of min-heap and the element is less than the previous median then pop the top element from max heap and insert into min-heap and insert the new element to max heap else insert the new element to min-heap. Calculate the new median as the average of top of elements of both max and min heap.If the size of max heap is less than the size of min-heap and the element is greater than the previous median then pop the top element from min-heap and insert into the max heap and insert the new element to min heap else insert the new element to the max heap. Calculate the new median as the average of top of elements of both max and min heap.If the size of both heaps is the same. Then check if the current is less than the previous median or not. If the current element is less than the previous median then insert it to the max heap and a new median will be equal to the top element of max heap. If the current element is greater than the previous median then insert it to min-heap and new median will be equal to the top element of min heap.
Create two heaps. One max heap to maintain elements of lower half and one min heap to maintain elements of higher half at any point of time..
Take initial value of median as 0.
For every newly read element, insert it into either max heap or min-heap and calculate the median based on the following conditions: If the size of max heap is greater than the size of min-heap and the element is less than the previous median then pop the top element from max heap and insert into min-heap and insert the new element to max heap else insert the new element to min-heap. Calculate the new median as the average of top of elements of both max and min heap.If the size of max heap is less than the size of min-heap and the element is greater than the previous median then pop the top element from min-heap and insert into the max heap and insert the new element to min heap else insert the new element to the max heap. Calculate the new median as the average of top of elements of both max and min heap.If the size of both heaps is the same. Then check if the current is less than the previous median or not. If the current element is less than the previous median then insert it to the max heap and a new median will be equal to the top element of max heap. If the current element is greater than the previous median then insert it to min-heap and new median will be equal to the top element of min heap.
If the size of max heap is greater than the size of min-heap and the element is less than the previous median then pop the top element from max heap and insert into min-heap and insert the new element to max heap else insert the new element to min-heap. Calculate the new median as the average of top of elements of both max and min heap.
If the size of max heap is less than the size of min-heap and the element is greater than the previous median then pop the top element from min-heap and insert into the max heap and insert the new element to min heap else insert the new element to the max heap. Calculate the new median as the average of top of elements of both max and min heap.
If the size of both heaps is the same. Then check if the current is less than the previous median or not. If the current element is less than the previous median then insert it to the max heap and a new median will be equal to the top element of max heap. If the current element is greater than the previous median then insert it to min-heap and new median will be equal to the top element of min heap.
Below is the implementation of above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find med in// stream of running integers#include<bits/stdc++.h>using namespace std; // function to calculate med of streamvoid printMedians(double arr[], int n){ // max heap to store the smaller half elements priority_queue<double> s; // min heap to store the greater half elements priority_queue<double,vector<double>,greater<double> > g; double med = arr[0]; s.push(arr[0]); cout << med << endl; // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for (int i=1; i < n; i++) { double x = arr[i]; // case1(left side heap has more elements) if (s.size() > g.size()) { if (x < med) { g.push(s.top()); s.pop(); s.push(x); } else g.push(x); med = (s.top() + g.top())/2.0; } // case2(both heaps are balanced) else if (s.size()==g.size()) { if (x < med) { s.push(x); med = (double)s.top(); } else { g.push(x); med = (double)g.top(); } } // case3(right side heap has more elements) else { if (x > med) { s.push(g.top()); g.pop(); g.push(x); } else s.push(x); med = (s.top() + g.top())/2.0; } cout << med << endl; }} // Driver program to test above functionsint main(){ // stream of integers double arr[] = {5, 15, 10, 20, 3}; int n = sizeof(arr)/sizeof(arr[0]); printMedians(arr, n); return 0;}
// Java program to find med in// stream of running integersimport java.util.Collections;import java.util.PriorityQueue; public class MedianMaintain{ // method to calculate med of stream public static void printMedian(int[] a) { double med = a[0]; // max heap to store the smaller half elements PriorityQueue<Integer> smaller = new PriorityQueue<> (Collections.reverseOrder()); // min-heap to store the greater half elements PriorityQueue<Integer> greater = new PriorityQueue<>(); smaller.add(a[0]); System.out.println(med); // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for(int i = 1; i < a.length; i++) { int x = a[i]; // case1(left side heap has more elements) if(smaller.size() > greater.size()) { if(x < med) { greater.add(smaller.remove()); smaller.add(x); } else greater.add(x); med = (double)(smaller.peek() + greater.peek())/2; } // case2(both heaps are balanced) else if(smaller.size() == greater.size()) { if(x < med) { smaller.add(x); med = (double)smaller.peek(); } else { greater.add(x); med = (double)greater.peek(); } } // case3(right side heap has more elements) else { if(x > med) { smaller.add(greater.remove()); greater.add(x); } else smaller.add(x); med = (double)(smaller.peek() + greater.peek())/2; } System.out.println(med); } } // Driver code public static void main(String []args) { // stream of integers int[] arr = new int[]{5, 15, 10, 20, 3}; printMedian(arr); }} // This code is contributed by Kaustav kumar Chanda.
# python3 program to find med in# stream of running integersfrom heapq import * # function to calculate med of streamdef printMedians(arr, n): # max heap to store the smaller half elements s = [] # min heap to store the greater half elements g = [] heapify(s) heapify(g) med = arr[0] heappush(s, arr[0]) print(med) # reading elements of stream one by one for i in range(1, n): x = arr[i] # case1(left side heap has more elements) if len(s) > len(g): if x < med: heappush(g, heappop(s)) heappush(s, x) else: heappush(g, x) med = (nlargest(1, s)[0] + nsmallest(1, g)[0])/2 # case2(both heaps are balanced) elif len(s) == len(g): if x < med: heappush(s, x) med = nlargest(1, s)[0] else: heappush(g, x) med = nsmallest(1, g)[0] # case3(right side heap has more elements) else: if x > med: heappush(s, heappop(g)) heappush(g, x) else: heappush(s, x) med = (nlargest(1, s)[0] + nsmallest(1, g)[0])/2 print(med) # Driver program to test above functionsarr = [5, 15, 10, 20, 3]printMedians(arr, len(arr)) # This code is contributed by cavi4762.
// C# program to find med in// stream of running integersusing System;using System.Collections.Generic;public class MedianMaintain{ // method to calculate med of stream public static void printMedian(int[] a) { double med = a[0]; // max heap to store the smaller half elements List<int> smaller = new List<int>(); // min-heap to store the greater half elements List<int> greater = new List<int>(); smaller.Add(a[0]); Console.WriteLine(med); // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for(int i = 1; i < a.Length; i++) { int x = a[i]; // case1(left side heap has more elements) if(smaller.Count > greater.Count) { if(x < med) { smaller.Sort(); smaller.Reverse(); greater.Add(smaller[0]); smaller.RemoveAt(0); smaller.Add(x); } else greater.Add(x); smaller.Sort(); smaller.Reverse(); greater.Sort(); med = (double)(smaller[0] + greater[0])/2; } // case2(both heaps are balanced) else if(smaller.Count == greater.Count) { if(x < med) { smaller.Add(x); smaller.Sort(); smaller.Reverse(); med = (double)smaller[0]; } else { greater.Add(x); greater.Sort(); med = (double)greater[0]; } } // case3(right side heap has more elements) else { if(x > med) { greater.Sort(); smaller.Add(greater[0]); greater.RemoveAt(0); greater.Add(x); } else smaller.Add(x); smaller.Sort(); smaller.Reverse(); med = (double)(smaller[0] + greater[0])/2; } Console.WriteLine(med); } } // Driver code public static void Main(String []args) { // stream of integers int[] arr = new int[]{5, 15, 10, 20, 3}; printMedian(arr); }} // This code is contributed by Rajput-Ji
<script>// Javascript program to find med in// stream of running integers // method to calculate med of streamfunction printMedian(a){ let med = a[0]; // max heap to store the smaller half elements let smaller = []; // min-heap to store the greater half elements let greater = []; smaller.push(a[0]); document.write(med+"<br>"); // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for(let i = 1; i < a.length; i++) { let x = a[i]; // case1(left side heap has more elements) if(smaller.length > greater.length) { if(x < med) { smaller.sort(function(a,b){return b-a;}); greater.push(smaller.shift()); smaller.push(x); } else { greater.push(x);} smaller.sort(function(a,b){return b-a;}); greater.sort(function(a,b){return a-b;}); med = (smaller[0] + greater[0])/2; } // case2(both heaps are balanced) else if(smaller.length == greater.length) { if(x < med) { smaller.push(x); smaller.sort(function(a,b){return b-a;}); med = smaller[0]; } else { greater.push(x); greater.sort(function(a,b){return a-b;}); med = greater[0]; } } // case3(right side heap has more elements) else { if(x > med) { greater.sort(function(a,b){return a-b;}); smaller.push(greater.shift()); greater.push(x); } else { smaller.push(x);} smaller.sort(function(a,b){return b-a;}); med = (smaller[0] + greater[0])/2; } document.write(med+"<br>"); }} // Driver code// stream of integerslet arr=[5, 15, 10, 20, 3];printMedian(arr); // This code is contributed by avanitrachhadiya2155</script>
5
10
10
12.5
10
Complexity Analysis:
Time Complexity: O(n Log n). Time Complexity to insert element in min heap is log n. So to insert n element is O( n log n).
Auxiliary Space : O(n). The Space required to store the elements in Heap is O(n).
Median of Stream of Running Integers using STL | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersMedian of Stream of Running Integers using STL | 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 / 2:26•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=XpLJmPzpcCg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Vibhu Garg. 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.
Kaustav kumar Chanda
Akanksha_Rai
andrew1234
Rajput-Ji
avanitrachhadiya2155
cavi4762
Adobe
Amazon
Apple
Belzabar
Facebook
featured
Google
Microsoft
Morgan Stanley
Ola Cabs
Oracle
Order-Statistics
SAP Labs
statistical-algorithms
STL
Yahoo
Heap
Morgan Stanley
Amazon
Microsoft
Ola Cabs
Oracle
Adobe
Google
SAP Labs
Facebook
Yahoo
Belzabar
Apple
Heap
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 367,
"s": 52,
"text": "Given that integers are being read from a data stream. Find the median of all the elements read so far starting from the first integer till the last integer. This is also called the Median of Running Integers. The data stream can be any source of data, for example, a file, an array of integers, input stream etc. "
},
{
"code": null,
"e": 383,
"s": 367,
"text": "What is Median?"
},
{
"code": null,
"e": 392,
"s": 383,
"text": "Chapters"
},
{
"code": null,
"e": 419,
"s": 392,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 469,
"s": 419,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 492,
"s": 469,
"text": "captions off, selected"
},
{
"code": null,
"e": 500,
"s": 492,
"text": "English"
},
{
"code": null,
"e": 524,
"s": 500,
"text": "This is a modal window."
},
{
"code": null,
"e": 593,
"s": 524,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 615,
"s": 593,
"text": "End of dialog window."
},
{
"code": null,
"e": 963,
"s": 615,
"text": "Median can be defined as the element in the data set which separates the higher half of the data sample from the lower half. In other words, we can get the median element as, when the input size is odd, we take the middle element of sorted data. If the input size is even, we pick an average of middle two elements in the sorted stream.Examples: "
},
{
"code": null,
"e": 1558,
"s": 963,
"text": "Input: 5 10 15 Output: 5, 7.5, 10 Explanation: Given the input stream as an array of integers [5,10,15]. Read integers one by one and print the median correspondingly. So, after reading first element 5,median is 5. After reading 10,median is 7.5 After reading 15 ,median is 10.Input: 1, 2, 3, 4 Output: 1, 1.5, 2, 2.5 Explanation: Given the input stream as an array of integers [1, 2, 3, 4]. Read integers one by one and print the median correspondingly. So, after reading first element 1,median is 1. After reading 2,median is 1.5 After reading 3 ,median is 2.After reading 4 ,median is 2.5. "
},
{
"code": null,
"e": 1809,
"s": 1560,
"text": "Approach: The idea is to use max heap and min heap to store the elements of higher half and lower half. Max heap and min heap can be implemented using priority_queue in C++ STL. Below is the step by step algorithm to solve this problem.Algorithm: "
},
{
"code": null,
"e": 3204,
"s": 1809,
"text": "Create two heaps. One max heap to maintain elements of lower half and one min heap to maintain elements of higher half at any point of time..Take initial value of median as 0.For every newly read element, insert it into either max heap or min-heap and calculate the median based on the following conditions: If the size of max heap is greater than the size of min-heap and the element is less than the previous median then pop the top element from max heap and insert into min-heap and insert the new element to max heap else insert the new element to min-heap. Calculate the new median as the average of top of elements of both max and min heap.If the size of max heap is less than the size of min-heap and the element is greater than the previous median then pop the top element from min-heap and insert into the max heap and insert the new element to min heap else insert the new element to the max heap. Calculate the new median as the average of top of elements of both max and min heap.If the size of both heaps is the same. Then check if the current is less than the previous median or not. If the current element is less than the previous median then insert it to the max heap and a new median will be equal to the top element of max heap. If the current element is greater than the previous median then insert it to min-heap and new median will be equal to the top element of min heap."
},
{
"code": null,
"e": 3346,
"s": 3204,
"text": "Create two heaps. One max heap to maintain elements of lower half and one min heap to maintain elements of higher half at any point of time.."
},
{
"code": null,
"e": 3381,
"s": 3346,
"text": "Take initial value of median as 0."
},
{
"code": null,
"e": 4601,
"s": 3381,
"text": "For every newly read element, insert it into either max heap or min-heap and calculate the median based on the following conditions: If the size of max heap is greater than the size of min-heap and the element is less than the previous median then pop the top element from max heap and insert into min-heap and insert the new element to max heap else insert the new element to min-heap. Calculate the new median as the average of top of elements of both max and min heap.If the size of max heap is less than the size of min-heap and the element is greater than the previous median then pop the top element from min-heap and insert into the max heap and insert the new element to min heap else insert the new element to the max heap. Calculate the new median as the average of top of elements of both max and min heap.If the size of both heaps is the same. Then check if the current is less than the previous median or not. If the current element is less than the previous median then insert it to the max heap and a new median will be equal to the top element of max heap. If the current element is greater than the previous median then insert it to min-heap and new median will be equal to the top element of min heap."
},
{
"code": null,
"e": 4940,
"s": 4601,
"text": "If the size of max heap is greater than the size of min-heap and the element is less than the previous median then pop the top element from max heap and insert into min-heap and insert the new element to max heap else insert the new element to min-heap. Calculate the new median as the average of top of elements of both max and min heap."
},
{
"code": null,
"e": 5287,
"s": 4940,
"text": "If the size of max heap is less than the size of min-heap and the element is greater than the previous median then pop the top element from min-heap and insert into the max heap and insert the new element to min heap else insert the new element to the max heap. Calculate the new median as the average of top of elements of both max and min heap."
},
{
"code": null,
"e": 5690,
"s": 5287,
"text": "If the size of both heaps is the same. Then check if the current is less than the previous median or not. If the current element is less than the previous median then insert it to the max heap and a new median will be equal to the top element of max heap. If the current element is greater than the previous median then insert it to min-heap and new median will be equal to the top element of min heap."
},
{
"code": null,
"e": 5739,
"s": 5690,
"text": "Below is the implementation of above approach. "
},
{
"code": null,
"e": 5743,
"s": 5739,
"text": "C++"
},
{
"code": null,
"e": 5748,
"s": 5743,
"text": "Java"
},
{
"code": null,
"e": 5756,
"s": 5748,
"text": "Python3"
},
{
"code": null,
"e": 5759,
"s": 5756,
"text": "C#"
},
{
"code": null,
"e": 5770,
"s": 5759,
"text": "Javascript"
},
{
"code": "// C++ program to find med in// stream of running integers#include<bits/stdc++.h>using namespace std; // function to calculate med of streamvoid printMedians(double arr[], int n){ // max heap to store the smaller half elements priority_queue<double> s; // min heap to store the greater half elements priority_queue<double,vector<double>,greater<double> > g; double med = arr[0]; s.push(arr[0]); cout << med << endl; // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for (int i=1; i < n; i++) { double x = arr[i]; // case1(left side heap has more elements) if (s.size() > g.size()) { if (x < med) { g.push(s.top()); s.pop(); s.push(x); } else g.push(x); med = (s.top() + g.top())/2.0; } // case2(both heaps are balanced) else if (s.size()==g.size()) { if (x < med) { s.push(x); med = (double)s.top(); } else { g.push(x); med = (double)g.top(); } } // case3(right side heap has more elements) else { if (x > med) { s.push(g.top()); g.pop(); g.push(x); } else s.push(x); med = (s.top() + g.top())/2.0; } cout << med << endl; }} // Driver program to test above functionsint main(){ // stream of integers double arr[] = {5, 15, 10, 20, 3}; int n = sizeof(arr)/sizeof(arr[0]); printMedians(arr, n); return 0;}",
"e": 7795,
"s": 5770,
"text": null
},
{
"code": "// Java program to find med in// stream of running integersimport java.util.Collections;import java.util.PriorityQueue; public class MedianMaintain{ // method to calculate med of stream public static void printMedian(int[] a) { double med = a[0]; // max heap to store the smaller half elements PriorityQueue<Integer> smaller = new PriorityQueue<> (Collections.reverseOrder()); // min-heap to store the greater half elements PriorityQueue<Integer> greater = new PriorityQueue<>(); smaller.add(a[0]); System.out.println(med); // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for(int i = 1; i < a.length; i++) { int x = a[i]; // case1(left side heap has more elements) if(smaller.size() > greater.size()) { if(x < med) { greater.add(smaller.remove()); smaller.add(x); } else greater.add(x); med = (double)(smaller.peek() + greater.peek())/2; } // case2(both heaps are balanced) else if(smaller.size() == greater.size()) { if(x < med) { smaller.add(x); med = (double)smaller.peek(); } else { greater.add(x); med = (double)greater.peek(); } } // case3(right side heap has more elements) else { if(x > med) { smaller.add(greater.remove()); greater.add(x); } else smaller.add(x); med = (double)(smaller.peek() + greater.peek())/2; } System.out.println(med); } } // Driver code public static void main(String []args) { // stream of integers int[] arr = new int[]{5, 15, 10, 20, 3}; printMedian(arr); }} // This code is contributed by Kaustav kumar Chanda.",
"e": 10421,
"s": 7795,
"text": null
},
{
"code": "# python3 program to find med in# stream of running integersfrom heapq import * # function to calculate med of streamdef printMedians(arr, n): # max heap to store the smaller half elements s = [] # min heap to store the greater half elements g = [] heapify(s) heapify(g) med = arr[0] heappush(s, arr[0]) print(med) # reading elements of stream one by one for i in range(1, n): x = arr[i] # case1(left side heap has more elements) if len(s) > len(g): if x < med: heappush(g, heappop(s)) heappush(s, x) else: heappush(g, x) med = (nlargest(1, s)[0] + nsmallest(1, g)[0])/2 # case2(both heaps are balanced) elif len(s) == len(g): if x < med: heappush(s, x) med = nlargest(1, s)[0] else: heappush(g, x) med = nsmallest(1, g)[0] # case3(right side heap has more elements) else: if x > med: heappush(s, heappop(g)) heappush(g, x) else: heappush(s, x) med = (nlargest(1, s)[0] + nsmallest(1, g)[0])/2 print(med) # Driver program to test above functionsarr = [5, 15, 10, 20, 3]printMedians(arr, len(arr)) # This code is contributed by cavi4762.",
"e": 11793,
"s": 10421,
"text": null
},
{
"code": "// C# program to find med in// stream of running integersusing System;using System.Collections.Generic;public class MedianMaintain{ // method to calculate med of stream public static void printMedian(int[] a) { double med = a[0]; // max heap to store the smaller half elements List<int> smaller = new List<int>(); // min-heap to store the greater half elements List<int> greater = new List<int>(); smaller.Add(a[0]); Console.WriteLine(med); // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for(int i = 1; i < a.Length; i++) { int x = a[i]; // case1(left side heap has more elements) if(smaller.Count > greater.Count) { if(x < med) { smaller.Sort(); smaller.Reverse(); greater.Add(smaller[0]); smaller.RemoveAt(0); smaller.Add(x); } else greater.Add(x); smaller.Sort(); smaller.Reverse(); greater.Sort(); med = (double)(smaller[0] + greater[0])/2; } // case2(both heaps are balanced) else if(smaller.Count == greater.Count) { if(x < med) { smaller.Add(x); smaller.Sort(); smaller.Reverse(); med = (double)smaller[0]; } else { greater.Add(x); greater.Sort(); med = (double)greater[0]; } } // case3(right side heap has more elements) else { if(x > med) { greater.Sort(); smaller.Add(greater[0]); greater.RemoveAt(0); greater.Add(x); } else smaller.Add(x); smaller.Sort(); smaller.Reverse(); med = (double)(smaller[0] + greater[0])/2; } Console.WriteLine(med); } } // Driver code public static void Main(String []args) { // stream of integers int[] arr = new int[]{5, 15, 10, 20, 3}; printMedian(arr); }} // This code is contributed by Rajput-Ji",
"e": 14112,
"s": 11793,
"text": null
},
{
"code": "<script>// Javascript program to find med in// stream of running integers // method to calculate med of streamfunction printMedian(a){ let med = a[0]; // max heap to store the smaller half elements let smaller = []; // min-heap to store the greater half elements let greater = []; smaller.push(a[0]); document.write(med+\"<br>\"); // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for(let i = 1; i < a.length; i++) { let x = a[i]; // case1(left side heap has more elements) if(smaller.length > greater.length) { if(x < med) { smaller.sort(function(a,b){return b-a;}); greater.push(smaller.shift()); smaller.push(x); } else { greater.push(x);} smaller.sort(function(a,b){return b-a;}); greater.sort(function(a,b){return a-b;}); med = (smaller[0] + greater[0])/2; } // case2(both heaps are balanced) else if(smaller.length == greater.length) { if(x < med) { smaller.push(x); smaller.sort(function(a,b){return b-a;}); med = smaller[0]; } else { greater.push(x); greater.sort(function(a,b){return a-b;}); med = greater[0]; } } // case3(right side heap has more elements) else { if(x > med) { greater.sort(function(a,b){return a-b;}); smaller.push(greater.shift()); greater.push(x); } else { smaller.push(x);} smaller.sort(function(a,b){return b-a;}); med = (smaller[0] + greater[0])/2; } document.write(med+\"<br>\"); }} // Driver code// stream of integerslet arr=[5, 15, 10, 20, 3];printMedian(arr); // This code is contributed by avanitrachhadiya2155</script>",
"e": 16941,
"s": 14112,
"text": null
},
{
"code": null,
"e": 16957,
"s": 16941,
"text": "5\n10\n10\n12.5\n10"
},
{
"code": null,
"e": 16982,
"s": 16959,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 17106,
"s": 16982,
"text": "Time Complexity: O(n Log n). Time Complexity to insert element in min heap is log n. So to insert n element is O( n log n)."
},
{
"code": null,
"e": 17188,
"s": 17106,
"text": "Auxiliary Space : O(n). The Space required to store the elements in Heap is O(n)."
},
{
"code": null,
"e": 18100,
"s": 17190,
"text": "Median of Stream of Running Integers using STL | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersMedian of Stream of Running Integers using STL | 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 / 2:26•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=XpLJmPzpcCg\" 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": 18519,
"s": 18100,
"text": "This article is contributed by Vibhu Garg. 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": 18540,
"s": 18519,
"text": "Kaustav kumar Chanda"
},
{
"code": null,
"e": 18553,
"s": 18540,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 18564,
"s": 18553,
"text": "andrew1234"
},
{
"code": null,
"e": 18574,
"s": 18564,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 18595,
"s": 18574,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 18604,
"s": 18595,
"text": "cavi4762"
},
{
"code": null,
"e": 18610,
"s": 18604,
"text": "Adobe"
},
{
"code": null,
"e": 18617,
"s": 18610,
"text": "Amazon"
},
{
"code": null,
"e": 18623,
"s": 18617,
"text": "Apple"
},
{
"code": null,
"e": 18632,
"s": 18623,
"text": "Belzabar"
},
{
"code": null,
"e": 18641,
"s": 18632,
"text": "Facebook"
},
{
"code": null,
"e": 18650,
"s": 18641,
"text": "featured"
},
{
"code": null,
"e": 18657,
"s": 18650,
"text": "Google"
},
{
"code": null,
"e": 18667,
"s": 18657,
"text": "Microsoft"
},
{
"code": null,
"e": 18682,
"s": 18667,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 18691,
"s": 18682,
"text": "Ola Cabs"
},
{
"code": null,
"e": 18698,
"s": 18691,
"text": "Oracle"
},
{
"code": null,
"e": 18715,
"s": 18698,
"text": "Order-Statistics"
},
{
"code": null,
"e": 18724,
"s": 18715,
"text": "SAP Labs"
},
{
"code": null,
"e": 18747,
"s": 18724,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 18751,
"s": 18747,
"text": "STL"
},
{
"code": null,
"e": 18757,
"s": 18751,
"text": "Yahoo"
},
{
"code": null,
"e": 18762,
"s": 18757,
"text": "Heap"
},
{
"code": null,
"e": 18777,
"s": 18762,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 18784,
"s": 18777,
"text": "Amazon"
},
{
"code": null,
"e": 18794,
"s": 18784,
"text": "Microsoft"
},
{
"code": null,
"e": 18803,
"s": 18794,
"text": "Ola Cabs"
},
{
"code": null,
"e": 18810,
"s": 18803,
"text": "Oracle"
},
{
"code": null,
"e": 18816,
"s": 18810,
"text": "Adobe"
},
{
"code": null,
"e": 18823,
"s": 18816,
"text": "Google"
},
{
"code": null,
"e": 18832,
"s": 18823,
"text": "SAP Labs"
},
{
"code": null,
"e": 18841,
"s": 18832,
"text": "Facebook"
},
{
"code": null,
"e": 18847,
"s": 18841,
"text": "Yahoo"
},
{
"code": null,
"e": 18856,
"s": 18847,
"text": "Belzabar"
},
{
"code": null,
"e": 18862,
"s": 18856,
"text": "Apple"
},
{
"code": null,
"e": 18867,
"s": 18862,
"text": "Heap"
},
{
"code": null,
"e": 18871,
"s": 18867,
"text": "STL"
}
] |
Python | Sum list of dictionaries with same key
|
03 Mar, 2019
You have given a list of dictionaries, the task is to return a single dictionary with sum values with the same key.
Let’s discuss different methods to do the task.
Method #1: Using reduce() + operator
# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary import collections, functools, operator # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90}, {'a':45, 'b':78}, {'a':90, 'c':10}] # printing initial dictionaryprint ("initial dictionary", str(ini_dict)) # sum the values with same keysresult = dict(functools.reduce(operator.add, map(collections.Counter, ini_dict))) print("resultant dictionary : ", str(result))
initial dictionary [{‘b’: 10, ‘a’: 5, ‘c’: 90}, {‘b’: 78, ‘a’: 45}, {‘a’: 90, ‘c’: 10}]resultant dictionary : {‘b’: 88, ‘a’: 140, ‘c’: 100}
Method #2: Using counter
# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary import collections # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90}, {'a':45, 'b':78}, {'a':90, 'c':10}] # printing initial dictionaryprint ("initial dictionary", str(ini_dict)) # sum the values with same keyscounter = collections.Counter()for d in ini_dict: counter.update(d) result = dict(counter) print("resultant dictionary : ", str(counter))
initial dictionary [{‘c’: 90, ‘a’: 5, ‘b’: 10}, {‘a’: 45, ‘b’: 78}, {‘a’: 90, ‘c’: 10}]resultant dictionary : Counter({‘a’: 140, ‘c’: 100, ‘b’: 88})
Method #3: Naive Method
# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary from operator import itemgetter # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90}, {'a':45, 'b':78}, {'a':90, 'c':10}] # printing initial dictionaryprint ("initial dictionary", str(ini_dict)) # sum the values with same keysresult = {}for d in ini_dict: for k in d.keys(): result[k] = result.get(k, 0) + d[k] print("resultant dictionary : ", str(result))
initial dictionary [{‘b’: 10, ‘c’: 90, ‘a’: 5}, {‘b’: 78, ‘a’: 45}, {‘c’: 10, ‘a’: 90}]resultant dictionary : {‘b’: 88, ‘c’: 100, ‘a’: 140}
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Mar, 2019"
},
{
"code": null,
"e": 168,
"s": 52,
"text": "You have given a list of dictionaries, the task is to return a single dictionary with sum values with the same key."
},
{
"code": null,
"e": 216,
"s": 168,
"text": "Let’s discuss different methods to do the task."
},
{
"code": null,
"e": 253,
"s": 216,
"text": "Method #1: Using reduce() + operator"
},
{
"code": "# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary import collections, functools, operator # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90}, {'a':45, 'b':78}, {'a':90, 'c':10}] # printing initial dictionaryprint (\"initial dictionary\", str(ini_dict)) # sum the values with same keysresult = dict(functools.reduce(operator.add, map(collections.Counter, ini_dict))) print(\"resultant dictionary : \", str(result))",
"e": 776,
"s": 253,
"text": null
},
{
"code": null,
"e": 916,
"s": 776,
"text": "initial dictionary [{‘b’: 10, ‘a’: 5, ‘c’: 90}, {‘b’: 78, ‘a’: 45}, {‘a’: 90, ‘c’: 10}]resultant dictionary : {‘b’: 88, ‘a’: 140, ‘c’: 100}"
},
{
"code": null,
"e": 942,
"s": 916,
"text": " Method #2: Using counter"
},
{
"code": "# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary import collections # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90}, {'a':45, 'b':78}, {'a':90, 'c':10}] # printing initial dictionaryprint (\"initial dictionary\", str(ini_dict)) # sum the values with same keyscounter = collections.Counter()for d in ini_dict: counter.update(d) result = dict(counter) print(\"resultant dictionary : \", str(counter))",
"e": 1455,
"s": 942,
"text": null
},
{
"code": null,
"e": 1604,
"s": 1455,
"text": "initial dictionary [{‘c’: 90, ‘a’: 5, ‘b’: 10}, {‘a’: 45, ‘b’: 78}, {‘a’: 90, ‘c’: 10}]resultant dictionary : Counter({‘a’: 140, ‘c’: 100, ‘b’: 88})"
},
{
"code": null,
"e": 1629,
"s": 1604,
"text": " Method #3: Naive Method"
},
{
"code": "# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary from operator import itemgetter # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90}, {'a':45, 'b':78}, {'a':90, 'c':10}] # printing initial dictionaryprint (\"initial dictionary\", str(ini_dict)) # sum the values with same keysresult = {}for d in ini_dict: for k in d.keys(): result[k] = result.get(k, 0) + d[k] print(\"resultant dictionary : \", str(result))",
"e": 2149,
"s": 1629,
"text": null
},
{
"code": null,
"e": 2289,
"s": 2149,
"text": "initial dictionary [{‘b’: 10, ‘c’: 90, ‘a’: 5}, {‘b’: 78, ‘a’: 45}, {‘c’: 10, ‘a’: 90}]resultant dictionary : {‘b’: 88, ‘c’: 100, ‘a’: 140}"
},
{
"code": null,
"e": 2316,
"s": 2289,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2328,
"s": 2316,
"text": "python-dict"
},
{
"code": null,
"e": 2335,
"s": 2328,
"text": "Python"
},
{
"code": null,
"e": 2351,
"s": 2335,
"text": "Python Programs"
},
{
"code": null,
"e": 2363,
"s": 2351,
"text": "python-dict"
}
] |
Python | Pandas Series.str.get_dummies()
|
25 Oct, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.get_dummies() is used to separate each string in the caller series at the passed separator. A data frame is returned with all the possible values after splitting every string. If the text value in original data frame at same index contains the string (Column name/ Splitted values) then the value at that position is 1 otherwise, 0.
Since this is a string operation, .str has to be prefixed every time before calling this function. Otherwise, it will throw an error.
Syntax: Series.str.get_dummies(sep=’|’)
Parameters:sep: String value, separator to split strings at
Return type: Data frame with binary values only
To download the data set used in following examples, click here.
In the following examples, the data frame used contains data of some employees. The image of data frame before any operations is attached below. Example #1: Separating different strings on whitespace.
In this example, string in the Team column have been split at ” ” (White-space) and the data frame is returned with all possible values after splitting. The value in returned data frame is 1 if the string(Column name) exists in the text value at same index in old data frame.
Python3
# importing pandasimport pandas as pd # making data frame from csv at urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/employees.csv") # making dataframe using get_dummies()dummies = data["Team"].str.get_dummies(" ") # displaydummies.head(10)
Output:As shown in the output image, it can be compared with the original image of data frame. If the string exists at that same index, then value is 1 otherwise 0. Important points:
If string is not null, then at least one column will have value 1 at the same index.
If the value is null, then all columns will have 0 value at that index (Can be seen at 2nd element in above example)
Example #2: Splitting at multiple points/Static value column
In this example, a static value is taken for the new column (“Hello gfg family”). Then the get_dummies() method is applied and the string is separated at “g”. Since “g” is occurring more than once, there will be more than one column and also the values in all column must be same as the string is also same for all rows.
Python3
# importing pandasimport pandas as pd # making data frame from csv at urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/employees.csv") # string for new columnstring ="Hello gfg family" # creating new columndata["New_column"]= string # creating dummiesdf = data["New_column"].str.get_dummies("g") # displaydf.head(10)
Output:As shown in output image, the new data frame has 3 columns and every row has same values.
Akanksha_Rai
gabaa406
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 586,
"s": 242,
"text": "Pandas str.get_dummies() is used to separate each string in the caller series at the passed separator. A data frame is returned with all the possible values after splitting every string. If the text value in original data frame at same index contains the string (Column name/ Splitted values) then the value at that position is 1 otherwise, 0."
},
{
"code": null,
"e": 720,
"s": 586,
"text": "Since this is a string operation, .str has to be prefixed every time before calling this function. Otherwise, it will throw an error."
},
{
"code": null,
"e": 760,
"s": 720,
"text": "Syntax: Series.str.get_dummies(sep=’|’)"
},
{
"code": null,
"e": 820,
"s": 760,
"text": "Parameters:sep: String value, separator to split strings at"
},
{
"code": null,
"e": 868,
"s": 820,
"text": "Return type: Data frame with binary values only"
},
{
"code": null,
"e": 933,
"s": 868,
"text": "To download the data set used in following examples, click here."
},
{
"code": null,
"e": 1134,
"s": 933,
"text": "In the following examples, the data frame used contains data of some employees. The image of data frame before any operations is attached below. Example #1: Separating different strings on whitespace."
},
{
"code": null,
"e": 1410,
"s": 1134,
"text": "In this example, string in the Team column have been split at ” ” (White-space) and the data frame is returned with all possible values after splitting. The value in returned data frame is 1 if the string(Column name) exists in the text value at same index in old data frame."
},
{
"code": null,
"e": 1418,
"s": 1410,
"text": "Python3"
},
{
"code": "# importing pandasimport pandas as pd # making data frame from csv at urldata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/employees.csv\") # making dataframe using get_dummies()dummies = data[\"Team\"].str.get_dummies(\" \") # displaydummies.head(10)",
"e": 1689,
"s": 1418,
"text": null
},
{
"code": null,
"e": 1872,
"s": 1689,
"text": "Output:As shown in the output image, it can be compared with the original image of data frame. If the string exists at that same index, then value is 1 otherwise 0. Important points:"
},
{
"code": null,
"e": 1957,
"s": 1872,
"text": "If string is not null, then at least one column will have value 1 at the same index."
},
{
"code": null,
"e": 2074,
"s": 1957,
"text": "If the value is null, then all columns will have 0 value at that index (Can be seen at 2nd element in above example)"
},
{
"code": null,
"e": 2136,
"s": 2074,
"text": " Example #2: Splitting at multiple points/Static value column"
},
{
"code": null,
"e": 2457,
"s": 2136,
"text": "In this example, a static value is taken for the new column (“Hello gfg family”). Then the get_dummies() method is applied and the string is separated at “g”. Since “g” is occurring more than once, there will be more than one column and also the values in all column must be same as the string is also same for all rows."
},
{
"code": null,
"e": 2465,
"s": 2457,
"text": "Python3"
},
{
"code": "# importing pandasimport pandas as pd # making data frame from csv at urldata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/employees.csv\") # string for new columnstring =\"Hello gfg family\" # creating new columndata[\"New_column\"]= string # creating dummiesdf = data[\"New_column\"].str.get_dummies(\"g\") # displaydf.head(10)",
"e": 2812,
"s": 2465,
"text": null
},
{
"code": null,
"e": 2909,
"s": 2812,
"text": "Output:As shown in output image, the new data frame has 3 columns and every row has same values."
},
{
"code": null,
"e": 2922,
"s": 2909,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2931,
"s": 2922,
"text": "gabaa406"
},
{
"code": null,
"e": 2952,
"s": 2931,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2981,
"s": 2952,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2995,
"s": 2981,
"text": "Python-pandas"
},
{
"code": null,
"e": 3002,
"s": 2995,
"text": "Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.