title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Python String maketrans() Method | Python string method maketrans() returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. Then this table is passed to the translate() function.
Note β Both intab and outtab must have the same length.
Following is the syntax for maketrans() method β
str.maketrans(intab, outtab)
intab β This is the string having actual characters.
intab β This is the string having actual characters.
outtab β This is the string having corresponding mapping character.
outtab β This is the string having corresponding mapping character.
This method returns a translate table to be used translate() function.
The following example shows the usage of maketrans() method. Under this, every vowel in a string is replaced by its vowel position β
#!/usr/bin/python
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"
print str.translate(trantab)
When we run above program, it produces following result β
th3s 3s str3ng 2x1mpl2....w4w!!!
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": 2467,
"s": 2244,
"text": "Python string method maketrans() returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. Then this table is passed to the translate() function."
},
{
"code": null,
"e": 2523,
"s": 2467,
"text": "Note β Both intab and outtab must have the same length."
},
{
"code": null,
"e": 2572,
"s": 2523,
"text": "Following is the syntax for maketrans() method β"
},
{
"code": null,
"e": 2602,
"s": 2572,
"text": "str.maketrans(intab, outtab)\n"
},
{
"code": null,
"e": 2655,
"s": 2602,
"text": "intab β This is the string having actual characters."
},
{
"code": null,
"e": 2708,
"s": 2655,
"text": "intab β This is the string having actual characters."
},
{
"code": null,
"e": 2776,
"s": 2708,
"text": "outtab β This is the string having corresponding mapping character."
},
{
"code": null,
"e": 2844,
"s": 2776,
"text": "outtab β This is the string having corresponding mapping character."
},
{
"code": null,
"e": 2915,
"s": 2844,
"text": "This method returns a translate table to be used translate() function."
},
{
"code": null,
"e": 3048,
"s": 2915,
"text": "The following example shows the usage of maketrans() method. Under this, every vowel in a string is replaced by its vowel position β"
},
{
"code": null,
"e": 3277,
"s": 3048,
"text": "#!/usr/bin/python\n\nfrom string import maketrans # Required to call maketrans function.\n\nintab = \"aeiou\"\nouttab = \"12345\"\ntrantab = maketrans(intab, outtab)\n\nstr = \"this is string example....wow!!!\"\nprint str.translate(trantab)"
},
{
"code": null,
"e": 3335,
"s": 3277,
"text": "When we run above program, it produces following result β"
},
{
"code": null,
"e": 3369,
"s": 3335,
"text": "th3s 3s str3ng 2x1mpl2....w4w!!!\n"
},
{
"code": null,
"e": 3406,
"s": 3369,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3422,
"s": 3406,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3455,
"s": 3422,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3474,
"s": 3455,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3509,
"s": 3474,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3531,
"s": 3509,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3565,
"s": 3531,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3593,
"s": 3565,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3628,
"s": 3593,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3642,
"s": 3628,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3675,
"s": 3642,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3692,
"s": 3675,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3699,
"s": 3692,
"text": " Print"
},
{
"code": null,
"e": 3710,
"s": 3699,
"text": " Add Notes"
}
]
|
Find a specific element in a C# List | Set a list β
List<int> myList = new List<int>() {
5,
10,
17,
19,
23,
33
};
Let us say you need to find an element that is divisible by 2. For that, use the Find() method β
int val = myList.Find(item => item % 2 == 0);
Here is the complete code β
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<int> myList = new List<int>() {
5,
10,
17,
19,
23,
33
};
Console.WriteLine("List: ");
foreach(int i in myList) {
Console.WriteLine(i);
}
int val = myList.Find(item => item % 2 == 0);
Console.WriteLine("Element that divides by zero: "+val);
}
}
List:
5
10
17
19
23
33
Element that divides by zero: 10 | [
{
"code": null,
"e": 1075,
"s": 1062,
"text": "Set a list β"
},
{
"code": null,
"e": 1155,
"s": 1075,
"text": "List<int> myList = new List<int>() {\n 5,\n 10,\n 17,\n 19,\n 23,\n 33\n};"
},
{
"code": null,
"e": 1252,
"s": 1155,
"text": "Let us say you need to find an element that is divisible by 2. For that, use the Find() method β"
},
{
"code": null,
"e": 1298,
"s": 1252,
"text": "int val = myList.Find(item => item % 2 == 0);"
},
{
"code": null,
"e": 1326,
"s": 1298,
"text": "Here is the complete code β"
},
{
"code": null,
"e": 1337,
"s": 1326,
"text": " Live Demo"
},
{
"code": null,
"e": 1798,
"s": 1337,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nclass Demo {\n static void Main() {\n List<int> myList = new List<int>() {\n 5,\n 10,\n 17,\n 19,\n 23,\n 33\n };\n Console.WriteLine(\"List: \");\n foreach(int i in myList) {\n Console.WriteLine(i);\n }\n int val = myList.Find(item => item % 2 == 0);\n Console.WriteLine(\"Element that divides by zero: \"+val);\n }\n}"
},
{
"code": null,
"e": 1854,
"s": 1798,
"text": "List:\n5\n10\n17\n19\n23\n33\nElement that divides by zero: 10"
}
]
|
CSS - Pulse Effect | It Provides a single vibration or short burs to an element.
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
Transform β Transform applies to 2d and 3d transformation to an element.
Transform β Transform applies to 2d and 3d transformation to an element.
Opacity β Opacity applies to an element to make translucence.
Opacity β Opacity applies to an element to make translucence.
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes pulse {
0% { -webkit-transform: scale(1); }
50% { -webkit-transform: scale(1.1); }
100% { -webkit-transform: scale(1); }
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
.pulse {
-webkit-animation-name: pulse;
animation-name: pulse;
}
</style>
</head>
<body>
<div id = "animated-example" class = "animated pulse"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
It will produce the following result β
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2686,
"s": 2626,
"text": "It Provides a single vibration or short burs to an element."
},
{
"code": null,
"e": 2807,
"s": 2686,
"text": "@keyframes pulse {\n 0% { transform: scale(1); }\n 50% { transform: scale(1.1); }\n 100% { transform: scale(1); } \n} "
},
{
"code": null,
"e": 2880,
"s": 2807,
"text": "Transform β Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 2953,
"s": 2880,
"text": "Transform β Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 3015,
"s": 2953,
"text": "Opacity β Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 3077,
"s": 3015,
"text": "Opacity β Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 4316,
"s": 3077,
"text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes pulse {\n 0% { -webkit-transform: scale(1); }\n 50% { -webkit-transform: scale(1.1); }\n 100% { -webkit-transform: scale(1); }\n }\n \n @keyframes pulse {\n 0% { transform: scale(1); }\n 50% { transform: scale(1.1); }\n 100% { transform: scale(1); }\n }\n \n .pulse {\n -webkit-animation-name: pulse;\n animation-name: pulse;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated pulse\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4355,
"s": 4316,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 5002,
"s": 4355,
"text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n"
},
{
"code": null,
"e": 5022,
"s": 5002,
"text": " Academic Tutorials"
},
{
"code": null,
"e": 5045,
"s": 5022,
"text": " Big Data & Analytics "
},
{
"code": null,
"e": 5068,
"s": 5045,
"text": " Computer Programming "
},
{
"code": null,
"e": 5087,
"s": 5068,
"text": " Computer Science "
},
{
"code": null,
"e": 5099,
"s": 5087,
"text": " Databases "
},
{
"code": null,
"e": 5108,
"s": 5099,
"text": " DevOps "
},
{
"code": null,
"e": 5128,
"s": 5108,
"text": " Digital Marketing "
},
{
"code": null,
"e": 5152,
"s": 5128,
"text": " Engineering Tutorials "
},
{
"code": null,
"e": 5169,
"s": 5152,
"text": " Exams Syllabus "
},
{
"code": null,
"e": 5188,
"s": 5169,
"text": " Famous Monuments "
},
{
"code": null,
"e": 5210,
"s": 5188,
"text": " GATE Exams Tutorials"
},
{
"code": null,
"e": 5232,
"s": 5210,
"text": " Latest Technologies "
},
{
"code": null,
"e": 5251,
"s": 5232,
"text": " Machine Learning "
},
{
"code": null,
"e": 5275,
"s": 5251,
"text": " Mainframe Development "
},
{
"code": null,
"e": 5298,
"s": 5275,
"text": " Management Tutorials "
},
{
"code": null,
"e": 5321,
"s": 5298,
"text": " Mathematics Tutorials"
},
{
"code": null,
"e": 5346,
"s": 5321,
"text": " Microsoft Technologies "
},
{
"code": null,
"e": 5363,
"s": 5346,
"text": " Misc tutorials "
},
{
"code": null,
"e": 5384,
"s": 5363,
"text": " Mobile Development "
},
{
"code": null,
"e": 5404,
"s": 5384,
"text": " Java Technologies "
},
{
"code": null,
"e": 5426,
"s": 5404,
"text": " Python Technologies "
},
{
"code": null,
"e": 5442,
"s": 5426,
"text": " SAP Tutorials "
},
{
"code": null,
"e": 5463,
"s": 5442,
"text": "Programming Scripts "
},
{
"code": null,
"e": 5482,
"s": 5463,
"text": " Selected Reading "
},
{
"code": null,
"e": 5501,
"s": 5482,
"text": " Software Quality "
},
{
"code": null,
"e": 5515,
"s": 5501,
"text": " Soft Skills "
},
{
"code": null,
"e": 5535,
"s": 5515,
"text": " Telecom Tutorials "
},
{
"code": null,
"e": 5552,
"s": 5535,
"text": " UPSC IAS Exams "
},
{
"code": null,
"e": 5570,
"s": 5552,
"text": " Web Development "
},
{
"code": null,
"e": 5589,
"s": 5570,
"text": " Sports Tutorials "
},
{
"code": null,
"e": 5608,
"s": 5589,
"text": " XML Technologies "
},
{
"code": null,
"e": 5624,
"s": 5608,
"text": " Multi-Language"
},
{
"code": null,
"e": 5645,
"s": 5624,
"text": " Interview Questions"
},
{
"code": null,
"e": 5662,
"s": 5645,
"text": "Selected Reading"
},
{
"code": null,
"e": 5683,
"s": 5662,
"text": "UPSC IAS Exams Notes"
},
{
"code": null,
"e": 5710,
"s": 5683,
"text": "Developer's Best Practices"
},
{
"code": null,
"e": 5732,
"s": 5710,
"text": "Questions and Answers"
},
{
"code": null,
"e": 5757,
"s": 5732,
"text": "Effective Resume Writing"
},
{
"code": null,
"e": 5780,
"s": 5757,
"text": "HR Interview Questions"
},
{
"code": null,
"e": 5798,
"s": 5780,
"text": "Computer Glossary"
},
{
"code": null,
"e": 5809,
"s": 5798,
"text": "Who is Who"
},
{
"code": null,
"e": 5816,
"s": 5809,
"text": " Print"
},
{
"code": null,
"e": 5827,
"s": 5816,
"text": " Add Notes"
}
]
|
Stream toArray() in Java with Examples | 06 Dec, 2018
Stream toArray() returns an array containing the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
Syntax :
Object[] toArray()
Return Value : The function returns an array containing the elements of this stream.
Example 1 :
// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Integers Stream<Integer> stream = Stream.of(5, 6, 7, 8, 9, 10); // Using Stream toArray() Object[] arr = stream.toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}
Output :
[5, 6, 7, 8, 9, 10]
Example 2 :
// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of("Geeks", "for", "Geeks", "GeeksQuiz"); // Using Stream toArray() Object[] arr = stream.toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}
Output :
[Geeks, for, Geeks, GeeksQuiz]
Example 3 :
// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of("Geeks", "for", "gfg", "GeeksQuiz"); // Using Stream toArray() and filtering // the elements that starts with 'G' Object[] arr = stream.filter(str -> str.startsWith("G")) .toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}
Output :
[Geeks, GeeksQuiz]
array-stream
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 313,
"s": 28,
"text": "Stream toArray() returns an array containing the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used."
},
{
"code": null,
"e": 322,
"s": 313,
"text": "Syntax :"
},
{
"code": null,
"e": 342,
"s": 322,
"text": "Object[] toArray()\n"
},
{
"code": null,
"e": 427,
"s": 342,
"text": "Return Value : The function returns an array containing the elements of this stream."
},
{
"code": null,
"e": 439,
"s": 427,
"text": "Example 1 :"
},
{
"code": "// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Integers Stream<Integer> stream = Stream.of(5, 6, 7, 8, 9, 10); // Using Stream toArray() Object[] arr = stream.toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}",
"e": 884,
"s": 439,
"text": null
},
{
"code": null,
"e": 893,
"s": 884,
"text": "Output :"
},
{
"code": null,
"e": 914,
"s": 893,
"text": "[5, 6, 7, 8, 9, 10]\n"
},
{
"code": null,
"e": 926,
"s": 914,
"text": "Example 2 :"
},
{
"code": "// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of(\"Geeks\", \"for\", \"Geeks\", \"GeeksQuiz\"); // Using Stream toArray() Object[] arr = stream.toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}",
"e": 1429,
"s": 926,
"text": null
},
{
"code": null,
"e": 1438,
"s": 1429,
"text": "Output :"
},
{
"code": null,
"e": 1470,
"s": 1438,
"text": "[Geeks, for, Geeks, GeeksQuiz]\n"
},
{
"code": null,
"e": 1482,
"s": 1470,
"text": "Example 3 :"
},
{
"code": "// Java code for Stream toArray()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of(\"Geeks\", \"for\", \"gfg\", \"GeeksQuiz\"); // Using Stream toArray() and filtering // the elements that starts with 'G' Object[] arr = stream.filter(str -> str.startsWith(\"G\")) .toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}",
"e": 2139,
"s": 1482,
"text": null
},
{
"code": null,
"e": 2148,
"s": 2139,
"text": "Output :"
},
{
"code": null,
"e": 2168,
"s": 2148,
"text": "[Geeks, GeeksQuiz]\n"
},
{
"code": null,
"e": 2181,
"s": 2168,
"text": "array-stream"
},
{
"code": null,
"e": 2201,
"s": 2181,
"text": "Java - util package"
},
{
"code": null,
"e": 2216,
"s": 2201,
"text": "Java-Functions"
},
{
"code": null,
"e": 2228,
"s": 2216,
"text": "java-stream"
},
{
"code": null,
"e": 2250,
"s": 2228,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 2255,
"s": 2250,
"text": "Java"
},
{
"code": null,
"e": 2260,
"s": 2255,
"text": "Java"
}
]
|
TimeUnit sleep() method in Java with Examples | 15 Oct, 2018
The sleep() method of TimeUnit Class is used to performs a Thread.sleep using this time unit. This is a convenience method that sleeps time arguments into the form required by the Thread.sleep method.
Syntax:
public void sleep(long timeout)
throws InterruptedException
Parameters: This method accepts a mandatory parameters timeout which is the minimum time to sleep. If this is less than or equal to zero, then do not sleep at all.
Return Value: This method does not return anything.
Exception: This method throws InterruptedException if interrupted while sleeping.
Below program illustrate the implementation of TimeUnit sleep() method:
Program 1:
// Java program to demonstrate// sleep() method of TimeUnit Class import java.util.concurrent.*; class GFG { public static void main(String args[]) { // Get time to sleep long timeToSleep = 0L; // Create a TimeUnit object TimeUnit time = TimeUnit.SECONDS; try { System.out.println("Going to sleep for " + timeToSleep + " seconds"); // using sleep() method time.sleep(timeToSleep); System.out.println("Slept for " + timeToSleep + " seconds"); } catch (InterruptedException e) { System.out.println("Interrupted " + "while Sleeping"); } }}
Going to sleep for 0 seconds
Slept for 0 seconds
Program 2:
// Java program to demonstrate// sleep() method of TimeUnit Class import java.util.concurrent.*; class GFG { public static void main(String args[]) { // Get time to sleep long timeToSleep = 10L; // Create a TimeUnit object TimeUnit time = TimeUnit.SECONDS; try { System.out.println("Going to sleep for " + timeToSleep + " seconds"); // using sleep() method time.sleep(timeToSleep); System.out.println("Slept for " + timeToSleep + " seconds"); } catch (InterruptedException e) { System.out.println("Interrupted " + "while Sleeping"); } }}
Going to sleep for 10 seconds
Slept for 10 seconds
Java - util package
Java-Functions
Java-TimeUnit
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Stream In Java
Set in Java
Singleton Class in Java
Initializing a List in Java
Introduction to Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2018"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "The sleep() method of TimeUnit Class is used to performs a Thread.sleep using this time unit. This is a convenience method that sleeps time arguments into the form required by the Thread.sleep method."
},
{
"code": null,
"e": 237,
"s": 229,
"text": "Syntax:"
},
{
"code": null,
"e": 308,
"s": 237,
"text": "public void sleep(long timeout)\n throws InterruptedException"
},
{
"code": null,
"e": 472,
"s": 308,
"text": "Parameters: This method accepts a mandatory parameters timeout which is the minimum time to sleep. If this is less than or equal to zero, then do not sleep at all."
},
{
"code": null,
"e": 524,
"s": 472,
"text": "Return Value: This method does not return anything."
},
{
"code": null,
"e": 606,
"s": 524,
"text": "Exception: This method throws InterruptedException if interrupted while sleeping."
},
{
"code": null,
"e": 678,
"s": 606,
"text": "Below program illustrate the implementation of TimeUnit sleep() method:"
},
{
"code": null,
"e": 689,
"s": 678,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// sleep() method of TimeUnit Class import java.util.concurrent.*; class GFG { public static void main(String args[]) { // Get time to sleep long timeToSleep = 0L; // Create a TimeUnit object TimeUnit time = TimeUnit.SECONDS; try { System.out.println(\"Going to sleep for \" + timeToSleep + \" seconds\"); // using sleep() method time.sleep(timeToSleep); System.out.println(\"Slept for \" + timeToSleep + \" seconds\"); } catch (InterruptedException e) { System.out.println(\"Interrupted \" + \"while Sleeping\"); } }}",
"e": 1510,
"s": 689,
"text": null
},
{
"code": null,
"e": 1560,
"s": 1510,
"text": "Going to sleep for 0 seconds\nSlept for 0 seconds\n"
},
{
"code": null,
"e": 1571,
"s": 1560,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// sleep() method of TimeUnit Class import java.util.concurrent.*; class GFG { public static void main(String args[]) { // Get time to sleep long timeToSleep = 10L; // Create a TimeUnit object TimeUnit time = TimeUnit.SECONDS; try { System.out.println(\"Going to sleep for \" + timeToSleep + \" seconds\"); // using sleep() method time.sleep(timeToSleep); System.out.println(\"Slept for \" + timeToSleep + \" seconds\"); } catch (InterruptedException e) { System.out.println(\"Interrupted \" + \"while Sleeping\"); } }}",
"e": 2393,
"s": 1571,
"text": null
},
{
"code": null,
"e": 2445,
"s": 2393,
"text": "Going to sleep for 10 seconds\nSlept for 10 seconds\n"
},
{
"code": null,
"e": 2465,
"s": 2445,
"text": "Java - util package"
},
{
"code": null,
"e": 2480,
"s": 2465,
"text": "Java-Functions"
},
{
"code": null,
"e": 2494,
"s": 2480,
"text": "Java-TimeUnit"
},
{
"code": null,
"e": 2499,
"s": 2494,
"text": "Java"
},
{
"code": null,
"e": 2504,
"s": 2499,
"text": "Java"
},
{
"code": null,
"e": 2602,
"s": 2504,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2621,
"s": 2602,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2651,
"s": 2621,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2669,
"s": 2651,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2701,
"s": 2669,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2721,
"s": 2701,
"text": "Collections in Java"
},
{
"code": null,
"e": 2736,
"s": 2721,
"text": "Stream In Java"
},
{
"code": null,
"e": 2748,
"s": 2736,
"text": "Set in Java"
},
{
"code": null,
"e": 2772,
"s": 2748,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2800,
"s": 2772,
"text": "Initializing a List in Java"
}
]
|
Writer write(String) method in Java with Examples | 29 Jan, 2019
The write(String) method of Writer Class in Java is used to write the specified String on the stream. This String value is taken as a parameter.
Syntax:
public void write(String string)
Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream.
Return Value: This method do not returns any value.
Below methods illustrates the working of write(String) method:
Program 1:
// Java program to demonstrate// Writer write(String) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Write the String 'GeeksForGeeks' // to this writer using write() method // This will put the string in the stream // till it is printed on the console writer.write("GeeksForGeeks"); writer.flush(); } catch (Exception e) { System.out.println(e); } }}
GeeksForGeeks
Program 2:
// Java program to demonstrate// Writer write(String) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Write the String 'GFG' // to this writer using write() method // This will put the string in the stream // till it is printed on the console writer.write("GFG"); writer.flush(); } catch (Exception e) { System.out.println(e); } }}
GFG
Java-Functions
Java-IO package
Java-Writer
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": "\n29 Jan, 2019"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "The write(String) method of Writer Class in Java is used to write the specified String on the stream. This String value is taken as a parameter."
},
{
"code": null,
"e": 181,
"s": 173,
"text": "Syntax:"
},
{
"code": null,
"e": 214,
"s": 181,
"text": "public void write(String string)"
},
{
"code": null,
"e": 324,
"s": 214,
"text": "Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream."
},
{
"code": null,
"e": 376,
"s": 324,
"text": "Return Value: This method do not returns any value."
},
{
"code": null,
"e": 439,
"s": 376,
"text": "Below methods illustrates the working of write(String) method:"
},
{
"code": null,
"e": 450,
"s": 439,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Writer write(String) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Write the String 'GeeksForGeeks' // to this writer using write() method // This will put the string in the stream // till it is printed on the console writer.write(\"GeeksForGeeks\"); writer.flush(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1075,
"s": 450,
"text": null
},
{
"code": null,
"e": 1090,
"s": 1075,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 1101,
"s": 1090,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Writer write(String) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Write the String 'GFG' // to this writer using write() method // This will put the string in the stream // till it is printed on the console writer.write(\"GFG\"); writer.flush(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1706,
"s": 1101,
"text": null
},
{
"code": null,
"e": 1711,
"s": 1706,
"text": "GFG\n"
},
{
"code": null,
"e": 1726,
"s": 1711,
"text": "Java-Functions"
},
{
"code": null,
"e": 1742,
"s": 1726,
"text": "Java-IO package"
},
{
"code": null,
"e": 1754,
"s": 1742,
"text": "Java-Writer"
},
{
"code": null,
"e": 1759,
"s": 1754,
"text": "Java"
},
{
"code": null,
"e": 1764,
"s": 1759,
"text": "Java"
}
]
|
Node.js fs.rmdir() Method | 12 Oct, 2021
The fs.rmdir() method is used to delete a directory at the given path. It can also be used recursively to remove nested directories.
Syntax:
fs.rmdir( path, options, callback )
Parameters: This method accept three parameters as mentioned above and described below:
path: It holds the path of the directory that has to be removed. It can be a String, Buffer or URL.
options: It is an object that can be used to specify optional parameters that will affect the operation. It has three optional parameters:recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.maxRetries: It is an integer value which specifies the number of times Node.js will try to perform the operation when it fails due to any error. The operations are performed after the given retry delay. This option is ignored if the recursive option is not set to true. The default value is 0.retryDelay: It is an integer value which specifies the time to wait in milliseconds before the operation is retried. This option is ignored if the recursive option is not set to true. The default value is 100 milliseconds.
recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.
maxRetries: It is an integer value which specifies the number of times Node.js will try to perform the operation when it fails due to any error. The operations are performed after the given retry delay. This option is ignored if the recursive option is not set to true. The default value is 0.
retryDelay: It is an integer value which specifies the time to wait in milliseconds before the operation is retried. This option is ignored if the recursive option is not set to true. The default value is 100 milliseconds.
callback: It is the function that would be called when the method is executed. err: It is an error that would be thrown if the operation fails.
err: It is an error that would be thrown if the operation fails.
Below examples illustrate the fs.rmdir() method in Node.js:
Example 1: This example uses fs.rmdir() method to delete a directory.
Javascript
// Node.js program to demonstrate the// fs.rmdir() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// in the directorygetCurrentFilenames(); fs.rmdir("directory_one", () => { console.log("Folder Deleted!"); // Get the current filenames // in the directory to verify getCurrentFilenames();}); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log("\n");}
Output:
Current filenames:
directory_one
index.js
package.json
Folder Deleted!
Current filenames:
index.js
package.json
Example 2: This example uses fs.rmdir() method with the recursive parameter to delete nested directories.
Javascript
// Node.js program to demonstrate the// fs.rmdir() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// in the directorygetCurrentFilenames(); // Trying to delete nested directories// without the recursive parameterfs.rmdir("directory_one", { recursive: false,}, (error) => { if (error) { console.log(error); } else { console.log("Non Recursive: Directories Deleted!"); }}); // Using the recursive option to delete// multiple directories that are nestedfs.rmdir("directory_one", { recursive: true,}, (error) => { if (error) { console.log(error); } else { console.log("Recursive: Directories Deleted!"); // Get the current filenames // in the directory to verify getCurrentFilenames(); }}); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log("\n");}
Output:
Current filenames:
directory_one
index.js
package.json
[Error: ENOTEMPTY: directory not empty,
rmdir 'G:\tutorials\nodejs-fs-rmdir\directory_one'] {
errno: -4051,
code: 'ENOTEMPTY',
syscall: 'rmdir',
path: 'G:\\tutorials\\nodejs-fs-rmdir\\directory_one'
}
Recursive: Directories Deleted!
Current filenames:
index.js
package.json
Reference: https://nodejs.org/api/fs.html#fs_fs_rmdir_path_options_callback
arorakashish0911
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 161,
"s": 28,
"text": "The fs.rmdir() method is used to delete a directory at the given path. It can also be used recursively to remove nested directories."
},
{
"code": null,
"e": 170,
"s": 161,
"text": "Syntax: "
},
{
"code": null,
"e": 206,
"s": 170,
"text": "fs.rmdir( path, options, callback )"
},
{
"code": null,
"e": 296,
"s": 206,
"text": "Parameters: This method accept three parameters as mentioned above and described below: "
},
{
"code": null,
"e": 396,
"s": 296,
"text": "path: It holds the path of the directory that has to be removed. It can be a String, Buffer or URL."
},
{
"code": null,
"e": 1285,
"s": 396,
"text": "options: It is an object that can be used to specify optional parameters that will affect the operation. It has three optional parameters:recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.maxRetries: It is an integer value which specifies the number of times Node.js will try to perform the operation when it fails due to any error. The operations are performed after the given retry delay. This option is ignored if the recursive option is not set to true. The default value is 0.retryDelay: It is an integer value which specifies the time to wait in milliseconds before the operation is retried. This option is ignored if the recursive option is not set to true. The default value is 100 milliseconds."
},
{
"code": null,
"e": 1521,
"s": 1285,
"text": "recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false."
},
{
"code": null,
"e": 1815,
"s": 1521,
"text": "maxRetries: It is an integer value which specifies the number of times Node.js will try to perform the operation when it fails due to any error. The operations are performed after the given retry delay. This option is ignored if the recursive option is not set to true. The default value is 0."
},
{
"code": null,
"e": 2038,
"s": 1815,
"text": "retryDelay: It is an integer value which specifies the time to wait in milliseconds before the operation is retried. This option is ignored if the recursive option is not set to true. The default value is 100 milliseconds."
},
{
"code": null,
"e": 2182,
"s": 2038,
"text": "callback: It is the function that would be called when the method is executed. err: It is an error that would be thrown if the operation fails."
},
{
"code": null,
"e": 2247,
"s": 2182,
"text": "err: It is an error that would be thrown if the operation fails."
},
{
"code": null,
"e": 2307,
"s": 2247,
"text": "Below examples illustrate the fs.rmdir() method in Node.js:"
},
{
"code": null,
"e": 2378,
"s": 2307,
"text": "Example 1: This example uses fs.rmdir() method to delete a directory. "
},
{
"code": null,
"e": 2389,
"s": 2378,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.rmdir() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// in the directorygetCurrentFilenames(); fs.rmdir(\"directory_one\", () => { console.log(\"Folder Deleted!\"); // Get the current filenames // in the directory to verify getCurrentFilenames();}); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log(\"\\nCurrent filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log(\"\\n\");}",
"e": 2952,
"s": 2389,
"text": null
},
{
"code": null,
"e": 2960,
"s": 2952,
"text": "Output:"
},
{
"code": null,
"e": 3073,
"s": 2960,
"text": "Current filenames:\ndirectory_one\nindex.js\npackage.json\nFolder Deleted!\n\nCurrent filenames:\nindex.js\npackage.json"
},
{
"code": null,
"e": 3179,
"s": 3073,
"text": "Example 2: This example uses fs.rmdir() method with the recursive parameter to delete nested directories."
},
{
"code": null,
"e": 3190,
"s": 3179,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.rmdir() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// in the directorygetCurrentFilenames(); // Trying to delete nested directories// without the recursive parameterfs.rmdir(\"directory_one\", { recursive: false,}, (error) => { if (error) { console.log(error); } else { console.log(\"Non Recursive: Directories Deleted!\"); }}); // Using the recursive option to delete// multiple directories that are nestedfs.rmdir(\"directory_one\", { recursive: true,}, (error) => { if (error) { console.log(error); } else { console.log(\"Recursive: Directories Deleted!\"); // Get the current filenames // in the directory to verify getCurrentFilenames(); }}); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log(\"\\nCurrent filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log(\"\\n\");}",
"e": 4177,
"s": 3190,
"text": null
},
{
"code": null,
"e": 4185,
"s": 4177,
"text": "Output:"
},
{
"code": null,
"e": 4526,
"s": 4185,
"text": "Current filenames:\ndirectory_one\nindex.js\npackage.json\n\n\n[Error: ENOTEMPTY: directory not empty, \nrmdir 'G:\\tutorials\\nodejs-fs-rmdir\\directory_one'] {\n errno: -4051,\n code: 'ENOTEMPTY',\n syscall: 'rmdir',\n path: 'G:\\\\tutorials\\\\nodejs-fs-rmdir\\\\directory_one'\n}\nRecursive: Directories Deleted!\n\nCurrent filenames:\nindex.js\npackage.json"
},
{
"code": null,
"e": 4603,
"s": 4526,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_rmdir_path_options_callback "
},
{
"code": null,
"e": 4620,
"s": 4603,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4638,
"s": 4620,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 4645,
"s": 4638,
"text": "Picked"
},
{
"code": null,
"e": 4653,
"s": 4645,
"text": "Node.js"
},
{
"code": null,
"e": 4670,
"s": 4653,
"text": "Web Technologies"
}
]
|
Python MariaDB β Insert into Table using PyMySQL | 14 Oct, 2020
MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python.
In this article we will look into the process of inserting rows to a table of the database using pymysql. You can insert one row or multiple rows at once. The connector code is required to connect the commands to the particular database. To insert data use the following syntax:
Syntax: INSERT INTO table_name column1, column2 VALUES (value1, value2)
Note: The INSERT query is used to insert one or multiple rows in a table.
Example :
To insert one row in table PRODUCT.
Python3
# import the mysql client for python import pymysql # Create a connection object# IP address of the MySQL database serverHost = "localhost" # User name of the database serverUser = "user" # Password for the database userPassword = "" database = "database_name" conn = pymysql.connect(host=Host, user=User, password=Password, database) # Create a cursor objectcur = conn.cursor() PRODUCT_ID = '1201'price = 10000PRODUCT_TYPE = 'PRI' query = f"INSERT INTO PRODUCT (PRODUCT_ID, price,PRODUCT_TYPE) VALUES ('{PRODUCT_ID}', '{price}', '{PRODUCT_TYPE}')" cur.execute(query)print(f"{cur.rowcount} details inserted")conn.commit()conn.close()
Output :
To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method.
Example :
To insert multiple row in table PRODUCT.
Python3
query = "INSERT INTO PRODUCT (PRODUCT_ID, price,PRODUCT_TYPE) VALUES ('%s', %d, '%s')" values = [("1203",1000,"ILL"), ("1523",1500,"broadband"), ("154",14782,"Voice"), ]cur.execute(query,values)print(f"{cur.rowcount}, details inserted")conn.commit()conn.close()
Output :
Note :
The cursor() is used in order to iterate through the rows.
Without the command conn.commit() the changes will not be saved.
Python-MariaDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python."
},
{
"code": null,
"e": 485,
"s": 206,
"text": "In this article we will look into the process of inserting rows to a table of the database using pymysql. You can insert one row or multiple rows at once. The connector code is required to connect the commands to the particular database. To insert data use the following syntax:"
},
{
"code": null,
"e": 557,
"s": 485,
"text": "Syntax: INSERT INTO table_name column1, column2 VALUES (value1, value2)"
},
{
"code": null,
"e": 631,
"s": 557,
"text": "Note: The INSERT query is used to insert one or multiple rows in a table."
},
{
"code": null,
"e": 642,
"s": 631,
"text": "Example : "
},
{
"code": null,
"e": 678,
"s": 642,
"text": "To insert one row in table PRODUCT."
},
{
"code": null,
"e": 686,
"s": 678,
"text": "Python3"
},
{
"code": "# import the mysql client for python import pymysql # Create a connection object# IP address of the MySQL database serverHost = \"localhost\" # User name of the database serverUser = \"user\" # Password for the database userPassword = \"\" database = \"database_name\" conn = pymysql.connect(host=Host, user=User, password=Password, database) # Create a cursor objectcur = conn.cursor() PRODUCT_ID = '1201'price = 10000PRODUCT_TYPE = 'PRI' query = f\"INSERT INTO PRODUCT (PRODUCT_ID, price,PRODUCT_TYPE) VALUES ('{PRODUCT_ID}', '{price}', '{PRODUCT_TYPE}')\" cur.execute(query)print(f\"{cur.rowcount} details inserted\")conn.commit()conn.close()",
"e": 1350,
"s": 686,
"text": null
},
{
"code": null,
"e": 1359,
"s": 1350,
"text": "Output :"
},
{
"code": null,
"e": 1534,
"s": 1359,
"text": "To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method."
},
{
"code": null,
"e": 1545,
"s": 1534,
"text": "Example : "
},
{
"code": null,
"e": 1586,
"s": 1545,
"text": "To insert multiple row in table PRODUCT."
},
{
"code": null,
"e": 1594,
"s": 1586,
"text": "Python3"
},
{
"code": "query = \"INSERT INTO PRODUCT (PRODUCT_ID, price,PRODUCT_TYPE) VALUES ('%s', %d, '%s')\" values = [(\"1203\",1000,\"ILL\"), (\"1523\",1500,\"broadband\"), (\"154\",14782,\"Voice\"), ]cur.execute(query,values)print(f\"{cur.rowcount}, details inserted\")conn.commit()conn.close()",
"e": 1882,
"s": 1594,
"text": null
},
{
"code": null,
"e": 1891,
"s": 1882,
"text": "Output :"
},
{
"code": null,
"e": 1898,
"s": 1891,
"text": "Note :"
},
{
"code": null,
"e": 1957,
"s": 1898,
"text": "The cursor() is used in order to iterate through the rows."
},
{
"code": null,
"e": 2022,
"s": 1957,
"text": "Without the command conn.commit() the changes will not be saved."
},
{
"code": null,
"e": 2037,
"s": 2022,
"text": "Python-MariaDB"
},
{
"code": null,
"e": 2044,
"s": 2037,
"text": "Python"
}
]
|
How to Add SearchView in Google Maps in Android? | 04 Feb, 2021
We have seen the implementation of Google Maps in Android along with markers on it. But many apps provide features so that users can specify the location on which they have to place markers. So in this article, we will implement a SearchView in our Android app so that we can search a location name and add a marker to that location.
We will be building a simple application in which we will be displaying a simple Google map and a SearchView. Inside that search view when users enter any location name then we will add a marker to that location on Google Maps. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project.
Step 2: Generating an API key for using Google Maps
To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY.
Step 3: Working with the activity_maps.xml file
As we are adding SearchView to our Google Maps for searching a location and adding a marker on that location. So we have to add a search view to our activity_maps.xml file. For adding SearchView, navigate to the app > res > layout > activity_maps.xml and add the below code to it. Comments are added in the code to get to know in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <!--fragment to display our maps--> <fragment xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MapsActivity" /> <!--search view to search our location--> <androidx.appcompat.widget.SearchView android:id="@+id/idSearchView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:background="#BFBFBF" android:elevation="5dp" app:iconifiedByDefault="false" app:queryHint="Search Here" /> </RelativeLayout>
Step 4: Working with the MapsActivity.java file
Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.location.Address;import android.location.Geocoder;import android.os.Bundle; import androidx.appcompat.widget.SearchView;import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException;import java.util.List; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; // creating a variable // for search view. SearchView searchView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // initializing our search view. searchView = findViewById(R.id.idSearchView); // Obtain the SupportMapFragment and get notified // when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); // adding on query listener for our search view. searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // on below line we are getting the // location name from search view. String location = searchView.getQuery().toString(); // below line is to create a list of address // where we will store the list of all address. List<Address> addressList = null; // checking if the entered location is null or not. if (location != null || location.equals("")) { // on below line we are creating and initializing a geo coder. Geocoder geocoder = new Geocoder(MapsActivity.this); try { // on below line we are getting location from the // location name and adding that location to address list. addressList = geocoder.getFromLocationName(location, 1); } catch (IOException e) { e.printStackTrace(); } // on below line we are getting the location // from our list a first position. Address address = addressList.get(0); // on below line we are creating a variable for our location // where we will add our locations latitude and longitude. LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); // on below line we are adding marker to that position. mMap.addMarker(new MarkerOptions().position(latLng).title(location)); // below line is to animate camera to that position. mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10)); } return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); // at last we calling our map fragment to update. mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; }}
Now run your app and see the output of the app.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Feb, 2021"
},
{
"code": null,
"e": 363,
"s": 28,
"text": "We have seen the implementation of Google Maps in Android along with markers on it. But many apps provide features so that users can specify the location on which they have to place markers. So in this article, we will implement a SearchView in our Android app so that we can search a location name and add a marker to that location. "
},
{
"code": null,
"e": 758,
"s": 363,
"text": "We will be building a simple application in which we will be displaying a simple Google map and a SearchView. Inside that search view when users enter any location name then we will add a marker to that location on Google Maps. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 787,
"s": 758,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1013,
"s": 787,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project."
},
{
"code": null,
"e": 1065,
"s": 1013,
"text": "Step 2: Generating an API key for using Google Maps"
},
{
"code": null,
"e": 1423,
"s": 1065,
"text": "To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY. "
},
{
"code": null,
"e": 1471,
"s": 1423,
"text": "Step 3: Working with the activity_maps.xml file"
},
{
"code": null,
"e": 1815,
"s": 1471,
"text": "As we are adding SearchView to our Google Maps for searching a location and adding a marker on that location. So we have to add a search view to our activity_maps.xml file. For adding SearchView, navigate to the app > res > layout > activity_maps.xml and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 1819,
"s": 1815,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--fragment to display our maps--> <fragment xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/map\" android:name=\"com.google.android.gms.maps.SupportMapFragment\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MapsActivity\" /> <!--search view to search our location--> <androidx.appcompat.widget.SearchView android:id=\"@+id/idSearchView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:background=\"#BFBFBF\" android:elevation=\"5dp\" app:iconifiedByDefault=\"false\" app:queryHint=\"Search Here\" /> </RelativeLayout>",
"e": 2808,
"s": 1819,
"text": null
},
{
"code": null,
"e": 2856,
"s": 2808,
"text": "Step 4: Working with the MapsActivity.java file"
},
{
"code": null,
"e": 3046,
"s": 2856,
"text": "Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 3051,
"s": 3046,
"text": "Java"
},
{
"code": "import android.location.Address;import android.location.Geocoder;import android.os.Bundle; import androidx.appcompat.widget.SearchView;import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException;import java.util.List; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; // creating a variable // for search view. SearchView searchView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // initializing our search view. searchView = findViewById(R.id.idSearchView); // Obtain the SupportMapFragment and get notified // when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); // adding on query listener for our search view. searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // on below line we are getting the // location name from search view. String location = searchView.getQuery().toString(); // below line is to create a list of address // where we will store the list of all address. List<Address> addressList = null; // checking if the entered location is null or not. if (location != null || location.equals(\"\")) { // on below line we are creating and initializing a geo coder. Geocoder geocoder = new Geocoder(MapsActivity.this); try { // on below line we are getting location from the // location name and adding that location to address list. addressList = geocoder.getFromLocationName(location, 1); } catch (IOException e) { e.printStackTrace(); } // on below line we are getting the location // from our list a first position. Address address = addressList.get(0); // on below line we are creating a variable for our location // where we will add our locations latitude and longitude. LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); // on below line we are adding marker to that position. mMap.addMarker(new MarkerOptions().position(latLng).title(location)); // below line is to animate camera to that position. mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10)); } return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); // at last we calling our map fragment to update. mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; }}",
"e": 6756,
"s": 3051,
"text": null
},
{
"code": null,
"e": 6805,
"s": 6756,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 6813,
"s": 6805,
"text": "android"
},
{
"code": null,
"e": 6837,
"s": 6813,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6845,
"s": 6837,
"text": "Android"
},
{
"code": null,
"e": 6850,
"s": 6845,
"text": "Java"
},
{
"code": null,
"e": 6869,
"s": 6850,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6874,
"s": 6869,
"text": "Java"
},
{
"code": null,
"e": 6882,
"s": 6874,
"text": "Android"
}
]
|
Python | Get the starting index for all occurrences of given substring | 18 Dec, 2019
Given a string and a substring, the task to find out the starting index for all the occurrences of a given substring in a string. Letβs discuss a few methods to solve the given task.
Method #1: Using Naive Method
# Python3 code to demonstrate# to find all occurrences of substring in# a string # Initialising stringini_string = 'xbzefdgstbzefzexezef' # Initialising sub-stringsub_string = 'zef' # Printing initial string and sub-stringprint ("initial_strings : ", ini_string, "\nsubstring : ", sub_string) res = []flag = 0k = 0 # Finding all occurrences of substring# in a string using Naive methodfor i in range(0, len(ini_string)): k = i flag = 0 for j in range(0, len(sub_string)): if ini_string[k] != sub_string[j]: flag = 1 if flag: break k = k + 1 if flag == 0: res.append(i) # printing result(print ("resultant positions", str(res))
initial_strings : xbzefdgstbzefzexezef
substring : zef
resultant positions [2, 10, 17]
&nsbp;Method #2: Using list comprehension
# Python3 code to demonstrate# to find all occurrences of substring in# a string # Initialising stringini_string = 'xbzefdgstbzefzexezef' # Initialising sub-stringsub_string = 'zef' # Printing initial string and sub-stringprint ("initial_strings : ", ini_string, "\nsubstring : ", sub_string) res = []# Finding all occurrences of substring# in a string using list comprehensionres = [i for i in range(len(ini_string)) if ini_string.startswith(sub_string, i)] # printing result(print ("resultant positions", str(res))
initial_strings : xbzefdgstbzefzexezef
substring : zef
resultant positions [2, 10, 17]
Method #3: Using regex
# Python3 code to demonstrate# to find all occurrences of substring in# a stringimport re # Initialising stringini_string = 'xbzefdgstbzefzexezef' # Initialising sub-stringsub_string = 'zef' # Printing initial string and sub-stringprint ("initial_strings : ", ini_string, "\nsubstring : ", sub_string) res = []# Finding all occurrences of substring# in a string using re.finditerres = [m.start() for m in re.finditer(sub_string, ini_string)] # printing result(print ("resultant positions", str(res))
initial_strings : xbzefdgstbzefzexezef
substring : zef
resultant positions [2, 10, 17]
nidhi_biet
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Dec, 2019"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "Given a string and a substring, the task to find out the starting index for all the occurrences of a given substring in a string. Letβs discuss a few methods to solve the given task."
},
{
"code": null,
"e": 241,
"s": 211,
"text": "Method #1: Using Naive Method"
},
{
"code": "# Python3 code to demonstrate# to find all occurrences of substring in# a string # Initialising stringini_string = 'xbzefdgstbzefzexezef' # Initialising sub-stringsub_string = 'zef' # Printing initial string and sub-stringprint (\"initial_strings : \", ini_string, \"\\nsubstring : \", sub_string) res = []flag = 0k = 0 # Finding all occurrences of substring# in a string using Naive methodfor i in range(0, len(ini_string)): k = i flag = 0 for j in range(0, len(sub_string)): if ini_string[k] != sub_string[j]: flag = 1 if flag: break k = k + 1 if flag == 0: res.append(i) # printing result(print (\"resultant positions\", str(res))",
"e": 938,
"s": 241,
"text": null
},
{
"code": null,
"e": 1029,
"s": 938,
"text": "initial_strings : xbzefdgstbzefzexezef \nsubstring : zef\nresultant positions [2, 10, 17]\n"
},
{
"code": null,
"e": 1071,
"s": 1029,
"text": "&nsbp;Method #2: Using list comprehension"
},
{
"code": "# Python3 code to demonstrate# to find all occurrences of substring in# a string # Initialising stringini_string = 'xbzefdgstbzefzexezef' # Initialising sub-stringsub_string = 'zef' # Printing initial string and sub-stringprint (\"initial_strings : \", ini_string, \"\\nsubstring : \", sub_string) res = []# Finding all occurrences of substring# in a string using list comprehensionres = [i for i in range(len(ini_string)) if ini_string.startswith(sub_string, i)] # printing result(print (\"resultant positions\", str(res))",
"e": 1600,
"s": 1071,
"text": null
},
{
"code": null,
"e": 1691,
"s": 1600,
"text": "initial_strings : xbzefdgstbzefzexezef \nsubstring : zef\nresultant positions [2, 10, 17]\n"
},
{
"code": null,
"e": 1715,
"s": 1691,
"text": " Method #3: Using regex"
},
{
"code": "# Python3 code to demonstrate# to find all occurrences of substring in# a stringimport re # Initialising stringini_string = 'xbzefdgstbzefzexezef' # Initialising sub-stringsub_string = 'zef' # Printing initial string and sub-stringprint (\"initial_strings : \", ini_string, \"\\nsubstring : \", sub_string) res = []# Finding all occurrences of substring# in a string using re.finditerres = [m.start() for m in re.finditer(sub_string, ini_string)] # printing result(print (\"resultant positions\", str(res))",
"e": 2220,
"s": 1715,
"text": null
},
{
"code": null,
"e": 2311,
"s": 2220,
"text": "initial_strings : xbzefdgstbzefzexezef \nsubstring : zef\nresultant positions [2, 10, 17]\n"
},
{
"code": null,
"e": 2322,
"s": 2311,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2345,
"s": 2322,
"text": "Python string-programs"
},
{
"code": null,
"e": 2352,
"s": 2345,
"text": "Python"
},
{
"code": null,
"e": 2368,
"s": 2352,
"text": "Python Programs"
}
]
|
Program to convert a given number to words | Set 2 | 04 Jan, 2022
Write code to convert a given number into words.Examples:
Input: 438237764
Output: forty three crore eighty two lakh
thirty seven thousand seven hundred and
sixty four
Input: 999999
Output: nine lakh ninety nine thousand nine
hundred and ninety nine
Input: 1000
Output: one thousand
Explanation:1000 in words is "one thousand"
We have already discussed an approach that handles numbers from 0 to 9999 in the previous post.Solution: This approach can handle number till 20-digits long which are less than ULLONG_MAX (Maximum value for an object of type unsigned long long int). ULLONG_MAX is equal to 18446744073709551615 in decimal assuming compiler takes 8 bytes for storage of unsigned long long int.Below representation shows place value chart for any 9 digits positive integer:
4 3 8 2 3 7 7 6 4
| | | | | | | | |__ ones' place
| | | | | | | |__ __ tens' place
| | | | | | |__ __ __ hundreds' place
| | | | | |__ __ __ __ thousands' place
| | | | |__ __ __ __ __ tens thousands' place
| | | |__ __ __ __ __ __ hundred thousands' place
| | |__ __ __ __ __ __ __ one millions' place
| |__ __ __ __ __ __ __ __ ten millions' place
|__ __ __ __ __ __ __ __ __ hundred millions' place
The idea is to divide the number into individual digits based on the above place value chart and handle them starting from the Most Significant Digit. Hereβs a simple implementation that supports numbers having a maximum of 9 digits. The program can be easily extended to support any 20-digit number.
C++
Java
Python3
C#
PHP
Javascript
/* C++ program to print a given number in words. The program handles till 9 digits numbers and can be easily extended to 20 digit number */#include <iostream>using namespace std; // strings at index 0 is not used, it is to make array// indexing simplestring one[] = { "", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen " }; // strings at index 0 and 1 are not used, they is to// make array indexing simplestring ten[] = { "", "", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety " }; // n is 1- or 2-digit numberstring numToWords(int n, string s){ string str = ""; // if n is more than 19, divide it if (n > 19) str += ten[n / 10] + one[n % 10]; else str += one[n]; // if n is non-zero if (n) str += s; return str;} // Function to print a given number in wordsstring convertToWords(long n){ // stores word representation of given number n string out; // handles digits at ten millions and hundred // millions places (if any) out += numToWords((n / 10000000), "crore "); // handles digits at hundred thousands and one // millions places (if any) out += numToWords(((n / 100000) % 100), "lakh "); // handles digits at thousands and tens thousands // places (if any) out += numToWords(((n / 1000) % 100), "thousand "); // handles digit at hundreds places (if any) out += numToWords(((n / 100) % 10), "hundred "); if (n > 100 && n % 100) out += "and "; // handles digits at ones and tens places (if any) out += numToWords((n % 100), ""); //Handling the n=0 case if(out=="") out = "zero"; return out;} // Driver codeint main(){ // long handles upto 9 digit no // change to unsigned long long int to // handle more digit number long n = 438237764; // convert given number in words cout << convertToWords(n) << endl; return 0;}
/* Java program to print a given number in words.The program handles till 9 digits numbers andcan be easily extended to 20 digit number */class GFG { // Strings at index 0 is not used, it is to make array // indexing simple static String one[] = { "", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen " }; // Strings at index 0 and 1 are not used, they is to // make array indexing simple static String ten[] = { "", "", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety " }; // n is 1- or 2-digit number static String numToWords(int n, String s) { String str = ""; // if n is more than 19, divide it if (n > 19) { str += ten[n / 10] + one[n % 10]; } else { str += one[n]; } // if n is non-zero if (n != 0) { str += s; } return str; } // Function to print a given number in words static String convertToWords(long n) { // stores word representation of given number n String out = ""; // handles digits at ten millions and hundred // millions places (if any) out += numToWords((int)(n / 10000000), "crore "); // handles digits at hundred thousands and one // millions places (if any) out += numToWords((int)((n / 100000) % 100), "lakh "); // handles digits at thousands and tens thousands // places (if any) out += numToWords((int)((n / 1000) % 100), "thousand "); // handles digit at hundreds places (if any) out += numToWords((int)((n / 100) % 10), "hundred "); if (n > 100 && n % 100 > 0) { out += "and "; } // handles digits at ones and tens places (if any) out += numToWords((int)(n % 100), ""); return out; } // Driver code public static void main(String[] args) { // long handles upto 9 digit no // change to unsigned long long int to // handle more digit number long n = 438237764; // convert given number in words System.out.printf(convertToWords(n)); }}
# Python3 program to print a given number in words.# The program handles till 9 digits numbers and# can be easily extended to 20 digit number # strings at index 0 is not used, it# is to make array indexing simpleone = [ "", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen "]; # strings at index 0 and 1 are not used,# they is to make array indexing simpleten = [ "", "", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety "]; # n is 1- or 2-digit numberdef numToWords(n, s): str = ""; # if n is more than 19, divide it if (n > 19): str += ten[n // 10] + one[n % 10]; else: str += one[n]; # if n is non-zero if (n): str += s; return str; # Function to print a given number in wordsdef convertToWords(n): # stores word representation of given # number n out = ""; # handles digits at ten millions and # hundred millions places (if any) out += numToWords((n // 10000000), "crore "); # handles digits at hundred thousands # and one millions places (if any) out += numToWords(((n // 100000) % 100), "lakh "); # handles digits at thousands and tens # thousands places (if any) out += numToWords(((n // 1000) % 100), "thousand "); # handles digit at hundreds places (if any) out += numToWords(((n // 100) % 10), "hundred "); if (n > 100 and n % 100): out += "and "; # handles digits at ones and tens # places (if any) out += numToWords((n % 100), ""); return out; # Driver code # long handles upto 9 digit no# change to unsigned long long# int to handle more digit numbern = 438237764; # convert given number in wordsprint(convertToWords(n)); # This code is contributed by mits
/* C# program to print a given number in words.The program handles till 9 digits numbers andcan be easily extended to 20 digit number */using System;class GFG { // strings at index 0 is not used, it is // to make array indexing simple static string[] one = { "", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen " }; // strings at index 0 and 1 are not used, // they is to make array indexing simple static string[] ten = { "", "", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety " }; // n is 1- or 2-digit number static string numToWords(int n, string s) { string str = ""; // if n is more than 19, divide it if (n > 19) { str += ten[n / 10] + one[n % 10]; } else { str += one[n]; } // if n is non-zero if (n != 0) { str += s; } return str; } // Function to print a given number in words static string convertToWords(long n) { // stores word representation of // given number n string out1 = ""; // handles digits at ten millions and // hundred millions places (if any) out1 += numToWords((int)(n / 10000000), "crore "); // handles digits at hundred thousands // and one millions places (if any) out1 += numToWords((int)((n / 100000) % 100), "lakh "); // handles digits at thousands and tens // thousands places (if any) out1 += numToWords((int)((n / 1000) % 100), "thousand "); // handles digit at hundreds places (if any) out1 += numToWords((int)((n / 100) % 10), "hundred "); if (n > 100 && n % 100 > 0) { out1 += "and "; } // handles digits at ones and tens // places (if any) out1 += numToWords((int)(n % 100), ""); return out1; } // Driver code static void Main() { // long handles upto 9 digit no // change to unsigned long long int to // handle more digit number long n = 438237764; // convert given number in words Console.WriteLine(convertToWords(n)); }} // This code is contributed by mits
<?php/* PHP program to print a given number in words.The program handles till 9 digits numbers andcan be easily extended to 20 digit number */ // strings at index 0 is not used, it is// to make array indexing simple$one = array("", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen "); // strings at index 0 and 1 are not used,// they is to make array indexing simple$ten = array("", "", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety "); // n is 1- or 2-digit numberfunction numToWords($n, $s){ global $one, $ten; $str = ""; // if n is more than 19, divide it if ($n > 19) { $str .= $ten[(int)($n / 10)]; $str .= $one[$n % 10]; } else $str .= $one[$n]; // if n is non-zero if ($n != 0 ) $str .= $s; return $str;} // Function to print a given number in wordsfunction convertToWords($n){ // stores word representation of // given number n $out = ""; // handles digits at ten millions and // hundred millions places (if any) $out .= numToWords((int)($n / 10000000), "crore "); // handles digits at hundred thousands // and one millions places (if any) $out .= numToWords(((int)($n / 100000) % 100), "lakh "); // handles digits at thousands and tens // thousands places (if any) $out .= numToWords(((int)($n / 1000) % 100), "thousand "); // handles digit at hundreds places (if any) $out .= numToWords(((int)($n / 100) % 10), "hundred "); if ($n > 100 && $n % 100) $out .= "and "; // handles digits at ones and tens // places (if any) $out .= numToWords(($n % 100), ""); return $out;} // Driver code // long handles upto 9 digit no// change to unsigned long long int to// handle more digit number$n = 438237764; // convert given number in wordsecho convertToWords($n) . "\n"; // This code is contributed by Akanksha Rai?>
<script> /* Javascript program to print a given number in words. The program handles till 9 digits numbers andcan be easily extended to20 digit number */ // Strings at index 0 is not used, it is to make array // indexing simple var one = [ "", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen " ]; // Strings at index 0 and 1 are not used, they is to // make array indexing simple var ten = [ "", "", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety " ]; // n is 1- or 2-digit number function numToWords(n, s) { var str = ""; // if n is more than 19, divide it if (n > 19) { str += ten[parseInt(n / 10)] + one[n % 10]; } else { str += one[n]; } // if n is non-zero if (n != 0) { str += s; } return str; } // Function to print a given number in words function convertToWords(n) { // stores word representation of given number n var out = ""; // handles digits at ten millions and hundred // millions places (if any) out += numToWords(parseInt(n / 10000000), "crore "); // handles digits at hundred thousands and one // millions places (if any) out += numToWords(parseInt((n / 100000) % 100), "lakh "); // handles digits at thousands and tens thousands // places (if any) out += numToWords(parseInt((n / 1000) % 100), "thousand "); // handles digit at hundreds places (if any) out += numToWords(parseInt((n / 100) % 10), "hundred "); if (n > 100 && n % 100 > 0) { out += "and "; } // handles digits at ones and tens places (if any) out += numToWords(parseInt(n % 100), ""); return out; } // Driver code // var handles upto 9 digit no // change to unsigned var var var to // handle more digit number var n = 438237764; // convert given number in words document.write(convertToWords(n)); // This code is contributed by Amit Katiyar </script>
Output:
forty three crore eighty two lakh thirty seven
thousand seven hundred and sixty four
Complexity Analysis:
Time complexity: O(1). The loop runs for a constant amount of time.
Auxiliary space: O(1). As no extra space is required.
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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
Mithun Kumar
Akanksha_Rai
andrew1234
amit143katiyar
simranarora5sos
amol935paliwal
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 113,
"s": 54,
"text": "Write code to convert a given number into words.Examples: "
},
{
"code": null,
"e": 388,
"s": 113,
"text": "Input: 438237764\nOutput: forty three crore eighty two lakh \nthirty seven thousand seven hundred and \nsixty four \n\nInput: 999999\nOutput: nine lakh ninety nine thousand nine\nhundred and ninety nine\n\nInput: 1000\nOutput: one thousand \nExplanation:1000 in words is \"one thousand\""
},
{
"code": null,
"e": 845,
"s": 388,
"text": "We have already discussed an approach that handles numbers from 0 to 9999 in the previous post.Solution: This approach can handle number till 20-digits long which are less than ULLONG_MAX (Maximum value for an object of type unsigned long long int). ULLONG_MAX is equal to 18446744073709551615 in decimal assuming compiler takes 8 bytes for storage of unsigned long long int.Below representation shows place value chart for any 9 digits positive integer: "
},
{
"code": null,
"e": 1291,
"s": 845,
"text": "4 3 8 2 3 7 7 6 4\n| | | | | | | | |__ ones' place\n| | | | | | | |__ __ tens' place\n| | | | | | |__ __ __ hundreds' place\n| | | | | |__ __ __ __ thousands' place\n| | | | |__ __ __ __ __ tens thousands' place\n| | | |__ __ __ __ __ __ hundred thousands' place\n| | |__ __ __ __ __ __ __ one millions' place\n| |__ __ __ __ __ __ __ __ ten millions' place\n|__ __ __ __ __ __ __ __ __ hundred millions' place"
},
{
"code": null,
"e": 1593,
"s": 1291,
"text": "The idea is to divide the number into individual digits based on the above place value chart and handle them starting from the Most Significant Digit. Hereβs a simple implementation that supports numbers having a maximum of 9 digits. The program can be easily extended to support any 20-digit number. "
},
{
"code": null,
"e": 1597,
"s": 1593,
"text": "C++"
},
{
"code": null,
"e": 1602,
"s": 1597,
"text": "Java"
},
{
"code": null,
"e": 1610,
"s": 1602,
"text": "Python3"
},
{
"code": null,
"e": 1613,
"s": 1610,
"text": "C#"
},
{
"code": null,
"e": 1617,
"s": 1613,
"text": "PHP"
},
{
"code": null,
"e": 1628,
"s": 1617,
"text": "Javascript"
},
{
"code": "/* C++ program to print a given number in words. The program handles till 9 digits numbers and can be easily extended to 20 digit number */#include <iostream>using namespace std; // strings at index 0 is not used, it is to make array// indexing simplestring one[] = { \"\", \"one \", \"two \", \"three \", \"four \", \"five \", \"six \", \"seven \", \"eight \", \"nine \", \"ten \", \"eleven \", \"twelve \", \"thirteen \", \"fourteen \", \"fifteen \", \"sixteen \", \"seventeen \", \"eighteen \", \"nineteen \" }; // strings at index 0 and 1 are not used, they is to// make array indexing simplestring ten[] = { \"\", \"\", \"twenty \", \"thirty \", \"forty \", \"fifty \", \"sixty \", \"seventy \", \"eighty \", \"ninety \" }; // n is 1- or 2-digit numberstring numToWords(int n, string s){ string str = \"\"; // if n is more than 19, divide it if (n > 19) str += ten[n / 10] + one[n % 10]; else str += one[n]; // if n is non-zero if (n) str += s; return str;} // Function to print a given number in wordsstring convertToWords(long n){ // stores word representation of given number n string out; // handles digits at ten millions and hundred // millions places (if any) out += numToWords((n / 10000000), \"crore \"); // handles digits at hundred thousands and one // millions places (if any) out += numToWords(((n / 100000) % 100), \"lakh \"); // handles digits at thousands and tens thousands // places (if any) out += numToWords(((n / 1000) % 100), \"thousand \"); // handles digit at hundreds places (if any) out += numToWords(((n / 100) % 10), \"hundred \"); if (n > 100 && n % 100) out += \"and \"; // handles digits at ones and tens places (if any) out += numToWords((n % 100), \"\"); //Handling the n=0 case if(out==\"\") out = \"zero\"; return out;} // Driver codeint main(){ // long handles upto 9 digit no // change to unsigned long long int to // handle more digit number long n = 438237764; // convert given number in words cout << convertToWords(n) << endl; return 0;}",
"e": 3794,
"s": 1628,
"text": null
},
{
"code": "/* Java program to print a given number in words.The program handles till 9 digits numbers andcan be easily extended to 20 digit number */class GFG { // Strings at index 0 is not used, it is to make array // indexing simple static String one[] = { \"\", \"one \", \"two \", \"three \", \"four \", \"five \", \"six \", \"seven \", \"eight \", \"nine \", \"ten \", \"eleven \", \"twelve \", \"thirteen \", \"fourteen \", \"fifteen \", \"sixteen \", \"seventeen \", \"eighteen \", \"nineteen \" }; // Strings at index 0 and 1 are not used, they is to // make array indexing simple static String ten[] = { \"\", \"\", \"twenty \", \"thirty \", \"forty \", \"fifty \", \"sixty \", \"seventy \", \"eighty \", \"ninety \" }; // n is 1- or 2-digit number static String numToWords(int n, String s) { String str = \"\"; // if n is more than 19, divide it if (n > 19) { str += ten[n / 10] + one[n % 10]; } else { str += one[n]; } // if n is non-zero if (n != 0) { str += s; } return str; } // Function to print a given number in words static String convertToWords(long n) { // stores word representation of given number n String out = \"\"; // handles digits at ten millions and hundred // millions places (if any) out += numToWords((int)(n / 10000000), \"crore \"); // handles digits at hundred thousands and one // millions places (if any) out += numToWords((int)((n / 100000) % 100), \"lakh \"); // handles digits at thousands and tens thousands // places (if any) out += numToWords((int)((n / 1000) % 100), \"thousand \"); // handles digit at hundreds places (if any) out += numToWords((int)((n / 100) % 10), \"hundred \"); if (n > 100 && n % 100 > 0) { out += \"and \"; } // handles digits at ones and tens places (if any) out += numToWords((int)(n % 100), \"\"); return out; } // Driver code public static void main(String[] args) { // long handles upto 9 digit no // change to unsigned long long int to // handle more digit number long n = 438237764; // convert given number in words System.out.printf(convertToWords(n)); }}",
"e": 6279,
"s": 3794,
"text": null
},
{
"code": "# Python3 program to print a given number in words.# The program handles till 9 digits numbers and# can be easily extended to 20 digit number # strings at index 0 is not used, it# is to make array indexing simpleone = [ \"\", \"one \", \"two \", \"three \", \"four \", \"five \", \"six \", \"seven \", \"eight \", \"nine \", \"ten \", \"eleven \", \"twelve \", \"thirteen \", \"fourteen \", \"fifteen \", \"sixteen \", \"seventeen \", \"eighteen \", \"nineteen \"]; # strings at index 0 and 1 are not used,# they is to make array indexing simpleten = [ \"\", \"\", \"twenty \", \"thirty \", \"forty \", \"fifty \", \"sixty \", \"seventy \", \"eighty \", \"ninety \"]; # n is 1- or 2-digit numberdef numToWords(n, s): str = \"\"; # if n is more than 19, divide it if (n > 19): str += ten[n // 10] + one[n % 10]; else: str += one[n]; # if n is non-zero if (n): str += s; return str; # Function to print a given number in wordsdef convertToWords(n): # stores word representation of given # number n out = \"\"; # handles digits at ten millions and # hundred millions places (if any) out += numToWords((n // 10000000), \"crore \"); # handles digits at hundred thousands # and one millions places (if any) out += numToWords(((n // 100000) % 100), \"lakh \"); # handles digits at thousands and tens # thousands places (if any) out += numToWords(((n // 1000) % 100), \"thousand \"); # handles digit at hundreds places (if any) out += numToWords(((n // 100) % 10), \"hundred \"); if (n > 100 and n % 100): out += \"and \"; # handles digits at ones and tens # places (if any) out += numToWords((n % 100), \"\"); return out; # Driver code # long handles upto 9 digit no# change to unsigned long long# int to handle more digit numbern = 438237764; # convert given number in wordsprint(convertToWords(n)); # This code is contributed by mits",
"e": 8319,
"s": 6279,
"text": null
},
{
"code": "/* C# program to print a given number in words.The program handles till 9 digits numbers andcan be easily extended to 20 digit number */using System;class GFG { // strings at index 0 is not used, it is // to make array indexing simple static string[] one = { \"\", \"one \", \"two \", \"three \", \"four \", \"five \", \"six \", \"seven \", \"eight \", \"nine \", \"ten \", \"eleven \", \"twelve \", \"thirteen \", \"fourteen \", \"fifteen \", \"sixteen \", \"seventeen \", \"eighteen \", \"nineteen \" }; // strings at index 0 and 1 are not used, // they is to make array indexing simple static string[] ten = { \"\", \"\", \"twenty \", \"thirty \", \"forty \", \"fifty \", \"sixty \", \"seventy \", \"eighty \", \"ninety \" }; // n is 1- or 2-digit number static string numToWords(int n, string s) { string str = \"\"; // if n is more than 19, divide it if (n > 19) { str += ten[n / 10] + one[n % 10]; } else { str += one[n]; } // if n is non-zero if (n != 0) { str += s; } return str; } // Function to print a given number in words static string convertToWords(long n) { // stores word representation of // given number n string out1 = \"\"; // handles digits at ten millions and // hundred millions places (if any) out1 += numToWords((int)(n / 10000000), \"crore \"); // handles digits at hundred thousands // and one millions places (if any) out1 += numToWords((int)((n / 100000) % 100), \"lakh \"); // handles digits at thousands and tens // thousands places (if any) out1 += numToWords((int)((n / 1000) % 100), \"thousand \"); // handles digit at hundreds places (if any) out1 += numToWords((int)((n / 100) % 10), \"hundred \"); if (n > 100 && n % 100 > 0) { out1 += \"and \"; } // handles digits at ones and tens // places (if any) out1 += numToWords((int)(n % 100), \"\"); return out1; } // Driver code static void Main() { // long handles upto 9 digit no // change to unsigned long long int to // handle more digit number long n = 438237764; // convert given number in words Console.WriteLine(convertToWords(n)); }} // This code is contributed by mits",
"e": 10965,
"s": 8319,
"text": null
},
{
"code": "<?php/* PHP program to print a given number in words.The program handles till 9 digits numbers andcan be easily extended to 20 digit number */ // strings at index 0 is not used, it is// to make array indexing simple$one = array(\"\", \"one \", \"two \", \"three \", \"four \", \"five \", \"six \", \"seven \", \"eight \", \"nine \", \"ten \", \"eleven \", \"twelve \", \"thirteen \", \"fourteen \", \"fifteen \", \"sixteen \", \"seventeen \", \"eighteen \", \"nineteen \"); // strings at index 0 and 1 are not used,// they is to make array indexing simple$ten = array(\"\", \"\", \"twenty \", \"thirty \", \"forty \", \"fifty \", \"sixty \", \"seventy \", \"eighty \", \"ninety \"); // n is 1- or 2-digit numberfunction numToWords($n, $s){ global $one, $ten; $str = \"\"; // if n is more than 19, divide it if ($n > 19) { $str .= $ten[(int)($n / 10)]; $str .= $one[$n % 10]; } else $str .= $one[$n]; // if n is non-zero if ($n != 0 ) $str .= $s; return $str;} // Function to print a given number in wordsfunction convertToWords($n){ // stores word representation of // given number n $out = \"\"; // handles digits at ten millions and // hundred millions places (if any) $out .= numToWords((int)($n / 10000000), \"crore \"); // handles digits at hundred thousands // and one millions places (if any) $out .= numToWords(((int)($n / 100000) % 100), \"lakh \"); // handles digits at thousands and tens // thousands places (if any) $out .= numToWords(((int)($n / 1000) % 100), \"thousand \"); // handles digit at hundreds places (if any) $out .= numToWords(((int)($n / 100) % 10), \"hundred \"); if ($n > 100 && $n % 100) $out .= \"and \"; // handles digits at ones and tens // places (if any) $out .= numToWords(($n % 100), \"\"); return $out;} // Driver code // long handles upto 9 digit no// change to unsigned long long int to// handle more digit number$n = 438237764; // convert given number in wordsecho convertToWords($n) . \"\\n\"; // This code is contributed by Akanksha Rai?>",
"e": 13104,
"s": 10965,
"text": null
},
{
"code": "<script> /* Javascript program to print a given number in words. The program handles till 9 digits numbers andcan be easily extended to20 digit number */ // Strings at index 0 is not used, it is to make array // indexing simple var one = [ \"\", \"one \", \"two \", \"three \", \"four \", \"five \", \"six \", \"seven \", \"eight \", \"nine \", \"ten \", \"eleven \", \"twelve \", \"thirteen \", \"fourteen \", \"fifteen \", \"sixteen \", \"seventeen \", \"eighteen \", \"nineteen \" ]; // Strings at index 0 and 1 are not used, they is to // make array indexing simple var ten = [ \"\", \"\", \"twenty \", \"thirty \", \"forty \", \"fifty \", \"sixty \", \"seventy \", \"eighty \", \"ninety \" ]; // n is 1- or 2-digit number function numToWords(n, s) { var str = \"\"; // if n is more than 19, divide it if (n > 19) { str += ten[parseInt(n / 10)] + one[n % 10]; } else { str += one[n]; } // if n is non-zero if (n != 0) { str += s; } return str; } // Function to print a given number in words function convertToWords(n) { // stores word representation of given number n var out = \"\"; // handles digits at ten millions and hundred // millions places (if any) out += numToWords(parseInt(n / 10000000), \"crore \"); // handles digits at hundred thousands and one // millions places (if any) out += numToWords(parseInt((n / 100000) % 100), \"lakh \"); // handles digits at thousands and tens thousands // places (if any) out += numToWords(parseInt((n / 1000) % 100), \"thousand \"); // handles digit at hundreds places (if any) out += numToWords(parseInt((n / 100) % 10), \"hundred \"); if (n > 100 && n % 100 > 0) { out += \"and \"; } // handles digits at ones and tens places (if any) out += numToWords(parseInt(n % 100), \"\"); return out; } // Driver code // var handles upto 9 digit no // change to unsigned var var var to // handle more digit number var n = 438237764; // convert given number in words document.write(convertToWords(n)); // This code is contributed by Amit Katiyar </script>",
"e": 15505,
"s": 13104,
"text": null
},
{
"code": null,
"e": 15514,
"s": 15505,
"text": "Output: "
},
{
"code": null,
"e": 15601,
"s": 15514,
"text": "forty three crore eighty two lakh thirty seven \nthousand seven hundred and sixty four "
},
{
"code": null,
"e": 15623,
"s": 15601,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 15691,
"s": 15623,
"text": "Time complexity: O(1). The loop runs for a constant amount of time."
},
{
"code": null,
"e": 15745,
"s": 15691,
"text": "Auxiliary space: O(1). As no extra space is required."
},
{
"code": null,
"e": 16165,
"s": 15745,
"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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 16177,
"s": 16165,
"text": "29AjayKumar"
},
{
"code": null,
"e": 16190,
"s": 16177,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 16203,
"s": 16190,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 16214,
"s": 16203,
"text": "andrew1234"
},
{
"code": null,
"e": 16229,
"s": 16214,
"text": "amit143katiyar"
},
{
"code": null,
"e": 16245,
"s": 16229,
"text": "simranarora5sos"
},
{
"code": null,
"e": 16260,
"s": 16245,
"text": "amol935paliwal"
},
{
"code": null,
"e": 16273,
"s": 16260,
"text": "Mathematical"
},
{
"code": null,
"e": 16286,
"s": 16273,
"text": "Mathematical"
}
]
|
Serialize and Deserialize complex JSON in Python | 17 May, 2022
JSON stands for JavaScript Object Notation. It is a format that encodes the data in string format. JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization. JSON Object is defined using curly braces{} and consists of a key-value pair. It is important to note that the JSON object key is a string and its value can be any primitive(e.g. int, string, null) or complex data types(e.g. array).
Example of JSON Object:
{
"id":101,
"company" : "GeeksForGeeks"
}
Complex JSON objects are those objects that contain a nested object inside the other. Example of Complex JSON Object.
{
"id":101,
"company" : "GeeksForGeeks",
"Topics" : { "Data Structure",
"Algorithm",
"Gate Topics" }
}
Serialization & Deserialization
Python and the JSON module is working extremely well with dictionaries. For serializing and deserializing of JSON objects Python β__dict__β can be used. There is the __dict__ on any Python object, which is a dictionary used to store an objectβs (writable) attributes. We can use that for working with JSON, and that works well.Code:
Python3
import json class GFG_User(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name user = GFG_User(first_name="Jake", last_name="Doyle")json_data = json.dumps(user.__dict__)print(json_data)print(GFG_User(**json.loads(json_data)))
Output:
{"first_name": "Jake", "last_name": "Doyle"}
__main__.GFG_User object at 0x105ca7278
Note: The double asterisks ** in the GFG_User(**json.load(json_data) line may look confusing. But all it does is expanding the dictionary.
Now things get tricky while dealing with complex JSON objects as our trick β__dict__β doesnβt work anymore.Code:
Python3
from typing import Listimport json class Student(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name class Team(object): def __init__(self, students: List[Student]): self.students = students student1 = Student(first_name="Geeky", last_name="Guy")student2 = Student(first_name="GFG", last_name="Rocks")team = Team(students=[student1, student2])json_data = json.dumps(team.__dict__, indent=4)print(json_data)
Output:
TypeError: Object of type Student is not JSON serializable
But if you look at the documentation of dump function you will see there is a default setting that we can use. Simply by replacing this line:
json_data = json.dumps(team.__dict__, indent=4)
By this line:
json_data = json.dumps(team.__dict__, default=lambda o: o.__dict__, indent=4)
And everything works now as before. Now, letβs look at Deserializing:Code:
Python3
from typing import Listimport json class Student(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name class Team(object): def __init__(self, students: List[Student]): self.students = students student1 = Student(first_name="Geeky", last_name="Guy")student2 = Student(first_name="GFG", last_name="Rocks")team = Team(students=[student1, student2]) # Serializationjson_data = json.dumps(team, default=lambda o: o.__dict__, indent=4)print(json_data) # Deserializationdecoded_team = Team(**json.loads(json_data))print(decoded_team)
Output:
{
"students": [
{
"first_name": "Geeky",
"last_name": "Guy"
},
{
"first_name": "GFG",
"last_name": "Rocks"
}
]
}
__main__.Team object at 0x105cd41d0
mohamedshoukry
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2022"
},
{
"code": null,
"e": 602,
"s": 28,
"text": "JSON stands for JavaScript Object Notation. It is a format that encodes the data in string format. JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization. JSON Object is defined using curly braces{} and consists of a key-value pair. It is important to note that the JSON object key is a string and its value can be any primitive(e.g. int, string, null) or complex data types(e.g. array)."
},
{
"code": null,
"e": 626,
"s": 602,
"text": "Example of JSON Object:"
},
{
"code": null,
"e": 670,
"s": 626,
"text": "{\n \"id\":101,\n \"company\" : \"GeeksForGeeks\"\n}"
},
{
"code": null,
"e": 788,
"s": 670,
"text": "Complex JSON objects are those objects that contain a nested object inside the other. Example of Complex JSON Object."
},
{
"code": null,
"e": 922,
"s": 788,
"text": "{\n \"id\":101,\n \"company\" : \"GeeksForGeeks\",\n \"Topics\" : { \"Data Structure\",\n \"Algorithm\",\n \"Gate Topics\" }\n}"
},
{
"code": null,
"e": 954,
"s": 922,
"text": "Serialization & Deserialization"
},
{
"code": null,
"e": 1288,
"s": 954,
"text": "Python and the JSON module is working extremely well with dictionaries. For serializing and deserializing of JSON objects Python β__dict__β can be used. There is the __dict__ on any Python object, which is a dictionary used to store an objectβs (writable) attributes. We can use that for working with JSON, and that works well.Code: "
},
{
"code": null,
"e": 1296,
"s": 1288,
"text": "Python3"
},
{
"code": "import json class GFG_User(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name user = GFG_User(first_name=\"Jake\", last_name=\"Doyle\")json_data = json.dumps(user.__dict__)print(json_data)print(GFG_User(**json.loads(json_data)))",
"e": 1614,
"s": 1296,
"text": null
},
{
"code": null,
"e": 1623,
"s": 1614,
"text": "Output: "
},
{
"code": null,
"e": 1709,
"s": 1623,
"text": "{\"first_name\": \"Jake\", \"last_name\": \"Doyle\"} \n__main__.GFG_User object at 0x105ca7278"
},
{
"code": null,
"e": 1848,
"s": 1709,
"text": "Note: The double asterisks ** in the GFG_User(**json.load(json_data) line may look confusing. But all it does is expanding the dictionary."
},
{
"code": null,
"e": 1962,
"s": 1848,
"text": "Now things get tricky while dealing with complex JSON objects as our trick β__dict__β doesnβt work anymore.Code: "
},
{
"code": null,
"e": 1970,
"s": 1962,
"text": "Python3"
},
{
"code": "from typing import Listimport json class Student(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name class Team(object): def __init__(self, students: List[Student]): self.students = students student1 = Student(first_name=\"Geeky\", last_name=\"Guy\")student2 = Student(first_name=\"GFG\", last_name=\"Rocks\")team = Team(students=[student1, student2])json_data = json.dumps(team.__dict__, indent=4)print(json_data)",
"e": 2473,
"s": 1970,
"text": null
},
{
"code": null,
"e": 2482,
"s": 2473,
"text": "Output: "
},
{
"code": null,
"e": 2541,
"s": 2482,
"text": "TypeError: Object of type Student is not JSON serializable"
},
{
"code": null,
"e": 2683,
"s": 2541,
"text": "But if you look at the documentation of dump function you will see there is a default setting that we can use. Simply by replacing this line:"
},
{
"code": null,
"e": 2731,
"s": 2683,
"text": "json_data = json.dumps(team.__dict__, indent=4)"
},
{
"code": null,
"e": 2745,
"s": 2731,
"text": "By this line:"
},
{
"code": null,
"e": 2823,
"s": 2745,
"text": "json_data = json.dumps(team.__dict__, default=lambda o: o.__dict__, indent=4)"
},
{
"code": null,
"e": 2899,
"s": 2823,
"text": "And everything works now as before. Now, letβs look at Deserializing:Code: "
},
{
"code": null,
"e": 2907,
"s": 2899,
"text": "Python3"
},
{
"code": "from typing import Listimport json class Student(object): def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name class Team(object): def __init__(self, students: List[Student]): self.students = students student1 = Student(first_name=\"Geeky\", last_name=\"Guy\")student2 = Student(first_name=\"GFG\", last_name=\"Rocks\")team = Team(students=[student1, student2]) # Serializationjson_data = json.dumps(team, default=lambda o: o.__dict__, indent=4)print(json_data) # Deserializationdecoded_team = Team(**json.loads(json_data))print(decoded_team)",
"e": 3528,
"s": 2907,
"text": null
},
{
"code": null,
"e": 3537,
"s": 3528,
"text": "Output: "
},
{
"code": null,
"e": 3774,
"s": 3537,
"text": "{\n \"students\": [\n {\n \"first_name\": \"Geeky\",\n \"last_name\": \"Guy\"\n },\n {\n \"first_name\": \"GFG\",\n \"last_name\": \"Rocks\"\n }\n ]\n}\n__main__.Team object at 0x105cd41d0"
},
{
"code": null,
"e": 3789,
"s": 3774,
"text": "mohamedshoukry"
},
{
"code": null,
"e": 3801,
"s": 3789,
"text": "Python-json"
},
{
"code": null,
"e": 3808,
"s": 3801,
"text": "Python"
}
]
|
HTTP status codes | Successful Responses | 31 Oct, 2019
The HTTP status codes are used to indicate that any specific HTTP request has successfully completed or not. The HTTP status codes are categorized into five sections those are listed below:
Informational responses (100β199)
Successful responses (200β299)
Redirects (300β399)
Client errors (400β499)
Server errors (500β599)
There are ten Successful Responses those are OK, Created, Accepted, Non-Authoritative Information, No Content, Reset Content, Partial Content, Multi-Status, and Already Reported. All of them are described below:
200 OK: The HTTP 200 OK response meaning is that the request made by the client has been successful, but the meaning of the success depending on the four type of request made by the clients. The GET method fetch and transmitted the resources in the message body. The HEAD method is placed in the message body as a entity header. The POST method describing the result of the action is transmitted in the message body, and the last TRACE method contains the request message as received by the server.Status:200 OK
200 OK
201 Created: The 201 Created indicates that the request has succeeded and has led to the creation of a resource. It means the origin server MUST create the resource before returning the 201 Created code if that is not possible then it will become 202 Accepted. Basically this HTTP status code indicates that a new resource has been created as a result of the successful completion of a request.Status:201 Created
201 Created
202 Accepted: The 201 Accepted indicates that the request from the client has been received, but it does not means the server is working on it. Maybe that time the server is working on other requests, so the client has to wait until the turns of that accepted request come. Accepted means it will definitely proceed.Status:202 Accepted
202 Accepted
203 Non-Authoritative Information: The 203 Non-Authoritative Information indicates that the request has been received and understood and the information sent back to the client as the response is from a third-party rather than from the original server. The 203 holds a similar value compared to 214, 214 has the advantage of being applicable to responses with any status code.Status:203 Non-Authoritative Information
203 Non-Authoritative Information
204 No Content: The 204 No Content indicates that the server has successfully processed the request but needs to return any content or maybe there is no need to send back any data. This code is cacheable by default. Tag header is included in such a response. Best suited as a result of a PUT request which updates the content without changing the current content of the page visible to the client. If the page is gonna change it will become 200 OK.Status:204 No Content
204 No Content
205 Reset Content: The 205 Reset Content is send from the server to the client to request the client that reset the content from which the original document was sent. Like if client is sending the details in a form so need to refresh the UI.Status:205 Reset Content
205 Reset Content
206 Partial Content: The 206 Partial Content indicates that the server is sending only a part of the requested resource due to a range header sent by the client. There can two situations if the range is one the Content-Type will be the type of the document returned. If there are several ranges then Content-Type is set to multipart/byteranges and each fragment covers one range.Status:206 Partial Content
206 Partial Content
207 Multi-Status: A multi-status response conveys information about multiple resources where message body is followed by an XML message and contains separate response codes.
208 Already Reported: Already Reported used inside of the <dav:propstat> and it response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.
Supported Browsers: The browsers compatible with the HTTP status code Successful Responses are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "The HTTP status codes are used to indicate that any specific HTTP request has successfully completed or not. The HTTP status codes are categorized into five sections those are listed below:"
},
{
"code": null,
"e": 252,
"s": 218,
"text": "Informational responses (100β199)"
},
{
"code": null,
"e": 283,
"s": 252,
"text": "Successful responses (200β299)"
},
{
"code": null,
"e": 303,
"s": 283,
"text": "Redirects (300β399)"
},
{
"code": null,
"e": 327,
"s": 303,
"text": "Client errors (400β499)"
},
{
"code": null,
"e": 351,
"s": 327,
"text": "Server errors (500β599)"
},
{
"code": null,
"e": 563,
"s": 351,
"text": "There are ten Successful Responses those are OK, Created, Accepted, Non-Authoritative Information, No Content, Reset Content, Partial Content, Multi-Status, and Already Reported. All of them are described below:"
},
{
"code": null,
"e": 1075,
"s": 563,
"text": "200 OK: The HTTP 200 OK response meaning is that the request made by the client has been successful, but the meaning of the success depending on the four type of request made by the clients. The GET method fetch and transmitted the resources in the message body. The HEAD method is placed in the message body as a entity header. The POST method describing the result of the action is transmitted in the message body, and the last TRACE method contains the request message as received by the server.Status:200 OK"
},
{
"code": null,
"e": 1082,
"s": 1075,
"text": "200 OK"
},
{
"code": null,
"e": 1495,
"s": 1082,
"text": "201 Created: The 201 Created indicates that the request has succeeded and has led to the creation of a resource. It means the origin server MUST create the resource before returning the 201 Created code if that is not possible then it will become 202 Accepted. Basically this HTTP status code indicates that a new resource has been created as a result of the successful completion of a request.Status:201 Created"
},
{
"code": null,
"e": 1507,
"s": 1495,
"text": "201 Created"
},
{
"code": null,
"e": 1843,
"s": 1507,
"text": "202 Accepted: The 201 Accepted indicates that the request from the client has been received, but it does not means the server is working on it. Maybe that time the server is working on other requests, so the client has to wait until the turns of that accepted request come. Accepted means it will definitely proceed.Status:202 Accepted"
},
{
"code": null,
"e": 1856,
"s": 1843,
"text": "202 Accepted"
},
{
"code": null,
"e": 2273,
"s": 1856,
"text": "203 Non-Authoritative Information: The 203 Non-Authoritative Information indicates that the request has been received and understood and the information sent back to the client as the response is from a third-party rather than from the original server. The 203 holds a similar value compared to 214, 214 has the advantage of being applicable to responses with any status code.Status:203 Non-Authoritative Information"
},
{
"code": null,
"e": 2307,
"s": 2273,
"text": "203 Non-Authoritative Information"
},
{
"code": null,
"e": 2777,
"s": 2307,
"text": "204 No Content: The 204 No Content indicates that the server has successfully processed the request but needs to return any content or maybe there is no need to send back any data. This code is cacheable by default. Tag header is included in such a response. Best suited as a result of a PUT request which updates the content without changing the current content of the page visible to the client. If the page is gonna change it will become 200 OK.Status:204 No Content"
},
{
"code": null,
"e": 2792,
"s": 2777,
"text": "204 No Content"
},
{
"code": null,
"e": 3058,
"s": 2792,
"text": "205 Reset Content: The 205 Reset Content is send from the server to the client to request the client that reset the content from which the original document was sent. Like if client is sending the details in a form so need to refresh the UI.Status:205 Reset Content"
},
{
"code": null,
"e": 3076,
"s": 3058,
"text": "205 Reset Content"
},
{
"code": null,
"e": 3482,
"s": 3076,
"text": "206 Partial Content: The 206 Partial Content indicates that the server is sending only a part of the requested resource due to a range header sent by the client. There can two situations if the range is one the Content-Type will be the type of the document returned. If there are several ranges then Content-Type is set to multipart/byteranges and each fragment covers one range.Status:206 Partial Content"
},
{
"code": null,
"e": 3502,
"s": 3482,
"text": "206 Partial Content"
},
{
"code": null,
"e": 3676,
"s": 3502,
"text": "207 Multi-Status: A multi-status response conveys information about multiple resources where message body is followed by an XML message and contains separate response codes."
},
{
"code": null,
"e": 3871,
"s": 3676,
"text": "208 Already Reported: Already Reported used inside of the <dav:propstat> and it response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection."
},
{
"code": null,
"e": 3980,
"s": 3871,
"text": "Supported Browsers: The browsers compatible with the HTTP status code Successful Responses are listed below:"
},
{
"code": null,
"e": 3994,
"s": 3980,
"text": "Google Chrome"
},
{
"code": null,
"e": 4012,
"s": 3994,
"text": "Internet Explorer"
},
{
"code": null,
"e": 4020,
"s": 4012,
"text": "Firefox"
},
{
"code": null,
"e": 4027,
"s": 4020,
"text": "Safari"
},
{
"code": null,
"e": 4033,
"s": 4027,
"text": "Opera"
},
{
"code": null,
"e": 4046,
"s": 4033,
"text": "HTTP-headers"
},
{
"code": null,
"e": 4063,
"s": 4046,
"text": "Web Technologies"
}
]
|
Types of Motherboards | 24 Mar, 2022
There isnβt wide range of motherboard sizes available but in this article, we will discuss about the available options and when to use suitable size. Motherboards are described using form factor called Advanced Technology eXTENDED (ATX) and this form factor is invented by INTEL company and it has been industry standard for years now. ATX not only describes motherboard layout but also lays specification for power supply and PC cabinets and different connectors for compatibility purposes. Now, letβs discuss about different sizes available in main stream desktop computer segment. There are three main types of sizes :
1. Standard ATX
2. Micro ATX
3. eXtended ATX
These are explained as following below.
Standard ATX β This motherboard comes in 305*244mm (length*breadth) dimensions, these dimensions can vary with different manufacturer. This motherboard offers more expansion slots, up to four slots for RAM, Two or sometimes more than two PCIe slots for dual graphics cards and more USB and other ports for connectivity, also its size gives space in between components for airflow to keep heat in control. This size of motherboard is used by those who want more expansion slots and different connecting ports and deal with heavy workloads. This motherboard will only fit in cases which support full ATX or Extended ATX motherboards. Micro ATX β This motherboards come in 244*244 mm (length*breadth) dimensions (these dimensions can vary with different manufacturer.). This Motherboard has less ports and slots as compared to Standard ATX board. This type of motherboard is more suitable for those who donβt want to much connectivity and later upgrades like adding more ram and additional GPU or Graphics card and adding PCI cards. This board can fit any case which has enough room 244*244 mm of space and can also be fit in bigger cases which accept Standard ATX and eXTENDED ATX motherboards. eXtended ATX β This motherboard is 344*330 mm dimensions (these dimensions can vary with different manufacturer). This motherboard is designed for both dual CPU and single configuration and has up to 8 ram slots and has more PCIe and PCI slots for adding PCI cards for different purposes. It is used for workstations and servers. Some EATX motherboards are also designed for desktop computing, and there is ample space for cooling and attaching peripherals. Now a dayβs the technology is getting advanced and you can find all those extra slots and power that you get in Standard ATX board in micro ATX board.
Standard ATX β This motherboard comes in 305*244mm (length*breadth) dimensions, these dimensions can vary with different manufacturer. This motherboard offers more expansion slots, up to four slots for RAM, Two or sometimes more than two PCIe slots for dual graphics cards and more USB and other ports for connectivity, also its size gives space in between components for airflow to keep heat in control. This size of motherboard is used by those who want more expansion slots and different connecting ports and deal with heavy workloads. This motherboard will only fit in cases which support full ATX or Extended ATX motherboards.
Micro ATX β This motherboards come in 244*244 mm (length*breadth) dimensions (these dimensions can vary with different manufacturer.). This Motherboard has less ports and slots as compared to Standard ATX board. This type of motherboard is more suitable for those who donβt want to much connectivity and later upgrades like adding more ram and additional GPU or Graphics card and adding PCI cards. This board can fit any case which has enough room 244*244 mm of space and can also be fit in bigger cases which accept Standard ATX and eXTENDED ATX motherboards.
eXtended ATX β This motherboard is 344*330 mm dimensions (these dimensions can vary with different manufacturer). This motherboard is designed for both dual CPU and single configuration and has up to 8 ram slots and has more PCIe and PCI slots for adding PCI cards for different purposes. It is used for workstations and servers. Some EATX motherboards are also designed for desktop computing, and there is ample space for cooling and attaching peripherals. Now a dayβs the technology is getting advanced and you can find all those extra slots and power that you get in Standard ATX board in micro ATX board.
surinderdawra388
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Control Characters
Direct Access Media (DMA) Controller in Computer Architecture
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Programmable peripheral interface 8255
Architecture of 8085 microprocessor
Memory Hierarchy Design and its Characteristics
Write Through and Write Back in Cache
Interrupts
I/O Interface (Interrupt and DMA Mode) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 651,
"s": 28,
"text": "There isnβt wide range of motherboard sizes available but in this article, we will discuss about the available options and when to use suitable size. Motherboards are described using form factor called Advanced Technology eXTENDED (ATX) and this form factor is invented by INTEL company and it has been industry standard for years now. ATX not only describes motherboard layout but also lays specification for power supply and PC cabinets and different connectors for compatibility purposes. Now, letβs discuss about different sizes available in main stream desktop computer segment. There are three main types of sizes :"
},
{
"code": null,
"e": 697,
"s": 651,
"text": "1. Standard ATX\n2. Micro ATX\n3. eXtended ATX "
},
{
"code": null,
"e": 737,
"s": 697,
"text": "These are explained as following below."
},
{
"code": null,
"e": 2544,
"s": 737,
"text": "Standard ATX β This motherboard comes in 305*244mm (length*breadth) dimensions, these dimensions can vary with different manufacturer. This motherboard offers more expansion slots, up to four slots for RAM, Two or sometimes more than two PCIe slots for dual graphics cards and more USB and other ports for connectivity, also its size gives space in between components for airflow to keep heat in control. This size of motherboard is used by those who want more expansion slots and different connecting ports and deal with heavy workloads. This motherboard will only fit in cases which support full ATX or Extended ATX motherboards. Micro ATX β This motherboards come in 244*244 mm (length*breadth) dimensions (these dimensions can vary with different manufacturer.). This Motherboard has less ports and slots as compared to Standard ATX board. This type of motherboard is more suitable for those who donβt want to much connectivity and later upgrades like adding more ram and additional GPU or Graphics card and adding PCI cards. This board can fit any case which has enough room 244*244 mm of space and can also be fit in bigger cases which accept Standard ATX and eXTENDED ATX motherboards. eXtended ATX β This motherboard is 344*330 mm dimensions (these dimensions can vary with different manufacturer). This motherboard is designed for both dual CPU and single configuration and has up to 8 ram slots and has more PCIe and PCI slots for adding PCI cards for different purposes. It is used for workstations and servers. Some EATX motherboards are also designed for desktop computing, and there is ample space for cooling and attaching peripherals. Now a dayβs the technology is getting advanced and you can find all those extra slots and power that you get in Standard ATX board in micro ATX board."
},
{
"code": null,
"e": 3179,
"s": 2544,
"text": "Standard ATX β This motherboard comes in 305*244mm (length*breadth) dimensions, these dimensions can vary with different manufacturer. This motherboard offers more expansion slots, up to four slots for RAM, Two or sometimes more than two PCIe slots for dual graphics cards and more USB and other ports for connectivity, also its size gives space in between components for airflow to keep heat in control. This size of motherboard is used by those who want more expansion slots and different connecting ports and deal with heavy workloads. This motherboard will only fit in cases which support full ATX or Extended ATX motherboards. "
},
{
"code": null,
"e": 3743,
"s": 3179,
"text": "Micro ATX β This motherboards come in 244*244 mm (length*breadth) dimensions (these dimensions can vary with different manufacturer.). This Motherboard has less ports and slots as compared to Standard ATX board. This type of motherboard is more suitable for those who donβt want to much connectivity and later upgrades like adding more ram and additional GPU or Graphics card and adding PCI cards. This board can fit any case which has enough room 244*244 mm of space and can also be fit in bigger cases which accept Standard ATX and eXTENDED ATX motherboards. "
},
{
"code": null,
"e": 4353,
"s": 3743,
"text": "eXtended ATX β This motherboard is 344*330 mm dimensions (these dimensions can vary with different manufacturer). This motherboard is designed for both dual CPU and single configuration and has up to 8 ram slots and has more PCIe and PCI slots for adding PCI cards for different purposes. It is used for workstations and servers. Some EATX motherboards are also designed for desktop computing, and there is ample space for cooling and attaching peripherals. Now a dayβs the technology is getting advanced and you can find all those extra slots and power that you get in Standard ATX board in micro ATX board."
},
{
"code": null,
"e": 4370,
"s": 4353,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4407,
"s": 4370,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 4505,
"s": 4407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4524,
"s": 4505,
"text": "Control Characters"
},
{
"code": null,
"e": 4586,
"s": 4524,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 4635,
"s": 4586,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 4730,
"s": 4635,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 4769,
"s": 4730,
"text": "Programmable peripheral interface 8255"
},
{
"code": null,
"e": 4805,
"s": 4769,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 4853,
"s": 4805,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 4891,
"s": 4853,
"text": "Write Through and Write Back in Cache"
},
{
"code": null,
"e": 4902,
"s": 4891,
"text": "Interrupts"
}
]
|
numpy.poly1d() in Python | 04 Dec, 2020
The numpy.poly1d() function helps to define a polynomial function. It makes it easy to apply βnatural operationsβ on polynomials.
Syntax: numpy.poly1d(arr, root, var)Parameters :arr : [array_like] The polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation.
root : [bool, optional] True means polynomial roots. Default is False.var : variable like x, y, z that we need in polynomial [default is x].
Arguments :c : Polynomial coefficient.coef : Polynomial coefficient.coefficients : Polynomial coefficient.order : Order or degree of polynomial.o : Order or degree of polynomial.r : Polynomial root.roots : Polynomial root.
Return: Polynomial and the operation applied
For example: poly1d(3, 2, 6) = 3x2 + 2x + 6poly1d([1, 2, 3], True) = (x-1)(x-2)(x-3) = x3 β 6x2 + 11x -6
Code 1 : Explaining poly1d() and its argument
# Python code explaining# numpy.poly1d() # importing librariesimport numpy as np # Constructing polynomialp1 = np.poly1d([1, 2])p2 = np.poly1d([4, 9, 5, 4]) print ("P1 : ", p1)print ("\n p2 : \n", p2) # Solve for x = 2print ("\n\np1 at x = 2 : ", p1(2))print ("p2 at x = 2 : ", p2(2)) # Finding Rootsprint ("\n\nRoots of P1 : ", p1.r)print ("Roots of P2 : ", p2.r) # Finding Coefficientsprint ("\n\nCoefficients of P1 : ", p1.c)print ("Coefficients of P2 : ", p2.coeffs) # Finding Orderprint ("\n\nOrder / Degree of P1 : ", p1.o)print ("Order / Degree of P2 : ", p2.order)
Output :
P1 :
1 x + 2
p2 :
3 2
4 x + 9 x + 5 x + 4
p1 at x = 2 : 4
p2 at x = 2 : 82
Roots of P1 : [-2.]
Roots of P2 : [-1.86738371+0.j -0.19130814+0.70633545j -0.19130814-0.70633545j]
Coefficients of P1 : [1 2]
Coefficients of P2 : [4 9 5 4]
Order / Degree of P1 : 1
Order / Degree of P2 : 3
Code 2 : Basic mathematical operation on polynomial
# Python code explaining# numpy.poly1d() # importing librariesimport numpy as np # Constructing polynomialp1 = np.poly1d([1, 2])p2 = np.poly1d([4, 9, 5, 4]) print ("P1 : ", p1)print ("\n p2 : \n", p2) print ("\n\np1 ^ 2 : \n", p1**2)print ("p2 ^ 2 : \n", np.square(p2)) p3 = np.poly1d([1, 2], variable = 'y')print ("\n\np3 : ", p3) print ("\n\np1 * p2 : \n", p1 * p2)print ("\nMultiplying two polynimials : \n", np.poly1d([1, -1]) * np.poly1d([1, -2]))
Output :
P1 :
1 x + 2
p2 :
3 2
4 x + 9 x + 5 x + 4
p1 ^ 2 :
2
1 x + 4 x + 4
p2 ^ 2 :
[16 81 25 16]
p3 :
1 y + 2
p1 * p2 :
4 3 2
4 x + 17 x + 23 x + 14 x + 8
Multiplying two polynimials :
2
1 x - 3 x + 2
Python numpy-polynomials
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "The numpy.poly1d() function helps to define a polynomial function. It makes it easy to apply βnatural operationsβ on polynomials."
},
{
"code": null,
"e": 400,
"s": 158,
"text": "Syntax: numpy.poly1d(arr, root, var)Parameters :arr : [array_like] The polynomial coefficients are given in decreasing order of powers. If the second parameter (root) is set to True then array values are the roots of the polynomial equation."
},
{
"code": null,
"e": 541,
"s": 400,
"text": "root : [bool, optional] True means polynomial roots. Default is False.var : variable like x, y, z that we need in polynomial [default is x]."
},
{
"code": null,
"e": 764,
"s": 541,
"text": "Arguments :c : Polynomial coefficient.coef : Polynomial coefficient.coefficients : Polynomial coefficient.order : Order or degree of polynomial.o : Order or degree of polynomial.r : Polynomial root.roots : Polynomial root."
},
{
"code": null,
"e": 809,
"s": 764,
"text": "Return: Polynomial and the operation applied"
},
{
"code": null,
"e": 914,
"s": 809,
"text": "For example: poly1d(3, 2, 6) = 3x2 + 2x + 6poly1d([1, 2, 3], True) = (x-1)(x-2)(x-3) = x3 β 6x2 + 11x -6"
},
{
"code": null,
"e": 960,
"s": 914,
"text": "Code 1 : Explaining poly1d() and its argument"
},
{
"code": "# Python code explaining# numpy.poly1d() # importing librariesimport numpy as np # Constructing polynomialp1 = np.poly1d([1, 2])p2 = np.poly1d([4, 9, 5, 4]) print (\"P1 : \", p1)print (\"\\n p2 : \\n\", p2) # Solve for x = 2print (\"\\n\\np1 at x = 2 : \", p1(2))print (\"p2 at x = 2 : \", p2(2)) # Finding Rootsprint (\"\\n\\nRoots of P1 : \", p1.r)print (\"Roots of P2 : \", p2.r) # Finding Coefficientsprint (\"\\n\\nCoefficients of P1 : \", p1.c)print (\"Coefficients of P2 : \", p2.coeffs) # Finding Orderprint (\"\\n\\nOrder / Degree of P1 : \", p1.o)print (\"Order / Degree of P2 : \", p2.order)",
"e": 1540,
"s": 960,
"text": null
},
{
"code": null,
"e": 1549,
"s": 1540,
"text": "Output :"
},
{
"code": null,
"e": 1870,
"s": 1549,
"text": "P1 : \n1 x + 2\n\n p2 : \n 3 2\n4 x + 9 x + 5 x + 4\n\n\np1 at x = 2 : 4\np2 at x = 2 : 82\n\n\nRoots of P1 : [-2.]\nRoots of P2 : [-1.86738371+0.j -0.19130814+0.70633545j -0.19130814-0.70633545j]\n\n\nCoefficients of P1 : [1 2]\nCoefficients of P2 : [4 9 5 4]\n\n\nOrder / Degree of P1 : 1\nOrder / Degree of P2 : 3"
},
{
"code": null,
"e": 1923,
"s": 1870,
"text": " Code 2 : Basic mathematical operation on polynomial"
},
{
"code": "# Python code explaining# numpy.poly1d() # importing librariesimport numpy as np # Constructing polynomialp1 = np.poly1d([1, 2])p2 = np.poly1d([4, 9, 5, 4]) print (\"P1 : \", p1)print (\"\\n p2 : \\n\", p2) print (\"\\n\\np1 ^ 2 : \\n\", p1**2)print (\"p2 ^ 2 : \\n\", np.square(p2)) p3 = np.poly1d([1, 2], variable = 'y')print (\"\\n\\np3 : \", p3) print (\"\\n\\np1 * p2 : \\n\", p1 * p2)print (\"\\nMultiplying two polynimials : \\n\", np.poly1d([1, -1]) * np.poly1d([1, -2]))",
"e": 2391,
"s": 1923,
"text": null
},
{
"code": null,
"e": 2400,
"s": 2391,
"text": "Output :"
},
{
"code": null,
"e": 2645,
"s": 2400,
"text": "P1 : \n1 x + 2\n\n p2 : \n 3 2\n4 x + 9 x + 5 x + 4\n\n\np1 ^ 2 : \n 2\n1 x + 4 x + 4\np2 ^ 2 : \n [16 81 25 16]\n\n\np3 : \n1 y + 2\n\n\np1 * p2 : \n 4 3 2\n4 x + 17 x + 23 x + 14 x + 8\n\nMultiplying two polynimials : \n 2\n1 x - 3 x + 2"
},
{
"code": null,
"e": 2670,
"s": 2645,
"text": "Python numpy-polynomials"
},
{
"code": null,
"e": 2683,
"s": 2670,
"text": "Python-numpy"
},
{
"code": null,
"e": 2690,
"s": 2683,
"text": "Python"
}
]
|
How i can replace number with string using Python? | For this purpose let us use a dictionary object having digit as key and its word representation as value β
dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',
'5':'five','6':'six','7':'seven','8':'eight','9':'nine'
Initializa a new string object
newstr=''
Using a for loop traverse each character ch from input string at check if it is a digit with the help of isdigit() function.
If it is digit, use it as key and find corresponding value from dictionary and append it to newstr. If not append the character ch itself to newstr. Complete code is as follows:
string='I have 3 Networking books, 0 Database books, and 8 Programming books.'
dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',
'5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
newstr=''
for ch in string:
if ch.isdigit()==True:
dw=dct[ch]
newstr=newstr+dw
else:
newstr=newstr+ch
print (newstr)
The output is as desired
I have three Networking books, zero Database books, and eight Programming books. | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "For this purpose let us use a dictionary object having digit as key and its word representation as value β"
},
{
"code": null,
"e": 1290,
"s": 1169,
"text": "dct={'0':'zero','1':'one','2':'two','3':'three','4':'four',\n '5':'five','6':'six','7':'seven','8':'eight','9':'nine'"
},
{
"code": null,
"e": 1322,
"s": 1290,
"text": "Initializa a new string object "
},
{
"code": null,
"e": 1332,
"s": 1322,
"text": "newstr=''"
},
{
"code": null,
"e": 1459,
"s": 1332,
"text": "Using a for loop traverse each character ch from input string at check if it is a digit with the help of isdigit() function. "
},
{
"code": null,
"e": 1637,
"s": 1459,
"text": "If it is digit, use it as key and find corresponding value from dictionary and append it to newstr. If not append the character ch itself to newstr. Complete code is as follows:"
},
{
"code": null,
"e": 1993,
"s": 1637,
"text": "string='I have 3 Networking books, 0 Database books, and 8 Programming books.'\ndct={'0':'zero','1':'one','2':'two','3':'three','4':'four',\n '5':'five','6':'six','7':'seven','8':'eight','9':'nine'}\nnewstr=''\nfor ch in string:\n if ch.isdigit()==True:\n dw=dct[ch]\n newstr=newstr+dw\n else:\n newstr=newstr+ch\nprint (newstr) "
},
{
"code": null,
"e": 2018,
"s": 1993,
"text": "The output is as desired"
},
{
"code": null,
"e": 2099,
"s": 2018,
"text": "I have three Networking books, zero Database books, and eight Programming books."
}
]
|
PySpark UDFs and star expansion. A simple hack to ensure that Spark... | by Schaun Wheeler | Towards Data Science | For the most part, I found my transition from primarily working in SQL to primarily working in Spark to be smooth. Being familiar with ORMs like SQLalchemy and Django, it wasnβt hard to adapt. Selects, filters, joins, groupbys and things like that all work more or less the way they do in SQL. I think thereβs a logic to structuring a data query, and that getting a feel for that logic is the hardest part of the battle β the rest is just implementation.
The difficult part of Spark, in my opinion, is resource management. Figuring out the right balance of cores, memory (both on heap and off heap), and executors is more art than science, and the error messages Spark gives you are often only minimally informative. And Iβve found very few good training materials for Spark. Maybe I was a little spoiled by coming from mostly using the PyData and SQL stack: when I have a question about Pandas or Postgres I Google it, which nearly always gets me some fairly complete documentation with working examples, often gets me a handful of informative blog posts, and usually gets me at least one helpful Stack Exchange question. When I have a question about Spark, I Google it, which more often than not gets me a documentation page that simply confirms that the method technically exists. And thatβs it.
Iβve found resource management to be particularly tricky when it comes to PySpark user-defined functions (UDFs). Python UDFs are a convenient and often necessary way to do data science in Spark, even though they are not as efficient as using built-in Spark functions or even Scala UDFs. When using a Python UDF, itβs important to understand how Spark evaluates it. Consider the following example, which assumes a Spark data frame `sdf` with two numeric columns `col1` and `col2`:
import pyspark.sql.functions as fimport pyspark.sql.types as tdef my_function(arg1, arg2): argsum = arg1 + arg2 argdiff = arg1 - arg2 argprod = arg1 * arg2 return argsum, argdiff, argprodschema = t.StructType([ t.StructField('sum', t.FloatType(), False), t.StructField('difference', t.FloatType(), False), t.StructField('product', t.FloatType(), False),])my_function_udf = f.udf(my_function, schema)results_sdf = ( sdf .select( my_function_udf( f.col('col1'), f.col('col2') ).alias('metrics')) # call the UDF .select(f.col('metrics.*')) # expand into separate columns)
If you call `results_sdf.explain()` after executing the above code block, you should see a line that reads something like this:
BatchEvalPython [my_function(col1#87, col2#88), my_function(col1#87, col2#88), my_function(col1#87, col2#88)]
That means that in order to do the star expansion on your metrics field, Spark will call your udf three times β once for each item in your schema. This means youβll be taking an already inefficient function and running it multiple times.
You can trick Spark into evaluating the UDF only once by making a small change to the code:
results_sdf = ( sdf .select( f.explode( f.array( my_function_udf(f.col('col1'), f.col('col2')) ) ).alias('metrics') ) .select(f.col('metrics.*')))
Wrapping the results in an array and then exploding that array incurs some expense, but that expense is trivial compared to the resources saved by evaluating the UDF only once:
BatchEvalPython [my_function(col1#87, col2#88)]
You can achieve the same results by persisting or checkpointing the dataframe before doing star expansion, but that uses up memory and disk space, which you might not want to do. | [
{
"code": null,
"e": 627,
"s": 172,
"text": "For the most part, I found my transition from primarily working in SQL to primarily working in Spark to be smooth. Being familiar with ORMs like SQLalchemy and Django, it wasnβt hard to adapt. Selects, filters, joins, groupbys and things like that all work more or less the way they do in SQL. I think thereβs a logic to structuring a data query, and that getting a feel for that logic is the hardest part of the battle β the rest is just implementation."
},
{
"code": null,
"e": 1471,
"s": 627,
"text": "The difficult part of Spark, in my opinion, is resource management. Figuring out the right balance of cores, memory (both on heap and off heap), and executors is more art than science, and the error messages Spark gives you are often only minimally informative. And Iβve found very few good training materials for Spark. Maybe I was a little spoiled by coming from mostly using the PyData and SQL stack: when I have a question about Pandas or Postgres I Google it, which nearly always gets me some fairly complete documentation with working examples, often gets me a handful of informative blog posts, and usually gets me at least one helpful Stack Exchange question. When I have a question about Spark, I Google it, which more often than not gets me a documentation page that simply confirms that the method technically exists. And thatβs it."
},
{
"code": null,
"e": 1951,
"s": 1471,
"text": "Iβve found resource management to be particularly tricky when it comes to PySpark user-defined functions (UDFs). Python UDFs are a convenient and often necessary way to do data science in Spark, even though they are not as efficient as using built-in Spark functions or even Scala UDFs. When using a Python UDF, itβs important to understand how Spark evaluates it. Consider the following example, which assumes a Spark data frame `sdf` with two numeric columns `col1` and `col2`:"
},
{
"code": null,
"e": 2577,
"s": 1951,
"text": "import pyspark.sql.functions as fimport pyspark.sql.types as tdef my_function(arg1, arg2): argsum = arg1 + arg2 argdiff = arg1 - arg2 argprod = arg1 * arg2 return argsum, argdiff, argprodschema = t.StructType([ t.StructField('sum', t.FloatType(), False), t.StructField('difference', t.FloatType(), False), t.StructField('product', t.FloatType(), False),])my_function_udf = f.udf(my_function, schema)results_sdf = ( sdf .select( my_function_udf( f.col('col1'), f.col('col2') ).alias('metrics')) # call the UDF .select(f.col('metrics.*')) # expand into separate columns)"
},
{
"code": null,
"e": 2705,
"s": 2577,
"text": "If you call `results_sdf.explain()` after executing the above code block, you should see a line that reads something like this:"
},
{
"code": null,
"e": 2815,
"s": 2705,
"text": "BatchEvalPython [my_function(col1#87, col2#88), my_function(col1#87, col2#88), my_function(col1#87, col2#88)]"
},
{
"code": null,
"e": 3053,
"s": 2815,
"text": "That means that in order to do the star expansion on your metrics field, Spark will call your udf three times β once for each item in your schema. This means youβll be taking an already inefficient function and running it multiple times."
},
{
"code": null,
"e": 3145,
"s": 3053,
"text": "You can trick Spark into evaluating the UDF only once by making a small change to the code:"
},
{
"code": null,
"e": 3355,
"s": 3145,
"text": "results_sdf = ( sdf .select( f.explode( f.array( my_function_udf(f.col('col1'), f.col('col2')) ) ).alias('metrics') ) .select(f.col('metrics.*')))"
},
{
"code": null,
"e": 3532,
"s": 3355,
"text": "Wrapping the results in an array and then exploding that array incurs some expense, but that expense is trivial compared to the resources saved by evaluating the UDF only once:"
},
{
"code": null,
"e": 3580,
"s": 3532,
"text": "BatchEvalPython [my_function(col1#87, col2#88)]"
}
]
|
PHP - Introduction | PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
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.
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.
It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time.
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time.
PHP is forgiving: PHP language tries to be as forgiving as possible.
PHP is forgiving: PHP language tries to be as forgiving as possible.
PHP Syntax is C-Like.
PHP Syntax is C-Like.
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, through 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, through email you can send data, return data to the user.
You add, delete, modify elements within your database through PHP.
You add, delete, modify elements within your database through 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.
Five important characteristics make PHP's practical nature possible β
Simplicity
Efficiency
Security
Flexibility
Familiarity
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential example, first we will create a friendly little "Hello, World!" script.
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this β
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result β
Hello, World!
If you examine the HTML output of the above example, you'll notice that the PHP code is not present in the file sent from the server to your Web browser. All of the PHP present in the Web page is processed and stripped from the page; the only thing returned to the client from the Web server is pure HTML output.
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>
A most common tag is the <?php...?> and we will also use the same tag in our tutorial.
From the next chapter we will start with PHP Environment Setup on your machine and then we will dig out almost all concepts related to PHP to make you comfortable with the PHP language.
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": 2938,
"s": 2757,
"text": "PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994."
},
{
"code": null,
"e": 3000,
"s": 2938,
"text": "PHP is a recursive acronym for \"PHP: Hypertext Preprocessor\"."
},
{
"code": null,
"e": 3062,
"s": 3000,
"text": "PHP is a recursive acronym for \"PHP: Hypertext Preprocessor\"."
},
{
"code": null,
"e": 3231,
"s": 3062,
"text": "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": 3400,
"s": 3231,
"text": "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": 3534,
"s": 3400,
"text": "It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server."
},
{
"code": null,
"e": 3668,
"s": 3534,
"text": "It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server."
},
{
"code": null,
"e": 3886,
"s": 3668,
"text": "PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time."
},
{
"code": null,
"e": 4104,
"s": 3886,
"text": "PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix side. The MySQL server, once started, executes even very complex queries with huge result sets in record-setting time."
},
{
"code": null,
"e": 4323,
"s": 4104,
"text": "PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time."
},
{
"code": null,
"e": 4542,
"s": 4323,
"text": "PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time."
},
{
"code": null,
"e": 4611,
"s": 4542,
"text": "PHP is forgiving: PHP language tries to be as forgiving as possible."
},
{
"code": null,
"e": 4680,
"s": 4611,
"text": "PHP is forgiving: PHP language tries to be as forgiving as possible."
},
{
"code": null,
"e": 4702,
"s": 4680,
"text": "PHP Syntax is C-Like."
},
{
"code": null,
"e": 4724,
"s": 4702,
"text": "PHP Syntax is C-Like."
},
{
"code": null,
"e": 4833,
"s": 4724,
"text": "PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them."
},
{
"code": null,
"e": 4942,
"s": 4833,
"text": "PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them."
},
{
"code": null,
"e": 5072,
"s": 4942,
"text": "PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user."
},
{
"code": null,
"e": 5202,
"s": 5072,
"text": "PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user."
},
{
"code": null,
"e": 5269,
"s": 5202,
"text": "You add, delete, modify elements within your database through PHP."
},
{
"code": null,
"e": 5336,
"s": 5269,
"text": "You add, delete, modify elements within your database through PHP."
},
{
"code": null,
"e": 5378,
"s": 5336,
"text": "Access cookies variables and set cookies."
},
{
"code": null,
"e": 5420,
"s": 5378,
"text": "Access cookies variables and set cookies."
},
{
"code": null,
"e": 5492,
"s": 5420,
"text": "Using PHP, you can restrict users to access some pages of your website."
},
{
"code": null,
"e": 5564,
"s": 5492,
"text": "Using PHP, you can restrict users to access some pages of your website."
},
{
"code": null,
"e": 5585,
"s": 5564,
"text": "It can encrypt data."
},
{
"code": null,
"e": 5606,
"s": 5585,
"text": "It can encrypt data."
},
{
"code": null,
"e": 5676,
"s": 5606,
"text": "Five important characteristics make PHP's practical nature possible β"
},
{
"code": null,
"e": 5687,
"s": 5676,
"text": "Simplicity"
},
{
"code": null,
"e": 5698,
"s": 5687,
"text": "Efficiency"
},
{
"code": null,
"e": 5707,
"s": 5698,
"text": "Security"
},
{
"code": null,
"e": 5719,
"s": 5707,
"text": "Flexibility"
},
{
"code": null,
"e": 5731,
"s": 5719,
"text": "Familiarity"
},
{
"code": null,
"e": 5901,
"s": 5731,
"text": "To get a feel for PHP, first start with simple PHP scripts. Since \"Hello, World!\" is an essential example, first we will create a friendly little \"Hello, World!\" script."
},
{
"code": null,
"e": 6066,
"s": 5901,
"text": "As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this β"
},
{
"code": null,
"e": 6201,
"s": 6066,
"text": "<html>\n \n <head>\n <title>Hello World</title>\n </head>\n \n <body>\n <?php echo \"Hello, World!\";?>\n </body>\n\n</html>"
},
{
"code": null,
"e": 6236,
"s": 6201,
"text": "It will produce following result β"
},
{
"code": null,
"e": 6251,
"s": 6236,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 6564,
"s": 6251,
"text": "If you examine the HTML output of the above example, you'll notice that the PHP code is not present in the file sent from the server to your Web browser. All of the PHP present in the Web page is processed and stripped from the page; the only thing returned to the client from the Web server is pure HTML output."
},
{
"code": null,
"e": 6676,
"s": 6564,
"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": 6789,
"s": 6676,
"text": "<?php PHP code goes here ?>\n\n<? PHP code goes here ?>\n\n<script language = \"php\"> PHP code goes here </script>"
},
{
"code": null,
"e": 6876,
"s": 6789,
"text": "A most common tag is the <?php...?> and we will also use the same tag in our tutorial."
},
{
"code": null,
"e": 7063,
"s": 6876,
"text": "From the next chapter we will start with PHP Environment Setup on your machine and then we will dig out almost all concepts related to PHP to make you comfortable with the PHP language."
},
{
"code": null,
"e": 7096,
"s": 7063,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7112,
"s": 7096,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7145,
"s": 7112,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7156,
"s": 7145,
"text": " Syed Raza"
},
{
"code": null,
"e": 7191,
"s": 7156,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7208,
"s": 7191,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7241,
"s": 7208,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7256,
"s": 7241,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 7291,
"s": 7256,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 7303,
"s": 7291,
"text": " Azaz Patel"
},
{
"code": null,
"e": 7338,
"s": 7303,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7366,
"s": 7338,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 7373,
"s": 7366,
"text": " Print"
},
{
"code": null,
"e": 7384,
"s": 7373,
"text": " Add Notes"
}
]
|
How to use APIs to get spatial features for your models | by Philipp Spachtholz | Towards Data Science | In this post, I would like to show you how you can use APIs to quickly obtain many features for your spatial datasets to build better data science models.
On my own way to becoming a data scientist and subsequently in my work as a data scientist I built several models based on spatial data, e.g. to predict house prices, or more recently to predict the expected usage of charging stations for electric vehicles. What I quickly found out was that these models performance (at least for smaller datasets) doesnβt profit as much from models complexity or extensive parameter search but instead from the availability of good spatial features.
I also realized that extracting these spatial features can be quite cumbersome: You need to identify and evaluate data sources, set up a new set of tools like a PostGIS database, OpenStreetMap tools (like Overpass, Nominatim, etc.), and learn a lot of new things like map projections, spatial indexing, specific query languages and so on slowing down your feature extraction a lot.
However, there is also an easier and quicker way to get your set of spatial features: Using an API that handles all these tasks, so you donβt have to.
If you are just starting to get into data science or donβt come from a computer scientist educational background APIs may appear intimidating at first (with specialized terms as resources, endpoints, basic authentication, etc.). They did for me, at least, which to some degree prevented me from using them.
However, by learning more about APIs in general and playing around with APIs offering free accounts, you will quickly become familiar with using APIs and be able to integrate them as a new useful resource into your modelling workflow. As most APIs are built in a similar way (which is one reason that makes them so popular), knowing how to use one will help you understand how others work, too.
I am currently building a new API at features4.com (which is now publicly open for testing) which provides free and easy access to a rich set of spatial features such as the number of restaurants in a radius of 500m or the distance to the nearest doctors). I will use the Features4 API as an example on how to use APIs.
So how do we use the Featurees4 API to obtain your spatial features?
The birds eye view
From a birds eye view using an API is much like calling a normal function. You need the function name, you pass parameters to it and you get back a result. Thatβs basically the same with an API (only with different names): You need a URL, send it some data to it and get back a response.
URL
The most important difference is that while your functions are hosted on your computer, APIs are hosted on web servers. Consequently the API βfunction nameβ will always contain an address where it is located, which usually is an URL (just as you would type in a browser to retrieve a website). For example, all URLs for the features4 API start with https://api.features4.com/v1, because this is where the API can be reached on the server. The number βfunctionβ for example is located at https://api.features4.com/v1/number.
Passing parameters
Once you know the URL you need to specify the arguments you want to send it to. How would you find out which parameters a function takes? You would just take a look at its documentation. With APIs you do the same: In order to know which parameters an API endpoint takes you take a look at the API reference. In such a reference youβll usually find all information about the parameters, including their types, descriptions and allowed values.
One thing I did not mention yet is that APIs, in general, are more flexible than the typical function. Often times you can send your parameter values in different ways. One way youβll find often is to pass them in the following form (so-called form urlencoded as you can append them to the URL like this):
param1=value¶m2=300¶m4=true
Another common way to specify the parameters is by sending them JSON encoded:
The good thing about JSON is that it supports both nesting parameters and different data types, such as strings, numbers and lists:
Method
There is one piece of information you need to give the API: The request method tells the server what kind of action you want the server to take. This again makes APIs more flexible, so that the same URL can serve multiple different responses. For example, GET indicates that an item should be fetched or POST means that data is pushed to the server (creating a resource, or generating a temporary document to send back).
The method also tells the server where to look for the parameters you passed. While with the GET method you append the parameter values to the URL, with the POST method parameter values will be sent as part of the request.
As with passing parameters the API documentation will let you know exactly what methods the server accepts and what response it will give you as a result. The Features4 API currently only uses the POST method for consistency and simplicity so that all calls to the API can be made the same way.
Response
APIs are very reliable. Unless their web server cannot be reached, they will always return you a response, whether your request succeeded or failed. To let you know whether all went well or if something went wrong it will send you back a 3 digit number (e.g. 200) the so called status code. Each status code has a specific meaning and there is a large list of status codes with standardized meaning. No worries you donβt have to memorize all of them, or the beginning just remember this:
If the status code starts with:
2 everything is good
4 you probably made a mistake (such as omitting a parameter)
5 the API made an error (so, not much you can do about it)
If everything worked well and you received a response with a status code of 200, you will also receive the data you asked the API for. For example, the Features4 API would return you the spatial feature you asked for, such as the number of restaurants within a radius of 500m. The format of the response depends on the API, but oftentimes youβll receive it formatted as JSON, which you already know from passing the parameters:
If you receive a response with a status code starting with 4, meaning that something went wrong on your side, a good API will tell you more about the type of error you made, for you to be able to fix it quickly. For instance, if you omit a parameter named βradiusβ the Features4 API will tell you what went wrong:
So, this was a very brief introduction into how APIs work in general. There is a lot more to learn about it and the HTTP protocol in general and a good source of information is provided by Mozilla for example.
Let's move on to a concrete example on how to use the Features4 API to retrieve spatial features for a location. We will use Python as a language but basically all languages provide libraries for making requests to APIs.
Letβs say you are building a model to predict house prices and you think that centrality will be an important aspect of it. Assuming that bars and restaurants are located at higher densities in central parts of a city, you are interested in getting the number of restaurants in a radius of 500m around a given location.
Getting access
Almost all APIs require you to provide some credentials to access it, such as a username and password. Features4 allows you both to try out the API with a test username API_TEST_KEY and no password or your private API key after registration for a free account (including more features).
Getting your first feature
The first thing to do is to find out the URL, method and parameters for the feature Number of elements in Radius in the API Reference:
You can find the URL and method in the upper right corner, which says that you should use the POST method to the /number URL. Clicking on the URL will reveal the full URL https://api.features4.com/v1/number.
In the central part of the documentation you see all the parameters the API takes for this feature, which are:
lat: Latitude of the location
lng: Longitude of the location
element: The map element you are interested in (e.g. restaurant)
radius: The radius around the location in meters (e.g. 500)
To get latitude and longitude for a location you can, for example, use this website.
Once you have the URL, method, credentials and the parameters you can use the requests library to retrieve the feature. For your convenience, the API reference provides code samples in different languages you can just copy and paste to have the basic structure and then you just change the parameters as you wish. So in the example just replace bar with restaurant.
Great: You can see that the number of restaurants in a radius of 500 meters of a location (the city center of Munich) is 153.
Similarly, you can retrieve another feature: the distance to the nearest map element. For house prices, the distance to the nearest kindergarten might, for example, be of interest. The procedure to get this feature is the same as before:
Take a look at the appropriate section in the API Reference
Identify these pieces of information: URL /distance, method POST, and parameters lat, lng, element
Make the request
You have learned some basics of how to use an API to retrieve spatial features for your data science models using the new Features4 API.
Feel free to explore the API Reference for more features or have a look at the Documentation to see which map elements are available for the features.
Having knowledge of APIs will help you a lot as a data scientist, because for many things you donβt have to reinvent the wheel, but instead can use the work others have already done for you. Therefore leveraging an existing API will let you be productive a lot more quickly.
I hope this article helped you getting started using APIs. | [
{
"code": null,
"e": 327,
"s": 172,
"text": "In this post, I would like to show you how you can use APIs to quickly obtain many features for your spatial datasets to build better data science models."
},
{
"code": null,
"e": 812,
"s": 327,
"text": "On my own way to becoming a data scientist and subsequently in my work as a data scientist I built several models based on spatial data, e.g. to predict house prices, or more recently to predict the expected usage of charging stations for electric vehicles. What I quickly found out was that these models performance (at least for smaller datasets) doesnβt profit as much from models complexity or extensive parameter search but instead from the availability of good spatial features."
},
{
"code": null,
"e": 1194,
"s": 812,
"text": "I also realized that extracting these spatial features can be quite cumbersome: You need to identify and evaluate data sources, set up a new set of tools like a PostGIS database, OpenStreetMap tools (like Overpass, Nominatim, etc.), and learn a lot of new things like map projections, spatial indexing, specific query languages and so on slowing down your feature extraction a lot."
},
{
"code": null,
"e": 1345,
"s": 1194,
"text": "However, there is also an easier and quicker way to get your set of spatial features: Using an API that handles all these tasks, so you donβt have to."
},
{
"code": null,
"e": 1652,
"s": 1345,
"text": "If you are just starting to get into data science or donβt come from a computer scientist educational background APIs may appear intimidating at first (with specialized terms as resources, endpoints, basic authentication, etc.). They did for me, at least, which to some degree prevented me from using them."
},
{
"code": null,
"e": 2047,
"s": 1652,
"text": "However, by learning more about APIs in general and playing around with APIs offering free accounts, you will quickly become familiar with using APIs and be able to integrate them as a new useful resource into your modelling workflow. As most APIs are built in a similar way (which is one reason that makes them so popular), knowing how to use one will help you understand how others work, too."
},
{
"code": null,
"e": 2367,
"s": 2047,
"text": "I am currently building a new API at features4.com (which is now publicly open for testing) which provides free and easy access to a rich set of spatial features such as the number of restaurants in a radius of 500m or the distance to the nearest doctors). I will use the Features4 API as an example on how to use APIs."
},
{
"code": null,
"e": 2436,
"s": 2367,
"text": "So how do we use the Featurees4 API to obtain your spatial features?"
},
{
"code": null,
"e": 2455,
"s": 2436,
"text": "The birds eye view"
},
{
"code": null,
"e": 2743,
"s": 2455,
"text": "From a birds eye view using an API is much like calling a normal function. You need the function name, you pass parameters to it and you get back a result. Thatβs basically the same with an API (only with different names): You need a URL, send it some data to it and get back a response."
},
{
"code": null,
"e": 2747,
"s": 2743,
"text": "URL"
},
{
"code": null,
"e": 3271,
"s": 2747,
"text": "The most important difference is that while your functions are hosted on your computer, APIs are hosted on web servers. Consequently the API βfunction nameβ will always contain an address where it is located, which usually is an URL (just as you would type in a browser to retrieve a website). For example, all URLs for the features4 API start with https://api.features4.com/v1, because this is where the API can be reached on the server. The number βfunctionβ for example is located at https://api.features4.com/v1/number."
},
{
"code": null,
"e": 3290,
"s": 3271,
"text": "Passing parameters"
},
{
"code": null,
"e": 3732,
"s": 3290,
"text": "Once you know the URL you need to specify the arguments you want to send it to. How would you find out which parameters a function takes? You would just take a look at its documentation. With APIs you do the same: In order to know which parameters an API endpoint takes you take a look at the API reference. In such a reference youβll usually find all information about the parameters, including their types, descriptions and allowed values."
},
{
"code": null,
"e": 4038,
"s": 3732,
"text": "One thing I did not mention yet is that APIs, in general, are more flexible than the typical function. Often times you can send your parameter values in different ways. One way youβll find often is to pass them in the following form (so-called form urlencoded as you can append them to the URL like this):"
},
{
"code": null,
"e": 4074,
"s": 4038,
"text": "param1=value¶m2=300¶m4=true"
},
{
"code": null,
"e": 4152,
"s": 4074,
"text": "Another common way to specify the parameters is by sending them JSON encoded:"
},
{
"code": null,
"e": 4284,
"s": 4152,
"text": "The good thing about JSON is that it supports both nesting parameters and different data types, such as strings, numbers and lists:"
},
{
"code": null,
"e": 4291,
"s": 4284,
"text": "Method"
},
{
"code": null,
"e": 4712,
"s": 4291,
"text": "There is one piece of information you need to give the API: The request method tells the server what kind of action you want the server to take. This again makes APIs more flexible, so that the same URL can serve multiple different responses. For example, GET indicates that an item should be fetched or POST means that data is pushed to the server (creating a resource, or generating a temporary document to send back)."
},
{
"code": null,
"e": 4935,
"s": 4712,
"text": "The method also tells the server where to look for the parameters you passed. While with the GET method you append the parameter values to the URL, with the POST method parameter values will be sent as part of the request."
},
{
"code": null,
"e": 5230,
"s": 4935,
"text": "As with passing parameters the API documentation will let you know exactly what methods the server accepts and what response it will give you as a result. The Features4 API currently only uses the POST method for consistency and simplicity so that all calls to the API can be made the same way."
},
{
"code": null,
"e": 5239,
"s": 5230,
"text": "Response"
},
{
"code": null,
"e": 5727,
"s": 5239,
"text": "APIs are very reliable. Unless their web server cannot be reached, they will always return you a response, whether your request succeeded or failed. To let you know whether all went well or if something went wrong it will send you back a 3 digit number (e.g. 200) the so called status code. Each status code has a specific meaning and there is a large list of status codes with standardized meaning. No worries you donβt have to memorize all of them, or the beginning just remember this:"
},
{
"code": null,
"e": 5759,
"s": 5727,
"text": "If the status code starts with:"
},
{
"code": null,
"e": 5780,
"s": 5759,
"text": "2 everything is good"
},
{
"code": null,
"e": 5841,
"s": 5780,
"text": "4 you probably made a mistake (such as omitting a parameter)"
},
{
"code": null,
"e": 5900,
"s": 5841,
"text": "5 the API made an error (so, not much you can do about it)"
},
{
"code": null,
"e": 6328,
"s": 5900,
"text": "If everything worked well and you received a response with a status code of 200, you will also receive the data you asked the API for. For example, the Features4 API would return you the spatial feature you asked for, such as the number of restaurants within a radius of 500m. The format of the response depends on the API, but oftentimes youβll receive it formatted as JSON, which you already know from passing the parameters:"
},
{
"code": null,
"e": 6642,
"s": 6328,
"text": "If you receive a response with a status code starting with 4, meaning that something went wrong on your side, a good API will tell you more about the type of error you made, for you to be able to fix it quickly. For instance, if you omit a parameter named βradiusβ the Features4 API will tell you what went wrong:"
},
{
"code": null,
"e": 6852,
"s": 6642,
"text": "So, this was a very brief introduction into how APIs work in general. There is a lot more to learn about it and the HTTP protocol in general and a good source of information is provided by Mozilla for example."
},
{
"code": null,
"e": 7073,
"s": 6852,
"text": "Let's move on to a concrete example on how to use the Features4 API to retrieve spatial features for a location. We will use Python as a language but basically all languages provide libraries for making requests to APIs."
},
{
"code": null,
"e": 7393,
"s": 7073,
"text": "Letβs say you are building a model to predict house prices and you think that centrality will be an important aspect of it. Assuming that bars and restaurants are located at higher densities in central parts of a city, you are interested in getting the number of restaurants in a radius of 500m around a given location."
},
{
"code": null,
"e": 7408,
"s": 7393,
"text": "Getting access"
},
{
"code": null,
"e": 7695,
"s": 7408,
"text": "Almost all APIs require you to provide some credentials to access it, such as a username and password. Features4 allows you both to try out the API with a test username API_TEST_KEY and no password or your private API key after registration for a free account (including more features)."
},
{
"code": null,
"e": 7722,
"s": 7695,
"text": "Getting your first feature"
},
{
"code": null,
"e": 7857,
"s": 7722,
"text": "The first thing to do is to find out the URL, method and parameters for the feature Number of elements in Radius in the API Reference:"
},
{
"code": null,
"e": 8065,
"s": 7857,
"text": "You can find the URL and method in the upper right corner, which says that you should use the POST method to the /number URL. Clicking on the URL will reveal the full URL https://api.features4.com/v1/number."
},
{
"code": null,
"e": 8176,
"s": 8065,
"text": "In the central part of the documentation you see all the parameters the API takes for this feature, which are:"
},
{
"code": null,
"e": 8206,
"s": 8176,
"text": "lat: Latitude of the location"
},
{
"code": null,
"e": 8237,
"s": 8206,
"text": "lng: Longitude of the location"
},
{
"code": null,
"e": 8302,
"s": 8237,
"text": "element: The map element you are interested in (e.g. restaurant)"
},
{
"code": null,
"e": 8362,
"s": 8302,
"text": "radius: The radius around the location in meters (e.g. 500)"
},
{
"code": null,
"e": 8447,
"s": 8362,
"text": "To get latitude and longitude for a location you can, for example, use this website."
},
{
"code": null,
"e": 8813,
"s": 8447,
"text": "Once you have the URL, method, credentials and the parameters you can use the requests library to retrieve the feature. For your convenience, the API reference provides code samples in different languages you can just copy and paste to have the basic structure and then you just change the parameters as you wish. So in the example just replace bar with restaurant."
},
{
"code": null,
"e": 8939,
"s": 8813,
"text": "Great: You can see that the number of restaurants in a radius of 500 meters of a location (the city center of Munich) is 153."
},
{
"code": null,
"e": 9177,
"s": 8939,
"text": "Similarly, you can retrieve another feature: the distance to the nearest map element. For house prices, the distance to the nearest kindergarten might, for example, be of interest. The procedure to get this feature is the same as before:"
},
{
"code": null,
"e": 9237,
"s": 9177,
"text": "Take a look at the appropriate section in the API Reference"
},
{
"code": null,
"e": 9336,
"s": 9237,
"text": "Identify these pieces of information: URL /distance, method POST, and parameters lat, lng, element"
},
{
"code": null,
"e": 9353,
"s": 9336,
"text": "Make the request"
},
{
"code": null,
"e": 9490,
"s": 9353,
"text": "You have learned some basics of how to use an API to retrieve spatial features for your data science models using the new Features4 API."
},
{
"code": null,
"e": 9641,
"s": 9490,
"text": "Feel free to explore the API Reference for more features or have a look at the Documentation to see which map elements are available for the features."
},
{
"code": null,
"e": 9916,
"s": 9641,
"text": "Having knowledge of APIs will help you a lot as a data scientist, because for many things you donβt have to reinvent the wheel, but instead can use the work others have already done for you. Therefore leveraging an existing API will let you be productive a lot more quickly."
}
]
|
Java Type Casting | Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type
to a larger type size
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type
to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Widening casting is done automatically when passing a smaller size type to a
larger size type:
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Try it Yourself Β»
Narrowing casting must be done manually by placing the type in parentheses
in front of the value:
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
Try it Yourself Β»
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:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 84,
"s": 0,
"text": "Type casting is when you assign a value of one primitive data type to another type."
},
{
"code": null,
"e": 125,
"s": 84,
"text": "In Java, there are two types of casting:"
},
{
"code": null,
"e": 266,
"s": 125,
"text": "Widening Casting (automatically) - converting a smaller type \nto a larger type size\nbyte -> short -> char -> int -> long -> float -> double\n"
},
{
"code": null,
"e": 403,
"s": 266,
"text": "Narrowing Casting (manually) - converting a larger type \nto a smaller size type\ndouble -> float -> long -> int -> char -> short -> byte\n"
},
{
"code": null,
"e": 499,
"s": 403,
"text": "Widening casting is done automatically when passing a smaller size type to a \nlarger size type:"
},
{
"code": null,
"e": 754,
"s": 499,
"text": "public class Main {\n public static void main(String[] args) {\n int myInt = 9;\n double myDouble = myInt; // Automatic casting: int to double\n\n System.out.println(myInt); // Outputs 9\n System.out.println(myDouble); // Outputs 9.0\n }\n}\n"
},
{
"code": null,
"e": 774,
"s": 754,
"text": "\nTry it Yourself Β»\n"
},
{
"code": null,
"e": 873,
"s": 774,
"text": "Narrowing casting must be done manually by placing the type in parentheses \nin front of the value:"
},
{
"code": null,
"e": 1139,
"s": 873,
"text": "public class Main {\n public static void main(String[] args) {\n double myDouble = 9.78d;\n int myInt = (int) myDouble; // Manual casting: double to int\n\n System.out.println(myDouble); // Outputs 9.78\n System.out.println(myInt); // Outputs 9\n }\n}\n"
},
{
"code": null,
"e": 1159,
"s": 1139,
"text": "\nTry it Yourself Β»\n"
},
{
"code": null,
"e": 1192,
"s": 1159,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1234,
"s": 1192,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1341,
"s": 1234,
"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": 1360,
"s": 1341,
"text": "[email protected]"
}
]
|
From Text to Knowledge: The Information Extraction Pipeline | by Tomaz Bratanic | Towards Data Science | I am thrilled to present my latest project I have been working on. If you have been following my posts, you know that I am passionate about combining natural language processing and knowledge graphs. In this blog post, I will present my implementation of an information extraction data pipeline. Later on, I will also explain why I see the combination of NLP and graphs as one of the paths to explainable AI.
What exactly is an information extraction pipeline? To put it in simple terms, information extraction is the task of extracting structured information from unstructured data such as text.
My implementation of the information extraction pipeline consists of four parts. In the first step, we run the input text through a coreference resolution model. The coreference resolution is the task of finding all expressions that refer to a specific entity. To put it simply, it links all the pronouns to the referred entity. Once that step is finished, it splits the text into sentences and removes the punctuations. I have noticed that the specific ML model used for named entity linking works better when we first remove the punctuations. In the named entity linking part of the pipeline, we try to extract all the mentioned entities and connect them to a target knowledge base. The target knowledge base, in this case, is Wikipedia. Named entity linking is beneficial because it also deals with entity disambiguation, which can be a big problem.
Once we have extracted the mentioned entities, the IE pipeline tries to infer relationships between entities that make sense based on the textβs context. The IE pipeline results are entities and their relationships, so it makes sense to use a graph database to store the output. I will show how to save the IE information to Neo4j.
Iβll use the following excerpt from Wikipedia to walk you through the IE pipeline.
Elon Musk is a business magnate, industrial designer, and engineer. He is the founder, CEO, CTO, and chief designer of SpaceX. He is also early investor, CEO, and product architect of Tesla, Inc. He is also the founder of The Boring Company and the co-founder of Neuralink. A centibillionaire, Musk became the richest person in the world in January 2021, with an estimated net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother and South African father and raised in Pretoria, South Africa. He briefly attended the University of Pretoria before moving to Canada aged 17 to attend Queen's University. He transferred to the University of Pennsylvania two years later, where he received dual bachelor's degrees in economics and physics. He moved to California in 1995 to attend Stanford University, but decided instead to pursue a business career. He went on co-founding a web software company Zip2 with his brother Kimbal Musk.
Text is copied from https://en.wikipedia.org/wiki/Elon_Musk and is available under CC BY-SA 3.0 license.
As mentioned, the coreference resolution tries to find all expressions in the text that refer to a specific entity. In my implementation, I have used the Neuralcoref model from Huggingface that runs on top of the SpaCy framework. I have used the default parameters of the Neuralcoref model. One thing I did notice along the way is that the Neuralcoref model doesnβt work well with location pronouns. I have also borrowed a small improvement code from one of the GitHub issues. The code for the coreference resolution part is the following:
If we run our example text through the coref_resolution function, weβll get the following output:
Elon Musk is a business magnate, industrial designer, and engineer. Elon Musk is the founder, CEO, CTO, and chief designer of SpaceX. Elon Musk is also early investor, CEO, and product architect of Tesla, Inc. Elon Musk is also the founder of The Boring Company and the co-founder of Neuralink. A centibillionaire, Musk became the richest person in the world in January 2021, with an estimated net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother and South African father and raised in Pretoria, South Africa. Elon Musk briefly attended the University of Pretoria before moving to Canada aged 17 to attend Queen's University. Elon Musk transferred to the University of Pennsylvania two years later, where Elon Musk received dual bachelor's degrees in economics and physics. Elon Musk moved to California in 1995 to attend Stanford University, but decided instead to pursue a business career. Elon Musk went on co-founding a web software company Zip2 with Elon Musk brother Kimbal Musk.
In this example, there are no advanced coreference resolution techniques required. The Neuralcoref model changed a couple of pronouns βHeβ to βElon Muskβ. While it might seem very simple, this is an important step that will increase the overall efficiency of our IE pipeline.
Just recently, I have published a blog post using Named Entity Linking to construct a knowledge graph. Here, I wanted to use a different named entity linking model. I first tried to use the Facebook BLINK model, but I quickly realized it wouldnβt work on my laptop. It needs at least 50GB of free space, which is not a big problem per se, but it also requires 32GB of RAM. My laptop has only 16GB of RAM, and we still need other parts of the pipeline to work. So I reverted to use the good old Wikifier API, which has already shown to be useful. And itβs totally free. If you want to find more information about the API, look at my previous blog post or the official documentation.
Before we run our input text through the Wikifier API, we will split the text into sentences and remove the punctuations. Overall, the code for this step is as follows:
I forgot to mention that the Wikifier API returns all the classes that an entity belongs to. It looks at the INSTANCE_OF and SUBCLASS_OF classes and traverses all the way through the class hierarchy. I decided to filter out entities with categories that would belong to a person, organization, or location. If we run our example text through the Named Entity Linking part of the pipeline, we will get the following output.
A nice thing about the wikification process is that we also get the corresponding WikiData ids for entities along with their titles. Having the WikiData ids takes care of the entity disambiguation problem. You might wonder then what happens if an entity does not exist on Wikipedia. In that case, unfortunately, the Wikifier will not recognize it. I wouldnβt worry too much about it, though, as Wikipedia has more than 100 million entities if I recall correctly.
If you look closely at the results, youβll notice that Pretoria is wrongly classified as an Organization. I tried to solve this issue, but the Wikipedia class hierarchy is complicated and usually spans five or six hops. If there are some Wiki class experts out there, I will happily listen to your advice.
I have already presented all of the concepts until this point. I have never delved into relationship extraction before. So far, we have only played around with co-occurrence networks. So, I am excited to present a working relationship extraction process. I spend a lot of time searching for any open-source models that might do a decent job. I was delighted to stumble upon the OpenNRE project. It features five open-source relationship extraction models that were trained on either the Wiki80 or Tacred dataset. Because I am such a big fan of everything Wiki, I decided to use the Wiki80 dataset. Models trained on the Wiki80 dataset can infer 80 relationship types. I havenβt tried the models trained on the Tacred dataset. You might try that on your own. In the IE pipeline implementation, I have used the wiki80_bert_softmax model. As the name implies, it uses the BERT encoder under the hood. One thing is sure. If you donβt have a GPU, you are not going to have a good time.
If we look at an example relationship extraction call in the OpenNRE library, weβll notice that it only infers relationships and doesnβt try to extract named entities. We have to provide a pair of entities with the h and t parameters and then the model tries to infer a relationship.
model.infer({'text': 'He was the son of MaΜel DuΜin mac MaΜele Fithrich, and grandson of the high king AΜed Uaridnach (died 612).', 'h': {'pos': (18, 46)}, 't': {'pos': (78, 91)}})('father', 0.5108704566955566)
The results output a relationship type as well as the confidence level of the prediction. My not so spotless code for relationship extraction looks like this:
We have to use the results of the named entity linking as an input to the relationship extraction process. We iterate over every permutation of a pair of entities and try to infer a relationship. As you can see by the code, we also have a relation_threshold parameter to omit relationships with a small confidence level. You will later see why we use permutations and not combinations of entities.
So, if we run our example text through the relationship extraction pipeline, the results are the following:
Relationship extraction is a challenging problem to tackle, so donβt expect perfect results. I must say that this IE pipeline works as well, if not better than some of the commercial solutions out there. And obviously, other commercial solutions are way better.
As we are dealing with entities and their relationships, it only makes sense to store the results in a graph database. I used Neo4j in my example.
Remember, I said that we would try to infer a relationship between all permutations of pairs of entities instead of combinations. Looking at table results, it would be harder to spot why. In a graph visualization, it is easy to observe that while most of the relationships are inferred in both directions, that is not true in all cases. For example, the work location relationship between Elon Musk and the University of Pennsylvania is assumed in a single direction only. That brings us to another shortcoming of the OpenNRE model. The direction of the relationship isnβt as precise as we would like it to be.
To not leave you empty-handed, I will show you how you can use my IE implementation in your projects. We will run the IE pipeline through the BBC News Dataset found on Kaggle. The hardest part about the IE pipeline implementation was to set up all the dependencies. I want you to retain your mental sanity, so I built a docker image that you can use. Run the following command to get it up and running:
docker run -p 5000:5000 tomasonjo/trinityie
On the first run, the OpenNRE models have to be downloaded, so definitely donβt use -rm option. If you want to do some changes to the project and built your own version, I have also prepared a GitHub repository.
As we will be storing the results into Neo4j, you will also have to download and set it up. In the above example, I have used a simple graph schema, where nodes represent entities and relationships represent, well, relationships. Now we will refactor our graph schema a bit. We want to store entities and relationships in the graph but also save the original text. Having an audit trail is very useful in real-world scenarios as we already know that the IE pipeline is not perfect.
It might be a bit counter-intuitive to refactor a relationship into an intermediate node. The problem we are facing is that we canβt have a relationship pointing to another relationship. Given this issue, I have decided to refactor a relationship into an intermediate node. I could have used my imagination to produce better relationship types and node labels, but it is what it is. I only wanted for the relationship direction to retain its function.
The code to import 500 articles in the BBC news dataset to Neo4j is the following. Youβll have to have the trinityIE docker running for the IE pipeline to work.
The code is also available in the form of a Jupyter Notebook on GitHub. Depending on your GPU capabilities, the IE pipeline might take some time. Letβs now inspect the output. Obviously, I chose results that make sense. Run the following query:
MATCH p=(e:Entity{name:'Enrico Bondi'})-[:RELATION]->(r)-[:RELATION]->(), (r)<-[:MENTIONS_REL]-(s)RETURN *
Results
We can observe that Enrico Bondi is an Italian citizen. He held a position at Italyβs Chamber of Deputies. Another relationship was inferred that he also owns Parmalat. After a short Google search, it seems that this data is more or less at least in the realms of possible.
You might wonder, what has this got to do with explainable AI. Iβll give you a real-world example. This research paper is titled Drug Repurposing for COVID-19 via Knowledge Graph Completion. Iβm not a doctor, so donβt expect a detailed presentation, but I can give a high-level overview. There are a lot of medical research papers available online. There are also online medical entities databases such as MeSH or Ensembl. Suppose you run a Named Entity Linking model on biomedical research papers and use one of the online medical databases as a target knowledge base. In that case, you can extract mentioned entities in articles. The more challenging part is the relationship extraction. Because this is such an important field, great minds have come together and extracted those relationships.
Probably there are more projects, but I am aware of the SemMedDB project, which was also used in the mentioned article. Now that you have your knowledge graph, you can try to predict new purposes for existing drugs. In network science, this is referred to as link prediction. When you are trying to predict links as well as their relationship types, then the scientific community calls it knowledge graph completion. Imagine we have predicted some new use cases for existing drugs and show our results to a doctor or a pharmacologist. His response would probably be, thatβs nice, but what makes you think this new use case will work? The machine learning models are a black box, so thatβs not really helpful. But what you can give to the doctor is all the connections between the existing drug and the new disease it could treat. And not only direct relationships, but also those that are two or three hops away. Iβll make up an example, so it might not make sense to a biomedical researcher. Suppose the existing drug inhibits a gene that is correlated to the disease. There might be many direct or indirect connections between the drug and the disease that might make sense. Hence, we have embarked on a step towards an explainable AI.
I am really delighted with how this project worked out. Iβve been tinkering with combining NLP and Knowledge graphs for the last year or so, and now I have poured all of my knowledge into a single post. I hope you enjoyed it!
p.s. If you want to make some changes to the IE pipeline, the code is available as a Github repository. The code for reproducing this blog post is also available as a Jupyter Notebook. | [
{
"code": null,
"e": 581,
"s": 172,
"text": "I am thrilled to present my latest project I have been working on. If you have been following my posts, you know that I am passionate about combining natural language processing and knowledge graphs. In this blog post, I will present my implementation of an information extraction data pipeline. Later on, I will also explain why I see the combination of NLP and graphs as one of the paths to explainable AI."
},
{
"code": null,
"e": 769,
"s": 581,
"text": "What exactly is an information extraction pipeline? To put it in simple terms, information extraction is the task of extracting structured information from unstructured data such as text."
},
{
"code": null,
"e": 1622,
"s": 769,
"text": "My implementation of the information extraction pipeline consists of four parts. In the first step, we run the input text through a coreference resolution model. The coreference resolution is the task of finding all expressions that refer to a specific entity. To put it simply, it links all the pronouns to the referred entity. Once that step is finished, it splits the text into sentences and removes the punctuations. I have noticed that the specific ML model used for named entity linking works better when we first remove the punctuations. In the named entity linking part of the pipeline, we try to extract all the mentioned entities and connect them to a target knowledge base. The target knowledge base, in this case, is Wikipedia. Named entity linking is beneficial because it also deals with entity disambiguation, which can be a big problem."
},
{
"code": null,
"e": 1954,
"s": 1622,
"text": "Once we have extracted the mentioned entities, the IE pipeline tries to infer relationships between entities that make sense based on the textβs context. The IE pipeline results are entities and their relationships, so it makes sense to use a graph database to store the output. I will show how to save the IE information to Neo4j."
},
{
"code": null,
"e": 2037,
"s": 1954,
"text": "Iβll use the following excerpt from Wikipedia to walk you through the IE pipeline."
},
{
"code": null,
"e": 3005,
"s": 2037,
"text": "Elon Musk is a business magnate, industrial designer, and engineer. He is the founder, CEO, CTO, and chief designer of SpaceX. He is also early investor, CEO, and product architect of Tesla, Inc. He is also the founder of The Boring Company and the co-founder of Neuralink. A centibillionaire, Musk became the richest person in the world in January 2021, with an estimated net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother and South African father and raised in Pretoria, South Africa. He briefly attended the University of Pretoria before moving to Canada aged 17 to attend Queen's University. He transferred to the University of Pennsylvania two years later, where he received dual bachelor's degrees in economics and physics. He moved to California in 1995 to attend Stanford University, but decided instead to pursue a business career. He went on co-founding a web software company Zip2 with his brother Kimbal Musk."
},
{
"code": null,
"e": 3110,
"s": 3005,
"text": "Text is copied from https://en.wikipedia.org/wiki/Elon_Musk and is available under CC BY-SA 3.0 license."
},
{
"code": null,
"e": 3650,
"s": 3110,
"text": "As mentioned, the coreference resolution tries to find all expressions in the text that refer to a specific entity. In my implementation, I have used the Neuralcoref model from Huggingface that runs on top of the SpaCy framework. I have used the default parameters of the Neuralcoref model. One thing I did notice along the way is that the Neuralcoref model doesnβt work well with location pronouns. I have also borrowed a small improvement code from one of the GitHub issues. The code for the coreference resolution part is the following:"
},
{
"code": null,
"e": 3748,
"s": 3650,
"text": "If we run our example text through the coref_resolution function, weβll get the following output:"
},
{
"code": null,
"e": 4778,
"s": 3748,
"text": "Elon Musk is a business magnate, industrial designer, and engineer. Elon Musk is the founder, CEO, CTO, and chief designer of SpaceX. Elon Musk is also early investor, CEO, and product architect of Tesla, Inc. Elon Musk is also the founder of The Boring Company and the co-founder of Neuralink. A centibillionaire, Musk became the richest person in the world in January 2021, with an estimated net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother and South African father and raised in Pretoria, South Africa. Elon Musk briefly attended the University of Pretoria before moving to Canada aged 17 to attend Queen's University. Elon Musk transferred to the University of Pennsylvania two years later, where Elon Musk received dual bachelor's degrees in economics and physics. Elon Musk moved to California in 1995 to attend Stanford University, but decided instead to pursue a business career. Elon Musk went on co-founding a web software company Zip2 with Elon Musk brother Kimbal Musk."
},
{
"code": null,
"e": 5054,
"s": 4778,
"text": "In this example, there are no advanced coreference resolution techniques required. The Neuralcoref model changed a couple of pronouns βHeβ to βElon Muskβ. While it might seem very simple, this is an important step that will increase the overall efficiency of our IE pipeline."
},
{
"code": null,
"e": 5736,
"s": 5054,
"text": "Just recently, I have published a blog post using Named Entity Linking to construct a knowledge graph. Here, I wanted to use a different named entity linking model. I first tried to use the Facebook BLINK model, but I quickly realized it wouldnβt work on my laptop. It needs at least 50GB of free space, which is not a big problem per se, but it also requires 32GB of RAM. My laptop has only 16GB of RAM, and we still need other parts of the pipeline to work. So I reverted to use the good old Wikifier API, which has already shown to be useful. And itβs totally free. If you want to find more information about the API, look at my previous blog post or the official documentation."
},
{
"code": null,
"e": 5905,
"s": 5736,
"text": "Before we run our input text through the Wikifier API, we will split the text into sentences and remove the punctuations. Overall, the code for this step is as follows:"
},
{
"code": null,
"e": 6328,
"s": 5905,
"text": "I forgot to mention that the Wikifier API returns all the classes that an entity belongs to. It looks at the INSTANCE_OF and SUBCLASS_OF classes and traverses all the way through the class hierarchy. I decided to filter out entities with categories that would belong to a person, organization, or location. If we run our example text through the Named Entity Linking part of the pipeline, we will get the following output."
},
{
"code": null,
"e": 6791,
"s": 6328,
"text": "A nice thing about the wikification process is that we also get the corresponding WikiData ids for entities along with their titles. Having the WikiData ids takes care of the entity disambiguation problem. You might wonder then what happens if an entity does not exist on Wikipedia. In that case, unfortunately, the Wikifier will not recognize it. I wouldnβt worry too much about it, though, as Wikipedia has more than 100 million entities if I recall correctly."
},
{
"code": null,
"e": 7097,
"s": 6791,
"text": "If you look closely at the results, youβll notice that Pretoria is wrongly classified as an Organization. I tried to solve this issue, but the Wikipedia class hierarchy is complicated and usually spans five or six hops. If there are some Wiki class experts out there, I will happily listen to your advice."
},
{
"code": null,
"e": 8078,
"s": 7097,
"text": "I have already presented all of the concepts until this point. I have never delved into relationship extraction before. So far, we have only played around with co-occurrence networks. So, I am excited to present a working relationship extraction process. I spend a lot of time searching for any open-source models that might do a decent job. I was delighted to stumble upon the OpenNRE project. It features five open-source relationship extraction models that were trained on either the Wiki80 or Tacred dataset. Because I am such a big fan of everything Wiki, I decided to use the Wiki80 dataset. Models trained on the Wiki80 dataset can infer 80 relationship types. I havenβt tried the models trained on the Tacred dataset. You might try that on your own. In the IE pipeline implementation, I have used the wiki80_bert_softmax model. As the name implies, it uses the BERT encoder under the hood. One thing is sure. If you donβt have a GPU, you are not going to have a good time."
},
{
"code": null,
"e": 8362,
"s": 8078,
"text": "If we look at an example relationship extraction call in the OpenNRE library, weβll notice that it only infers relationships and doesnβt try to extract named entities. We have to provide a pair of entities with the h and t parameters and then the model tries to infer a relationship."
},
{
"code": null,
"e": 8573,
"s": 8362,
"text": "model.infer({'text': 'He was the son of MaΜel DuΜin mac MaΜele Fithrich, and grandson of the high king AΜed Uaridnach (died 612).', 'h': {'pos': (18, 46)}, 't': {'pos': (78, 91)}})('father', 0.5108704566955566)"
},
{
"code": null,
"e": 8732,
"s": 8573,
"text": "The results output a relationship type as well as the confidence level of the prediction. My not so spotless code for relationship extraction looks like this:"
},
{
"code": null,
"e": 9130,
"s": 8732,
"text": "We have to use the results of the named entity linking as an input to the relationship extraction process. We iterate over every permutation of a pair of entities and try to infer a relationship. As you can see by the code, we also have a relation_threshold parameter to omit relationships with a small confidence level. You will later see why we use permutations and not combinations of entities."
},
{
"code": null,
"e": 9238,
"s": 9130,
"text": "So, if we run our example text through the relationship extraction pipeline, the results are the following:"
},
{
"code": null,
"e": 9500,
"s": 9238,
"text": "Relationship extraction is a challenging problem to tackle, so donβt expect perfect results. I must say that this IE pipeline works as well, if not better than some of the commercial solutions out there. And obviously, other commercial solutions are way better."
},
{
"code": null,
"e": 9647,
"s": 9500,
"text": "As we are dealing with entities and their relationships, it only makes sense to store the results in a graph database. I used Neo4j in my example."
},
{
"code": null,
"e": 10258,
"s": 9647,
"text": "Remember, I said that we would try to infer a relationship between all permutations of pairs of entities instead of combinations. Looking at table results, it would be harder to spot why. In a graph visualization, it is easy to observe that while most of the relationships are inferred in both directions, that is not true in all cases. For example, the work location relationship between Elon Musk and the University of Pennsylvania is assumed in a single direction only. That brings us to another shortcoming of the OpenNRE model. The direction of the relationship isnβt as precise as we would like it to be."
},
{
"code": null,
"e": 10661,
"s": 10258,
"text": "To not leave you empty-handed, I will show you how you can use my IE implementation in your projects. We will run the IE pipeline through the BBC News Dataset found on Kaggle. The hardest part about the IE pipeline implementation was to set up all the dependencies. I want you to retain your mental sanity, so I built a docker image that you can use. Run the following command to get it up and running:"
},
{
"code": null,
"e": 10705,
"s": 10661,
"text": "docker run -p 5000:5000 tomasonjo/trinityie"
},
{
"code": null,
"e": 10917,
"s": 10705,
"text": "On the first run, the OpenNRE models have to be downloaded, so definitely donβt use -rm option. If you want to do some changes to the project and built your own version, I have also prepared a GitHub repository."
},
{
"code": null,
"e": 11399,
"s": 10917,
"text": "As we will be storing the results into Neo4j, you will also have to download and set it up. In the above example, I have used a simple graph schema, where nodes represent entities and relationships represent, well, relationships. Now we will refactor our graph schema a bit. We want to store entities and relationships in the graph but also save the original text. Having an audit trail is very useful in real-world scenarios as we already know that the IE pipeline is not perfect."
},
{
"code": null,
"e": 11851,
"s": 11399,
"text": "It might be a bit counter-intuitive to refactor a relationship into an intermediate node. The problem we are facing is that we canβt have a relationship pointing to another relationship. Given this issue, I have decided to refactor a relationship into an intermediate node. I could have used my imagination to produce better relationship types and node labels, but it is what it is. I only wanted for the relationship direction to retain its function."
},
{
"code": null,
"e": 12012,
"s": 11851,
"text": "The code to import 500 articles in the BBC news dataset to Neo4j is the following. Youβll have to have the trinityIE docker running for the IE pipeline to work."
},
{
"code": null,
"e": 12257,
"s": 12012,
"text": "The code is also available in the form of a Jupyter Notebook on GitHub. Depending on your GPU capabilities, the IE pipeline might take some time. Letβs now inspect the output. Obviously, I chose results that make sense. Run the following query:"
},
{
"code": null,
"e": 12372,
"s": 12257,
"text": "MATCH p=(e:Entity{name:'Enrico Bondi'})-[:RELATION]->(r)-[:RELATION]->(), (r)<-[:MENTIONS_REL]-(s)RETURN *"
},
{
"code": null,
"e": 12380,
"s": 12372,
"text": "Results"
},
{
"code": null,
"e": 12654,
"s": 12380,
"text": "We can observe that Enrico Bondi is an Italian citizen. He held a position at Italyβs Chamber of Deputies. Another relationship was inferred that he also owns Parmalat. After a short Google search, it seems that this data is more or less at least in the realms of possible."
},
{
"code": null,
"e": 13451,
"s": 12654,
"text": "You might wonder, what has this got to do with explainable AI. Iβll give you a real-world example. This research paper is titled Drug Repurposing for COVID-19 via Knowledge Graph Completion. Iβm not a doctor, so donβt expect a detailed presentation, but I can give a high-level overview. There are a lot of medical research papers available online. There are also online medical entities databases such as MeSH or Ensembl. Suppose you run a Named Entity Linking model on biomedical research papers and use one of the online medical databases as a target knowledge base. In that case, you can extract mentioned entities in articles. The more challenging part is the relationship extraction. Because this is such an important field, great minds have come together and extracted those relationships."
},
{
"code": null,
"e": 14689,
"s": 13451,
"text": "Probably there are more projects, but I am aware of the SemMedDB project, which was also used in the mentioned article. Now that you have your knowledge graph, you can try to predict new purposes for existing drugs. In network science, this is referred to as link prediction. When you are trying to predict links as well as their relationship types, then the scientific community calls it knowledge graph completion. Imagine we have predicted some new use cases for existing drugs and show our results to a doctor or a pharmacologist. His response would probably be, thatβs nice, but what makes you think this new use case will work? The machine learning models are a black box, so thatβs not really helpful. But what you can give to the doctor is all the connections between the existing drug and the new disease it could treat. And not only direct relationships, but also those that are two or three hops away. Iβll make up an example, so it might not make sense to a biomedical researcher. Suppose the existing drug inhibits a gene that is correlated to the disease. There might be many direct or indirect connections between the drug and the disease that might make sense. Hence, we have embarked on a step towards an explainable AI."
},
{
"code": null,
"e": 14915,
"s": 14689,
"text": "I am really delighted with how this project worked out. Iβve been tinkering with combining NLP and Knowledge graphs for the last year or so, and now I have poured all of my knowledge into a single post. I hope you enjoyed it!"
}
]
|
A comprehensive study of Mixed Integer Programming with JuMP on Julia (Part 1) | by Ouaguenouni Mohamed | Towards Data Science | One of the primary purposes of the computer sciences and operation research is to solve problems efficiently; problem-solving is a field where we often find very βad-hocβ methods of resolution, they can be efficient, but they rely on some specific properties of the problem which are not necessarily easy to notice.
In this series of posts, we will introduce and discover a very versatile and generic way of thinking and of solving a wide variety of problems, and this introduction will occur on three sides:
On the theoretical view, we will investigate how Linear Programming and Mixed Integer Programming can help us in modelling big combinatorial problems.
In the practical aspect, we will see how we can use an API to instantiate a Linear Program and exploit some of the problems we solve to improve the solving procedure's efficiency.
And finally, from the operational perspective, we will discover a very recent, efficient and user-friendly language: Julia, and more precisely, we will discover a library: JuMP, a domain-specific modelling language for mathematical optimization.
This series of posts doesn't assume a background in Julia; I think a Python background is more than enough to understand the pieces of code I will use.
This post is the pilot of the series, but it will also be the starting point of it by giving you the background you will need to understand the practical techniques that can be used to solve large combinatorial problems.
It will also be the only post in which we will present a pure theoretical academic problem as an application for simplicity.
Still, if you are comfortable with mixed-integer programming, this post (and more generally this series) is a good occasion to see to use Julia and, more precisely, how to tune your exact solving procedure with some approached methods.
Letβs start by presenting how a linear program is structured and how a solver will perform a resolution. To do it, we will go through a simple example.
To make it visualizable, we will take an example where we will try to optimize a linear function of two variables with respect to a set of linear constraints.
Geometrically, if we take each constraint and replace the inequality with equality, each constraint will be a line equation. This line will separate R2 into two parts and invalidate one of them according to the direction of the inequality.
We will name the polyhedron delimited by the set of constraints, which is, in this case, a polytope because itβs close and bounded, the polyhedron (or the polytope) of constraints.
As a warm-up to Julia, letβs see how we can draw the polytope of constraints by using plot.jl, a βmatplotlib-likeβ framework and the Package LinearAlgebra is similar to NumPy.
First, we use Pkg, which is the built-in package manager of Julia, to add the required Packages,
using Pkg;Pkg.add("LinearAlgebra");Pkg.add("Plots");Pkg.add("PyPlot");
After adding them, we can import them.
using LinearAlgebrausing Plotspyplot()
The last line aims to complete some package plot functionalities for visualization (check the doc here for more details).
An easy way to draw any function is to sample points and compute the associated images, and this can be done in Julia the following way :
x_v = LinRange(-2,15,100)plot([x_v], [x_v .+ 7.5], label ="Y=x + 7.5")plot!([x_v], [-2x_v .+ 20], label ="Y= -2x + 20")
The first line will sample 100 points from the interval [-2, 15]; a part of this; you have several things to notice :
βplotβ is used to create a line plot and plot! update a created plot.
β.+β is the element-wise equivalent of the vector addition.
Julia is so handy that omitting the β*β between a coefficient and a variable is possible even with a vector.
These lines will produce the following plot :
and now letβs print the polytope of constraints :
x_v = LinRange(-2,15,100)y_v = LinRange(-2,15,100)plot([0*x_v], [y_v],label ="Y Axis")plot!([x_v], [0*x_v],label ="X Axis")plot!([x_v], [0*x_v .+ 7.5], label ="Y=7.5")plot!([0*x_v .+ 10], [y_v],label ="X=10")plot!(title = "Polytop of Constraints")
The grey area I added to the plot represents the space's portion, which satisfies the problem's constraints.
Now letβs focus on the objective function by looking at the vector (1,2), representing the gradient of the linear function x+2y.
Each line I added represents a line of points with the same value. The further you go in the gradient direction, the bigger the objective value becomes.
We can visually conclude that the best solution is at the intersection of the green and the pink line, so letβs see if we find this result using JuMP.
The traditional add/import lines (we will use GLPK as a solver, but nothing is dependant on it).
Pkg.add("JuMP")Pkg.add("GLPK")using JuMPusing GLPK
Now we declare our model and set the optimizer from GLPK:
prgrm = Model()set_optimizer(prgrm, GLPK.Optimizer)
We add the variables and precise their scope; by default, the variables are continuous :
@variable(prgrm, 0<=x)@variable(prgrm, 0<=y)
Now we create and add the two remaining constraints; the first two are in the scope of the variables;
@constraint(prgrm, x <= 10)@constraint(prgrm, y <= 7.5)
Finally, we add the objective function and precise sense of optimization, which will be, in this case, a maximization :
@objective(prgrm, Max, x+2y)
One interesting feature of JuMP and especially when using it with Jupyter-notebook is that we can print the program as easily as the content of any variable, which gives us the following output :
And now solving it is as easy to say as it is to do :
optimize!(prgrm)
After that, we can access the values of the variables after optimization like this:
value.(x)value.(y)
And so one we can update our precedent plot to confirm our graphical resolution with the line :
plot!([value.(x)], [value.(y)], seriestype = :scatter, label="Optimum")
This gives us :
Solving a linear program is done with the Simplex algorithm, which works because of a simple but important principle :
Optimizing a linear function on a polytope (or more generally a compact convex space) always leads us to a vertex (more generally an extreme point).
The simplex algorithm is a local search procedure that walks from a vertex to another to increase the objective function's value until we reach a vertex where every neighbour has an inferior value.
Since the vertex where the optimization ends depends only on the objective function, we can try to find an objective function for each polytope vertex.
For example, in the following polytope (Note that we added a constraint to increase the number of vertex of the polytope)
We can obtain any of the vertices by optimizing in different directions.
Even if itβs not totally how a solver works, the first thing you have to understand to assimilate how Mixed Integer Programming works is the Branch and Bound method.
Letβs take the precedent example but restricting our variables to integers; the feasible region is no longer the grey area inside the polytope. Still, we can compute the feasible integer points, which give us the following figure :
In grey, we can see the feasible solutions, and the first thing we can notice is that some vertices are in the integer solutions and some not, and this distinction is crucial, but we will get back to this point later.
The branch and bound procedure create a tree called βenumeration treeβ; in each node, it constructs a mixed-integer program and solves its βlinear relaxationβ with the simplex algorithm, which means the same program after ignoring integrality constraint, from this point on, there are two possible outcomes :
The solution is integer feasible, and therefore we stop the resolution.
This can happen if the polytope of constraints has integer vertices. For instance, if we solve the LP relaxation of the precedent mixed-integer program with the objective function 2x+y, we will find (10,3), which is an integer solution.
The solution is βfractionalβ, and therefore we need to branch.
And this will happen in the precedent polytope if we try to optimize the function x+2y,
Now, letβs see how we can handle this case.
Branching refers to creating child nodes in the enumeration tree; these children are the same problem but solved on two partitions of the feasible space.
These two partitions are obtained by adding a branching constraint.
Since an example is worth a thousand words, for the precedent fractional solution, which was (5.5, 7.5), we can choose which variable we can branch on if we had an integer and a fractional component in our solution, we should have branched on the fractional one, letβs say, we will branch on x, so we add one constraint in each child node,
The first child node will have the constraint x β€ 5
The second one will inherit the constraint xβ₯6
As you can notice, the aim of these constraints is, in each case, to exclude or to cut the fractional solution (you will discover why itβs in bold in another part of this series :) )
This last childβs relaxation giveβs us the following solution.
The solution in red is : (6.0, 7.0) an integer feasible solution.
And so, are we done? Well.. not really.
Letβs review our enumeration tree.
As we can see, we solved only two of the 3 nodes of the tree; then, we have to solve P.1βs Linear Relaxation.
The relaxation gives us a fractional solution : (5.0, 7.5) which means the enumeration tree would become like this if we branch on y.
Why am I saying would? Well, the algorithmβs name is Brand-and-Bound, and until now, we just branched, so now we will see how we can bound.
The bounding or βprobingβ procedure consists of removing a branch of the tree provided that we have a superior bound (for maximization) of the values we can find in it.
To have this upper bound, we will introduce another intuitive and important principle :
The value of an LPβs relaxation is an upper bound on itβs value.
Itβs intuitive because the feasible region of the relaxation contains the original program's feasible region.
So when we solved P.1 and obtain a fractional solution whose value is 20, we are sure that in the sub-tree whose root is P.1, we won't find any solution with a value above 20 and since we already have an integer solution whose value is 20 we can probe this part of the tree, and after that, we are done.
The first question you should all have in mind is: βAm I going to do all this every time I have to solve a MIP ? β and the answer is, of course, no, I have to precise that the variables are integers and the solver will do this job (among other things) for us.
@variable(prgrm, 0<=x, Int)@variable(prgrm, 0<=y, Int)
But the most attentive among you are certainly wondering what if the solver, when constructing the enumeration tree, had started with the other child who doesn't give us instantly an integer solution?
This raises many questions about how to branch and how to explore the enumeration tree, but the principal thing you may focus on is that.
The sooner we obtain an integer solution, the best it is to prune subtrees.
But since the solver is doing this internally, what is the purpose of understanding this point (and of all this part)? this is what we will see in the following :)
In many large combinatorial problems, the solver may not find an integer solution, so its enumeration tree keeps growing exponentially.
Fortunately, many combinatorial problems have simple (often greedy) heuristics that compute quickly a feasible solution which is consequently an integer solution.
The solvers who are generally used gives us an interface to compute and submit heuristic solutions; this aims to give the algorithm an integer solution to enforce the probing.
Letβs try to apply this to a very classical example: The Vertex Cover Problem.
A vertex cover Vβ of an undirected graph G=(V,E),is a set of vertices that includes at least one endpoint of every edge of the graph, often we are interested in finding the smallest vertex cover.
The first question we have to think about is βHow are we going to represent an instance of the problem ?β, to answer this question, letβs take an example.
Since the edges are not weighted, we can represent the problem with an adjacency matrix of shape (n,n) where n is the number of nodes.
So, for instance, the precedent graph is encoded in the following matrix :
ADJ_MAT = [ [0 , 0 , 1, 0, 0, 0], [0 , 0 , 1, 0, 0, 0], [1 , 1 , 0, 1, 0, 0], [0 , 0 , 1, 0, 1, 0], [0 , 0 , 0, 1, 0, 1], [0 , 0 , 0, 0, 1, 0],]
(Now, I advise you to stop reading and to try to write the MIP formulation for the Vertex Cover Problem to check your understanding)
Now letβs think about the formulation we are going to use :
What are the decision variables?
We are trying to decide for each vertex if we take it or not in the cover, so we have n binary variables, indicating whether we take the corresponding vertex.
We can create the variables as follows:
#WARNING : Everything on Julia is indexed by default starting from #1.n = size(ADJ_MAT)[1] #We create a vector of variables indexed by 1 prefixed by x (x1, x2, ..., xn)@variable(prgrm2, 0<=x[1:n], Int)
What are the constraints?
A feasible solution must cover each edge, so we have to take one vertex or the other (or both) for each edge.
These constraints can be created simply like this :
for i in 1:n for j in 1:n if(ADJ_MAT[i,j] == 1) c = @constraint(prgrm2, x[i] + x[j] >= 1) set_name(c,"C") println(c) end endend
What are we optimising?
The objective is to minimise the number of vertices we take in the cover:
which can be generated like this :
@objective(prgrm2, Min, sum(x))#Output : x1+x2+x3+x4+x5+x6
So the MIP formulation is the following:
Which gives the following solution :
Which can be interpreted as follows:
In this part, I will present two ways of computing a feasible solution for the vertex cover problem; these two algorithms have a fascinating property: approximations with a performance guarantee.
Greedy algorithm :
This algorithm consists of taking each edge both endpoints and removing all the covered edges at each step.
The greedy algorithm is a 2-approximation which means it never return a solution that is more than two times worst than the optimal.
The proof is straightforward once you notice that you take two vertexes where one would have been enough in the worst case.
Rounding up a fractional solution:
The vertex cover problem has another interesting property: itβs a βhalf-integral problemβ, which means that even in its relaxation, the variables are 0 or 1 or 1/2.
Another way of getting an approximation of the solution is to round up a fractional solution by turning the 1/2 to ones, which will give us a feasible solution because the fractional was already fulfilling the constraints, and we increased some of its variables.
(for the full proofs of the validity of the two approaches, you can read this course)
Now, how can we tell our solver to call a heuristic at each fractional node?
To do so, you have to understand 3 things:
How can you get the solver's current solution values in the Callback?
How can you submit your heuristic solution after constructing it from the Callback?
How can you register your Callback so that the solver will use it?
And I will explain to you each of these aspects in the following example of using the round-up approximation :
The first step you have to design your callback; inside your callback, you can use two methods :
callback_value(cb_data, x) to get from the callback data the value of a variable (and only one at a time).
MOI.submit( model, MOI.HeuristicSolution(cb_data), [x], [v] ) : this method submit the solution x=v and returns the status of the solution which can either be βacceptedβ βrejectedβ (by the solver) or βunknownβ.
So for our round-up approximation, here is the callback we propose :
function my_callback_function(cb_data) println("Call to callback") new_sol = [] precedent = [callback_value(cb_data,x_k ) for x_k in x] for x_i in x x_val = callback_value(cb_data, x_i) x_new = ceil(Int, x_val) append!(new_sol, x_new) end println("Precedent: ", precedent) println("New: ",new_sol) status = MOI.submit( mod, MOI.HeuristicSolution(cb_data), [x_i for x_i in x], [floor(Int, k) for k in new_sol] ) println("status = ", status)end
I added the print statements to track the calls to the heuristic.
Now we register our callback :
MOI.set(mod, MOI.HeuristicCallback(), my_callback_function)
So when executing the optimization step, we can see this :
The rejected solutions after the first are because the rounding up procedure is quickly not sufficient in terms of efficiency to beat the integer solutions produced by the solver, so the solutions it proposes are rejected, but still, it was useful in the first iterations.
When you design a solution, you have to choose between an exact or an approached solution. Still, as we saw, provided a good intuition on the specific problem you want to solve and a good understanding of a solver's internal behaviour, we can get the best of both worlds.
A special thanks to Pr Pierre Fouillhoux, who enlightened us and helped us better understand this field's depth and appreciate all the nuance of it. Of course, s/o my mate Louis Grassin who helped me write and code the content of this article. | [
{
"code": null,
"e": 488,
"s": 172,
"text": "One of the primary purposes of the computer sciences and operation research is to solve problems efficiently; problem-solving is a field where we often find very βad-hocβ methods of resolution, they can be efficient, but they rely on some specific properties of the problem which are not necessarily easy to notice."
},
{
"code": null,
"e": 681,
"s": 488,
"text": "In this series of posts, we will introduce and discover a very versatile and generic way of thinking and of solving a wide variety of problems, and this introduction will occur on three sides:"
},
{
"code": null,
"e": 832,
"s": 681,
"text": "On the theoretical view, we will investigate how Linear Programming and Mixed Integer Programming can help us in modelling big combinatorial problems."
},
{
"code": null,
"e": 1012,
"s": 832,
"text": "In the practical aspect, we will see how we can use an API to instantiate a Linear Program and exploit some of the problems we solve to improve the solving procedure's efficiency."
},
{
"code": null,
"e": 1258,
"s": 1012,
"text": "And finally, from the operational perspective, we will discover a very recent, efficient and user-friendly language: Julia, and more precisely, we will discover a library: JuMP, a domain-specific modelling language for mathematical optimization."
},
{
"code": null,
"e": 1410,
"s": 1258,
"text": "This series of posts doesn't assume a background in Julia; I think a Python background is more than enough to understand the pieces of code I will use."
},
{
"code": null,
"e": 1631,
"s": 1410,
"text": "This post is the pilot of the series, but it will also be the starting point of it by giving you the background you will need to understand the practical techniques that can be used to solve large combinatorial problems."
},
{
"code": null,
"e": 1756,
"s": 1631,
"text": "It will also be the only post in which we will present a pure theoretical academic problem as an application for simplicity."
},
{
"code": null,
"e": 1992,
"s": 1756,
"text": "Still, if you are comfortable with mixed-integer programming, this post (and more generally this series) is a good occasion to see to use Julia and, more precisely, how to tune your exact solving procedure with some approached methods."
},
{
"code": null,
"e": 2144,
"s": 1992,
"text": "Letβs start by presenting how a linear program is structured and how a solver will perform a resolution. To do it, we will go through a simple example."
},
{
"code": null,
"e": 2303,
"s": 2144,
"text": "To make it visualizable, we will take an example where we will try to optimize a linear function of two variables with respect to a set of linear constraints."
},
{
"code": null,
"e": 2543,
"s": 2303,
"text": "Geometrically, if we take each constraint and replace the inequality with equality, each constraint will be a line equation. This line will separate R2 into two parts and invalidate one of them according to the direction of the inequality."
},
{
"code": null,
"e": 2724,
"s": 2543,
"text": "We will name the polyhedron delimited by the set of constraints, which is, in this case, a polytope because itβs close and bounded, the polyhedron (or the polytope) of constraints."
},
{
"code": null,
"e": 2900,
"s": 2724,
"text": "As a warm-up to Julia, letβs see how we can draw the polytope of constraints by using plot.jl, a βmatplotlib-likeβ framework and the Package LinearAlgebra is similar to NumPy."
},
{
"code": null,
"e": 2997,
"s": 2900,
"text": "First, we use Pkg, which is the built-in package manager of Julia, to add the required Packages,"
},
{
"code": null,
"e": 3068,
"s": 2997,
"text": "using Pkg;Pkg.add(\"LinearAlgebra\");Pkg.add(\"Plots\");Pkg.add(\"PyPlot\");"
},
{
"code": null,
"e": 3107,
"s": 3068,
"text": "After adding them, we can import them."
},
{
"code": null,
"e": 3146,
"s": 3107,
"text": "using LinearAlgebrausing Plotspyplot()"
},
{
"code": null,
"e": 3268,
"s": 3146,
"text": "The last line aims to complete some package plot functionalities for visualization (check the doc here for more details)."
},
{
"code": null,
"e": 3406,
"s": 3268,
"text": "An easy way to draw any function is to sample points and compute the associated images, and this can be done in Julia the following way :"
},
{
"code": null,
"e": 3526,
"s": 3406,
"text": "x_v = LinRange(-2,15,100)plot([x_v], [x_v .+ 7.5], label =\"Y=x + 7.5\")plot!([x_v], [-2x_v .+ 20], label =\"Y= -2x + 20\")"
},
{
"code": null,
"e": 3644,
"s": 3526,
"text": "The first line will sample 100 points from the interval [-2, 15]; a part of this; you have several things to notice :"
},
{
"code": null,
"e": 3714,
"s": 3644,
"text": "βplotβ is used to create a line plot and plot! update a created plot."
},
{
"code": null,
"e": 3774,
"s": 3714,
"text": "β.+β is the element-wise equivalent of the vector addition."
},
{
"code": null,
"e": 3883,
"s": 3774,
"text": "Julia is so handy that omitting the β*β between a coefficient and a variable is possible even with a vector."
},
{
"code": null,
"e": 3929,
"s": 3883,
"text": "These lines will produce the following plot :"
},
{
"code": null,
"e": 3979,
"s": 3929,
"text": "and now letβs print the polytope of constraints :"
},
{
"code": null,
"e": 4227,
"s": 3979,
"text": "x_v = LinRange(-2,15,100)y_v = LinRange(-2,15,100)plot([0*x_v], [y_v],label =\"Y Axis\")plot!([x_v], [0*x_v],label =\"X Axis\")plot!([x_v], [0*x_v .+ 7.5], label =\"Y=7.5\")plot!([0*x_v .+ 10], [y_v],label =\"X=10\")plot!(title = \"Polytop of Constraints\")"
},
{
"code": null,
"e": 4336,
"s": 4227,
"text": "The grey area I added to the plot represents the space's portion, which satisfies the problem's constraints."
},
{
"code": null,
"e": 4465,
"s": 4336,
"text": "Now letβs focus on the objective function by looking at the vector (1,2), representing the gradient of the linear function x+2y."
},
{
"code": null,
"e": 4618,
"s": 4465,
"text": "Each line I added represents a line of points with the same value. The further you go in the gradient direction, the bigger the objective value becomes."
},
{
"code": null,
"e": 4769,
"s": 4618,
"text": "We can visually conclude that the best solution is at the intersection of the green and the pink line, so letβs see if we find this result using JuMP."
},
{
"code": null,
"e": 4866,
"s": 4769,
"text": "The traditional add/import lines (we will use GLPK as a solver, but nothing is dependant on it)."
},
{
"code": null,
"e": 4917,
"s": 4866,
"text": "Pkg.add(\"JuMP\")Pkg.add(\"GLPK\")using JuMPusing GLPK"
},
{
"code": null,
"e": 4975,
"s": 4917,
"text": "Now we declare our model and set the optimizer from GLPK:"
},
{
"code": null,
"e": 5027,
"s": 4975,
"text": "prgrm = Model()set_optimizer(prgrm, GLPK.Optimizer)"
},
{
"code": null,
"e": 5116,
"s": 5027,
"text": "We add the variables and precise their scope; by default, the variables are continuous :"
},
{
"code": null,
"e": 5161,
"s": 5116,
"text": "@variable(prgrm, 0<=x)@variable(prgrm, 0<=y)"
},
{
"code": null,
"e": 5263,
"s": 5161,
"text": "Now we create and add the two remaining constraints; the first two are in the scope of the variables;"
},
{
"code": null,
"e": 5319,
"s": 5263,
"text": "@constraint(prgrm, x <= 10)@constraint(prgrm, y <= 7.5)"
},
{
"code": null,
"e": 5439,
"s": 5319,
"text": "Finally, we add the objective function and precise sense of optimization, which will be, in this case, a maximization :"
},
{
"code": null,
"e": 5468,
"s": 5439,
"text": "@objective(prgrm, Max, x+2y)"
},
{
"code": null,
"e": 5664,
"s": 5468,
"text": "One interesting feature of JuMP and especially when using it with Jupyter-notebook is that we can print the program as easily as the content of any variable, which gives us the following output :"
},
{
"code": null,
"e": 5718,
"s": 5664,
"text": "And now solving it is as easy to say as it is to do :"
},
{
"code": null,
"e": 5735,
"s": 5718,
"text": "optimize!(prgrm)"
},
{
"code": null,
"e": 5819,
"s": 5735,
"text": "After that, we can access the values of the variables after optimization like this:"
},
{
"code": null,
"e": 5838,
"s": 5819,
"text": "value.(x)value.(y)"
},
{
"code": null,
"e": 5934,
"s": 5838,
"text": "And so one we can update our precedent plot to confirm our graphical resolution with the line :"
},
{
"code": null,
"e": 6006,
"s": 5934,
"text": "plot!([value.(x)], [value.(y)], seriestype = :scatter, label=\"Optimum\")"
},
{
"code": null,
"e": 6022,
"s": 6006,
"text": "This gives us :"
},
{
"code": null,
"e": 6141,
"s": 6022,
"text": "Solving a linear program is done with the Simplex algorithm, which works because of a simple but important principle :"
},
{
"code": null,
"e": 6290,
"s": 6141,
"text": "Optimizing a linear function on a polytope (or more generally a compact convex space) always leads us to a vertex (more generally an extreme point)."
},
{
"code": null,
"e": 6488,
"s": 6290,
"text": "The simplex algorithm is a local search procedure that walks from a vertex to another to increase the objective function's value until we reach a vertex where every neighbour has an inferior value."
},
{
"code": null,
"e": 6640,
"s": 6488,
"text": "Since the vertex where the optimization ends depends only on the objective function, we can try to find an objective function for each polytope vertex."
},
{
"code": null,
"e": 6762,
"s": 6640,
"text": "For example, in the following polytope (Note that we added a constraint to increase the number of vertex of the polytope)"
},
{
"code": null,
"e": 6835,
"s": 6762,
"text": "We can obtain any of the vertices by optimizing in different directions."
},
{
"code": null,
"e": 7001,
"s": 6835,
"text": "Even if itβs not totally how a solver works, the first thing you have to understand to assimilate how Mixed Integer Programming works is the Branch and Bound method."
},
{
"code": null,
"e": 7233,
"s": 7001,
"text": "Letβs take the precedent example but restricting our variables to integers; the feasible region is no longer the grey area inside the polytope. Still, we can compute the feasible integer points, which give us the following figure :"
},
{
"code": null,
"e": 7451,
"s": 7233,
"text": "In grey, we can see the feasible solutions, and the first thing we can notice is that some vertices are in the integer solutions and some not, and this distinction is crucial, but we will get back to this point later."
},
{
"code": null,
"e": 7760,
"s": 7451,
"text": "The branch and bound procedure create a tree called βenumeration treeβ; in each node, it constructs a mixed-integer program and solves its βlinear relaxationβ with the simplex algorithm, which means the same program after ignoring integrality constraint, from this point on, there are two possible outcomes :"
},
{
"code": null,
"e": 7832,
"s": 7760,
"text": "The solution is integer feasible, and therefore we stop the resolution."
},
{
"code": null,
"e": 8069,
"s": 7832,
"text": "This can happen if the polytope of constraints has integer vertices. For instance, if we solve the LP relaxation of the precedent mixed-integer program with the objective function 2x+y, we will find (10,3), which is an integer solution."
},
{
"code": null,
"e": 8132,
"s": 8069,
"text": "The solution is βfractionalβ, and therefore we need to branch."
},
{
"code": null,
"e": 8220,
"s": 8132,
"text": "And this will happen in the precedent polytope if we try to optimize the function x+2y,"
},
{
"code": null,
"e": 8264,
"s": 8220,
"text": "Now, letβs see how we can handle this case."
},
{
"code": null,
"e": 8418,
"s": 8264,
"text": "Branching refers to creating child nodes in the enumeration tree; these children are the same problem but solved on two partitions of the feasible space."
},
{
"code": null,
"e": 8486,
"s": 8418,
"text": "These two partitions are obtained by adding a branching constraint."
},
{
"code": null,
"e": 8826,
"s": 8486,
"text": "Since an example is worth a thousand words, for the precedent fractional solution, which was (5.5, 7.5), we can choose which variable we can branch on if we had an integer and a fractional component in our solution, we should have branched on the fractional one, letβs say, we will branch on x, so we add one constraint in each child node,"
},
{
"code": null,
"e": 8878,
"s": 8826,
"text": "The first child node will have the constraint x β€ 5"
},
{
"code": null,
"e": 8925,
"s": 8878,
"text": "The second one will inherit the constraint xβ₯6"
},
{
"code": null,
"e": 9108,
"s": 8925,
"text": "As you can notice, the aim of these constraints is, in each case, to exclude or to cut the fractional solution (you will discover why itβs in bold in another part of this series :) )"
},
{
"code": null,
"e": 9171,
"s": 9108,
"text": "This last childβs relaxation giveβs us the following solution."
},
{
"code": null,
"e": 9237,
"s": 9171,
"text": "The solution in red is : (6.0, 7.0) an integer feasible solution."
},
{
"code": null,
"e": 9277,
"s": 9237,
"text": "And so, are we done? Well.. not really."
},
{
"code": null,
"e": 9312,
"s": 9277,
"text": "Letβs review our enumeration tree."
},
{
"code": null,
"e": 9422,
"s": 9312,
"text": "As we can see, we solved only two of the 3 nodes of the tree; then, we have to solve P.1βs Linear Relaxation."
},
{
"code": null,
"e": 9556,
"s": 9422,
"text": "The relaxation gives us a fractional solution : (5.0, 7.5) which means the enumeration tree would become like this if we branch on y."
},
{
"code": null,
"e": 9696,
"s": 9556,
"text": "Why am I saying would? Well, the algorithmβs name is Brand-and-Bound, and until now, we just branched, so now we will see how we can bound."
},
{
"code": null,
"e": 9865,
"s": 9696,
"text": "The bounding or βprobingβ procedure consists of removing a branch of the tree provided that we have a superior bound (for maximization) of the values we can find in it."
},
{
"code": null,
"e": 9953,
"s": 9865,
"text": "To have this upper bound, we will introduce another intuitive and important principle :"
},
{
"code": null,
"e": 10018,
"s": 9953,
"text": "The value of an LPβs relaxation is an upper bound on itβs value."
},
{
"code": null,
"e": 10128,
"s": 10018,
"text": "Itβs intuitive because the feasible region of the relaxation contains the original program's feasible region."
},
{
"code": null,
"e": 10432,
"s": 10128,
"text": "So when we solved P.1 and obtain a fractional solution whose value is 20, we are sure that in the sub-tree whose root is P.1, we won't find any solution with a value above 20 and since we already have an integer solution whose value is 20 we can probe this part of the tree, and after that, we are done."
},
{
"code": null,
"e": 10692,
"s": 10432,
"text": "The first question you should all have in mind is: βAm I going to do all this every time I have to solve a MIP ? β and the answer is, of course, no, I have to precise that the variables are integers and the solver will do this job (among other things) for us."
},
{
"code": null,
"e": 10747,
"s": 10692,
"text": "@variable(prgrm, 0<=x, Int)@variable(prgrm, 0<=y, Int)"
},
{
"code": null,
"e": 10948,
"s": 10747,
"text": "But the most attentive among you are certainly wondering what if the solver, when constructing the enumeration tree, had started with the other child who doesn't give us instantly an integer solution?"
},
{
"code": null,
"e": 11086,
"s": 10948,
"text": "This raises many questions about how to branch and how to explore the enumeration tree, but the principal thing you may focus on is that."
},
{
"code": null,
"e": 11162,
"s": 11086,
"text": "The sooner we obtain an integer solution, the best it is to prune subtrees."
},
{
"code": null,
"e": 11326,
"s": 11162,
"text": "But since the solver is doing this internally, what is the purpose of understanding this point (and of all this part)? this is what we will see in the following :)"
},
{
"code": null,
"e": 11462,
"s": 11326,
"text": "In many large combinatorial problems, the solver may not find an integer solution, so its enumeration tree keeps growing exponentially."
},
{
"code": null,
"e": 11625,
"s": 11462,
"text": "Fortunately, many combinatorial problems have simple (often greedy) heuristics that compute quickly a feasible solution which is consequently an integer solution."
},
{
"code": null,
"e": 11801,
"s": 11625,
"text": "The solvers who are generally used gives us an interface to compute and submit heuristic solutions; this aims to give the algorithm an integer solution to enforce the probing."
},
{
"code": null,
"e": 11880,
"s": 11801,
"text": "Letβs try to apply this to a very classical example: The Vertex Cover Problem."
},
{
"code": null,
"e": 12076,
"s": 11880,
"text": "A vertex cover Vβ of an undirected graph G=(V,E),is a set of vertices that includes at least one endpoint of every edge of the graph, often we are interested in finding the smallest vertex cover."
},
{
"code": null,
"e": 12231,
"s": 12076,
"text": "The first question we have to think about is βHow are we going to represent an instance of the problem ?β, to answer this question, letβs take an example."
},
{
"code": null,
"e": 12366,
"s": 12231,
"text": "Since the edges are not weighted, we can represent the problem with an adjacency matrix of shape (n,n) where n is the number of nodes."
},
{
"code": null,
"e": 12441,
"s": 12366,
"text": "So, for instance, the precedent graph is encoded in the following matrix :"
},
{
"code": null,
"e": 12604,
"s": 12441,
"text": "ADJ_MAT = [ [0 , 0 , 1, 0, 0, 0], [0 , 0 , 1, 0, 0, 0], [1 , 1 , 0, 1, 0, 0], [0 , 0 , 1, 0, 1, 0], [0 , 0 , 0, 1, 0, 1], [0 , 0 , 0, 0, 1, 0],]"
},
{
"code": null,
"e": 12737,
"s": 12604,
"text": "(Now, I advise you to stop reading and to try to write the MIP formulation for the Vertex Cover Problem to check your understanding)"
},
{
"code": null,
"e": 12797,
"s": 12737,
"text": "Now letβs think about the formulation we are going to use :"
},
{
"code": null,
"e": 12830,
"s": 12797,
"text": "What are the decision variables?"
},
{
"code": null,
"e": 12989,
"s": 12830,
"text": "We are trying to decide for each vertex if we take it or not in the cover, so we have n binary variables, indicating whether we take the corresponding vertex."
},
{
"code": null,
"e": 13029,
"s": 12989,
"text": "We can create the variables as follows:"
},
{
"code": null,
"e": 13231,
"s": 13029,
"text": "#WARNING : Everything on Julia is indexed by default starting from #1.n = size(ADJ_MAT)[1] #We create a vector of variables indexed by 1 prefixed by x (x1, x2, ..., xn)@variable(prgrm2, 0<=x[1:n], Int)"
},
{
"code": null,
"e": 13257,
"s": 13231,
"text": "What are the constraints?"
},
{
"code": null,
"e": 13367,
"s": 13257,
"text": "A feasible solution must cover each edge, so we have to take one vertex or the other (or both) for each edge."
},
{
"code": null,
"e": 13419,
"s": 13367,
"text": "These constraints can be created simply like this :"
},
{
"code": null,
"e": 13600,
"s": 13419,
"text": "for i in 1:n for j in 1:n if(ADJ_MAT[i,j] == 1) c = @constraint(prgrm2, x[i] + x[j] >= 1) set_name(c,\"C\") println(c) end endend"
},
{
"code": null,
"e": 13624,
"s": 13600,
"text": "What are we optimising?"
},
{
"code": null,
"e": 13698,
"s": 13624,
"text": "The objective is to minimise the number of vertices we take in the cover:"
},
{
"code": null,
"e": 13733,
"s": 13698,
"text": "which can be generated like this :"
},
{
"code": null,
"e": 13792,
"s": 13733,
"text": "@objective(prgrm2, Min, sum(x))#Output : x1+x2+x3+x4+x5+x6"
},
{
"code": null,
"e": 13833,
"s": 13792,
"text": "So the MIP formulation is the following:"
},
{
"code": null,
"e": 13870,
"s": 13833,
"text": "Which gives the following solution :"
},
{
"code": null,
"e": 13907,
"s": 13870,
"text": "Which can be interpreted as follows:"
},
{
"code": null,
"e": 14103,
"s": 13907,
"text": "In this part, I will present two ways of computing a feasible solution for the vertex cover problem; these two algorithms have a fascinating property: approximations with a performance guarantee."
},
{
"code": null,
"e": 14122,
"s": 14103,
"text": "Greedy algorithm :"
},
{
"code": null,
"e": 14230,
"s": 14122,
"text": "This algorithm consists of taking each edge both endpoints and removing all the covered edges at each step."
},
{
"code": null,
"e": 14363,
"s": 14230,
"text": "The greedy algorithm is a 2-approximation which means it never return a solution that is more than two times worst than the optimal."
},
{
"code": null,
"e": 14487,
"s": 14363,
"text": "The proof is straightforward once you notice that you take two vertexes where one would have been enough in the worst case."
},
{
"code": null,
"e": 14522,
"s": 14487,
"text": "Rounding up a fractional solution:"
},
{
"code": null,
"e": 14687,
"s": 14522,
"text": "The vertex cover problem has another interesting property: itβs a βhalf-integral problemβ, which means that even in its relaxation, the variables are 0 or 1 or 1/2."
},
{
"code": null,
"e": 14950,
"s": 14687,
"text": "Another way of getting an approximation of the solution is to round up a fractional solution by turning the 1/2 to ones, which will give us a feasible solution because the fractional was already fulfilling the constraints, and we increased some of its variables."
},
{
"code": null,
"e": 15036,
"s": 14950,
"text": "(for the full proofs of the validity of the two approaches, you can read this course)"
},
{
"code": null,
"e": 15113,
"s": 15036,
"text": "Now, how can we tell our solver to call a heuristic at each fractional node?"
},
{
"code": null,
"e": 15156,
"s": 15113,
"text": "To do so, you have to understand 3 things:"
},
{
"code": null,
"e": 15226,
"s": 15156,
"text": "How can you get the solver's current solution values in the Callback?"
},
{
"code": null,
"e": 15310,
"s": 15226,
"text": "How can you submit your heuristic solution after constructing it from the Callback?"
},
{
"code": null,
"e": 15377,
"s": 15310,
"text": "How can you register your Callback so that the solver will use it?"
},
{
"code": null,
"e": 15488,
"s": 15377,
"text": "And I will explain to you each of these aspects in the following example of using the round-up approximation :"
},
{
"code": null,
"e": 15585,
"s": 15488,
"text": "The first step you have to design your callback; inside your callback, you can use two methods :"
},
{
"code": null,
"e": 15692,
"s": 15585,
"text": "callback_value(cb_data, x) to get from the callback data the value of a variable (and only one at a time)."
},
{
"code": null,
"e": 15903,
"s": 15692,
"text": "MOI.submit( model, MOI.HeuristicSolution(cb_data), [x], [v] ) : this method submit the solution x=v and returns the status of the solution which can either be βacceptedβ βrejectedβ (by the solver) or βunknownβ."
},
{
"code": null,
"e": 15972,
"s": 15903,
"text": "So for our round-up approximation, here is the callback we propose :"
},
{
"code": null,
"e": 16473,
"s": 15972,
"text": "function my_callback_function(cb_data) println(\"Call to callback\") new_sol = [] precedent = [callback_value(cb_data,x_k ) for x_k in x] for x_i in x x_val = callback_value(cb_data, x_i) x_new = ceil(Int, x_val) append!(new_sol, x_new) end println(\"Precedent: \", precedent) println(\"New: \",new_sol) status = MOI.submit( mod, MOI.HeuristicSolution(cb_data), [x_i for x_i in x], [floor(Int, k) for k in new_sol] ) println(\"status = \", status)end"
},
{
"code": null,
"e": 16539,
"s": 16473,
"text": "I added the print statements to track the calls to the heuristic."
},
{
"code": null,
"e": 16570,
"s": 16539,
"text": "Now we register our callback :"
},
{
"code": null,
"e": 16630,
"s": 16570,
"text": "MOI.set(mod, MOI.HeuristicCallback(), my_callback_function)"
},
{
"code": null,
"e": 16689,
"s": 16630,
"text": "So when executing the optimization step, we can see this :"
},
{
"code": null,
"e": 16962,
"s": 16689,
"text": "The rejected solutions after the first are because the rounding up procedure is quickly not sufficient in terms of efficiency to beat the integer solutions produced by the solver, so the solutions it proposes are rejected, but still, it was useful in the first iterations."
},
{
"code": null,
"e": 17234,
"s": 16962,
"text": "When you design a solution, you have to choose between an exact or an approached solution. Still, as we saw, provided a good intuition on the specific problem you want to solve and a good understanding of a solver's internal behaviour, we can get the best of both worlds."
}
]
|
Combine Rows into String in SQL Server - GeeksforGeeks | 09 Mar, 2021
Imagine we need to select all the data from any given list. We could use multiple queries to combine rows in SQL Server to form a String.
Example-1 :Let us suppose we have below table named βgeek_demoβ β
Approach-1 :In the below example, we will combine rows using the COALESCE Function.
Query to Concatenate Rows in SQL Server β
DECLARE @Names VARCHAR(MAX)
SELECT @Names = COALESCE(@Names + ', ', '') + [FirstName]
FROM [geek_demo]
SELECT @Names AS [List of All Names]
Output :
Approach-2 :In the below example, we will combine the LastName rows also.
Query to Concatenate Rows in SQL Server β
DECLARE @FirstNames VARCHAR(MAX)
DECLARE @LastNames VARCHAR(MAX)
SELECT @FirstNames = COALESCE(@FirstNames + ', ', '') + [FirstName]
FROM [geek_demo]
SELECT @LastNames = COALESCE(@LastNames + ', ', '') + [LastName]
FROM [geek_demo]
SELECT @FirstNames AS [List of All First Names],
@LastNames AS [List of All Last Names]
Output :
Approach-3 :In the below example, we will concatenate the Last Name rows as well.
Query to Concatenate Rows in SQL Server β
DECLARE @FirstNames VARCHAR(MAX)
DECLARE @LastNames VARCHAR(MAX)
SELECT @FirstNames = CONCAT(@FirstNames + ', ', '') + [FirstName]
FROM [geek_demo]
SELECT @LastNames = CONCAT(@LastNames + ', ', '') + [LastName]
FROM [geek_demo]
SELECT @FirstNames AS [List of First All Names],
@LastNames AS [List of All Last Names]
Output :
Approach-4 :In the below example, we will combine the rows from two columns (FirstName & LastName) using the stuff function and for the XML path.
Query to Concatenate Rows in SQL Server β
SELECT STUFF((
SELECT ',' + SPACE(1) + [FirstName],
' ' + SPACE(1) + [LastName]
FROM [geek_demo]
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')
AS [List Of All Names]
Output :
Example-2 :Let us suppose we have below table named βgeek_demo1β β
Approach-1 :In the below example, we will combine rows into a string using the CONCAT Function in SQL Server.
Query to Concatenate Rows in SQL Server β
DECLARE @Names VARCHAR(MAX)
DECLARE @Emails VARCHAR(MAX)
SELECT @Names = CONCAT(@Names + ', ', '') + [Name]
FROM [geek_demo1]
SELECT @Emails = CONCAT(@Emails + ', ', '') + [Email]
FROM [geek_demo]
SELECT @Names AS [List of All Names],
@Emails AS [List of All Emails]
Output :
Approach-2 :In the below example, we will combine rows in SQL Server using the SPACE and for XML path.
Query to Concatenate Rows in SQL Server β
SELECT STUFF((
SELECT ',' + SPACE(1) + [Email]
FROM [geek_demo]
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')
AS [List Of All Emails]
Output :
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of ER Model
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
SQL Trigger | Student Database
SQL | Views | [
{
"code": null,
"e": 24013,
"s": 23985,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 24152,
"s": 24013,
"text": "Imagine we need to select all the data from any given list. We could use multiple queries to combine rows in SQL Server to form a String. "
},
{
"code": null,
"e": 24218,
"s": 24152,
"text": "Example-1 :Let us suppose we have below table named βgeek_demoβ β"
},
{
"code": null,
"e": 24302,
"s": 24218,
"text": "Approach-1 :In the below example, we will combine rows using the COALESCE Function."
},
{
"code": null,
"e": 24344,
"s": 24302,
"text": "Query to Concatenate Rows in SQL Server β"
},
{
"code": null,
"e": 24487,
"s": 24344,
"text": "DECLARE @Names VARCHAR(MAX) \nSELECT @Names = COALESCE(@Names + ', ', '') + [FirstName] \nFROM [geek_demo]\nSELECT @Names AS [List of All Names]"
},
{
"code": null,
"e": 24496,
"s": 24487,
"text": "Output :"
},
{
"code": null,
"e": 24570,
"s": 24496,
"text": "Approach-2 :In the below example, we will combine the LastName rows also."
},
{
"code": null,
"e": 24612,
"s": 24570,
"text": "Query to Concatenate Rows in SQL Server β"
},
{
"code": null,
"e": 24950,
"s": 24612,
"text": "DECLARE @FirstNames VARCHAR(MAX)\nDECLARE @LastNames VARCHAR(MAX)\nSELECT @FirstNames = COALESCE(@FirstNames + ', ', '') + [FirstName] \nFROM [geek_demo] \nSELECT @LastNames = COALESCE(@LastNames + ', ', '') + [LastName] \nFROM [geek_demo] \nSELECT @FirstNames AS [List of All First Names],\n @LastNames AS [List of All Last Names]"
},
{
"code": null,
"e": 24959,
"s": 24950,
"text": "Output :"
},
{
"code": null,
"e": 25041,
"s": 24959,
"text": "Approach-3 :In the below example, we will concatenate the Last Name rows as well."
},
{
"code": null,
"e": 25083,
"s": 25041,
"text": "Query to Concatenate Rows in SQL Server β"
},
{
"code": null,
"e": 25406,
"s": 25083,
"text": "DECLARE @FirstNames VARCHAR(MAX)\nDECLARE @LastNames VARCHAR(MAX)\nSELECT @FirstNames = CONCAT(@FirstNames + ', ', '') + [FirstName] \nFROM [geek_demo] \nSELECT @LastNames = CONCAT(@LastNames + ', ', '') + [LastName] \nFROM [geek_demo]\nSELECT @FirstNames AS [List of First All Names],\n @LastNames AS [List of All Last Names]"
},
{
"code": null,
"e": 25415,
"s": 25406,
"text": "Output :"
},
{
"code": null,
"e": 25561,
"s": 25415,
"text": "Approach-4 :In the below example, we will combine the rows from two columns (FirstName & LastName) using the stuff function and for the XML path."
},
{
"code": null,
"e": 25603,
"s": 25561,
"text": "Query to Concatenate Rows in SQL Server β"
},
{
"code": null,
"e": 25794,
"s": 25603,
"text": "SELECT STUFF((\n SELECT ',' + SPACE(1) + [FirstName],\n ' ' + SPACE(1) + [LastName]\n FROM [geek_demo]\n FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')\nAS [List Of All Names]"
},
{
"code": null,
"e": 25803,
"s": 25794,
"text": "Output :"
},
{
"code": null,
"e": 25870,
"s": 25803,
"text": "Example-2 :Let us suppose we have below table named βgeek_demo1β β"
},
{
"code": null,
"e": 25980,
"s": 25870,
"text": "Approach-1 :In the below example, we will combine rows into a string using the CONCAT Function in SQL Server."
},
{
"code": null,
"e": 26022,
"s": 25980,
"text": "Query to Concatenate Rows in SQL Server β"
},
{
"code": null,
"e": 26307,
"s": 26022,
"text": "DECLARE @Names VARCHAR(MAX)\nDECLARE @Emails VARCHAR(MAX)\nSELECT @Names = CONCAT(@Names + ', ', '') + [Name] \nFROM [geek_demo1] \nSELECT @Emails = CONCAT(@Emails + ', ', '') + [Email] \nFROM [geek_demo] \nSELECT @Names AS [List of All Names],\n @Emails AS [List of All Emails]"
},
{
"code": null,
"e": 26316,
"s": 26307,
"text": "Output :"
},
{
"code": null,
"e": 26419,
"s": 26316,
"text": "Approach-2 :In the below example, we will combine rows in SQL Server using the SPACE and for XML path."
},
{
"code": null,
"e": 26461,
"s": 26419,
"text": "Query to Concatenate Rows in SQL Server β"
},
{
"code": null,
"e": 26617,
"s": 26461,
"text": "SELECT STUFF((\n SELECT ',' + SPACE(1) + [Email]\n FROM [geek_demo]\n FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')\nAS [List Of All Emails]"
},
{
"code": null,
"e": 26626,
"s": 26617,
"text": "Output :"
},
{
"code": null,
"e": 26637,
"s": 26626,
"text": "SQL-Server"
},
{
"code": null,
"e": 26642,
"s": 26637,
"text": "DBMS"
},
{
"code": null,
"e": 26646,
"s": 26642,
"text": "SQL"
},
{
"code": null,
"e": 26651,
"s": 26646,
"text": "DBMS"
},
{
"code": null,
"e": 26655,
"s": 26651,
"text": "SQL"
},
{
"code": null,
"e": 26753,
"s": 26655,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26762,
"s": 26753,
"text": "Comments"
},
{
"code": null,
"e": 26775,
"s": 26762,
"text": "Old Comments"
},
{
"code": null,
"e": 26806,
"s": 26775,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 26829,
"s": 26806,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 26882,
"s": 26829,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 26940,
"s": 26882,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 26965,
"s": 26940,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 27007,
"s": 26965,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 27051,
"s": 27007,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 27072,
"s": 27051,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 27103,
"s": 27072,
"text": "SQL Trigger | Student Database"
}
]
|
Write a program in Python to read sample data from an SQL Database | Assume you have a sqlite3 database with student records and the result for reading all the data is,
Id Name
0 1 stud1
1 2 stud2
2 3 stud3
3 4 stud4
4 5 stud5
To solve this, we will follow the steps given below β
Define a new connection. It is shown below,
Define a new connection. It is shown below,
con = sqlite3.connect("db.sqlite3")
Read sql data from the database using below function,
Read sql data from the database using below function,
pd.read_sql_query()
Select all student data from table using read_sql_query with connection,
Select all student data from table using read_sql_query with connection,
pd.read_sql_query("SELECT * FROM student", con)
Let us see the complete implementation to get a better understanding β
import pandas as pd
import sqlite3
con = sqlite3.connect("db.sqlite3")
df = pd.read_sql_query("SELECT * FROM student", con)
print(df)
Id Name
0 1 stud1
1 2 stud2
2 3 stud3
3 4 stud4
4 5 stud5 | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "Assume you have a sqlite3 database with student records and the result for reading all the data is,"
},
{
"code": null,
"e": 1222,
"s": 1162,
"text": " Id Name\n0 1 stud1\n1 2 stud2\n2 3 stud3\n3 4 stud4\n4 5 stud5"
},
{
"code": null,
"e": 1276,
"s": 1222,
"text": "To solve this, we will follow the steps given below β"
},
{
"code": null,
"e": 1320,
"s": 1276,
"text": "Define a new connection. It is shown below,"
},
{
"code": null,
"e": 1364,
"s": 1320,
"text": "Define a new connection. It is shown below,"
},
{
"code": null,
"e": 1400,
"s": 1364,
"text": "con = sqlite3.connect(\"db.sqlite3\")"
},
{
"code": null,
"e": 1454,
"s": 1400,
"text": "Read sql data from the database using below function,"
},
{
"code": null,
"e": 1508,
"s": 1454,
"text": "Read sql data from the database using below function,"
},
{
"code": null,
"e": 1528,
"s": 1508,
"text": "pd.read_sql_query()"
},
{
"code": null,
"e": 1601,
"s": 1528,
"text": "Select all student data from table using read_sql_query with connection,"
},
{
"code": null,
"e": 1674,
"s": 1601,
"text": "Select all student data from table using read_sql_query with connection,"
},
{
"code": null,
"e": 1722,
"s": 1674,
"text": "pd.read_sql_query(\"SELECT * FROM student\", con)"
},
{
"code": null,
"e": 1793,
"s": 1722,
"text": "Let us see the complete implementation to get a better understanding β"
},
{
"code": null,
"e": 1927,
"s": 1793,
"text": "import pandas as pd\nimport sqlite3\ncon = sqlite3.connect(\"db.sqlite3\")\ndf = pd.read_sql_query(\"SELECT * FROM student\", con)\nprint(df)"
},
{
"code": null,
"e": 1987,
"s": 1927,
"text": " Id Name\n0 1 stud1\n1 2 stud2\n2 3 stud3\n3 4 stud4\n4 5 stud5"
}
]
|
Find the number of good permutations - GeeksforGeeks | 20 May, 2021
Given two integers N and K. The task is to find the number of good permutations of the first N natural numbers. A permutation is called good if there exist at least N β K indices i (1 β€ i β€ N) such that Pi = i.
Examples:
Input: N = 4, K = 1 Output: 1 {1, 2, 3, 4} is the only possible good permutation.
Input: N = 5, K = 2 Output: 11
Approach: Letβs iterate on m which is the number of indices such that Pi does not equal i. Obviously, 0 β€ m β€ k. In order to count the number of permutations with fixed m, we need to choose the indices that have the property Pi not equals to i β there are nCm ways to do this, then we need to construct a permutation Q for chosen indices such that for every chosen index Qi is not equaled to i. Permutations with this property are called derangements and the number of derangements of fixed size can be calculated using an exhaustive search for m β€ 4.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of good permutationsint Permutations(int n, int k){ // For m = 0, ans is 1 int ans = 1; // If k is greater than 1 if (k >= 2) ans += (n) * (n - 1) / 2; // If k is greater than 2 if (k >= 3) ans += (n) * (n - 1) * (n - 2) * 2 / 6; // If k is greater than 3 if (k >= 4) ans += (n) * (n - 1) * (n - 2) * (n - 3) * 9 / 24; return ans;} // Driver codeint main(){ int n = 5, k = 2; cout << Permutations(n, k); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the count of good permutationsstatic int Permutations(int n, int k){ // For m = 0, ans is 1 int ans = 1; // If k is greater than 1 if (k >= 2) ans += (n) * (n - 1) / 2; // If k is greater than 2 if (k >= 3) ans += (n) * (n - 1) * (n - 2) * 2 / 6; // If k is greater than 3 if (k >= 4) ans += (n) * (n - 1) * (n - 2) * (n - 3) * 9 / 24; return ans;} // Driver codepublic static void main(String[] args){ int n = 5, k = 2; System.out.println(Permutations(n, k));}} // This code contributed by Rajput-Ji
# Python3 implementation of the approach # Function to return the count# of good permutationsdef Permutations(n, k): # For m = 0, ans is 1 ans = 1 # If k is greater than 1 if k >= 2: ans += (n) * (n - 1) // 2 # If k is greater than 2 if k >= 3: ans += ((n) * (n - 1) * (n - 2) * 2 // 6) # If k is greater than 3 if k >= 4: ans += ((n) * (n - 1) * (n - 2) * (n - 3) * 9 // 24) return ans # Driver codeif __name__ == "__main__": n, k = 5, 2 print(Permutations(n, k)) # This code is contributed# by Rituraj Jain
// C# implementation of the above approach.using System; class GFG{ // Function to return the count of good permutationsstatic int Permutations(int n, int k){ // For m = 0, ans is 1 int ans = 1; // If k is greater than 1 if (k >= 2) ans += (n) * (n - 1) / 2; // If k is greater than 2 if (k >= 3) ans += (n) * (n - 1) * (n - 2) * 2 / 6; // If k is greater than 3 if (k >= 4) ans += (n) * (n - 1) * (n - 2) * (n - 3) * 9 / 24; return ans;} // Driver codepublic static void Main(){ int n = 5, k = 2; Console.WriteLine(Permutations(n, k));}} /* This code contributed by PrinciRaj1992 */
<?php// PHP implementation of the approach // Function to return the count// of good permutationsfunction Permutations($n, $k){ // For m = 0, ans is 1 $ans = 1; // If k is greater than 1 if ($k >= 2) $ans += ($n) * ($n - 1) / 2; // If k is greater than 2 if ($k >= 3) $ans += ($n) * ($n - 1) * ($n - 2) * 2 / 6; // If k is greater than 3 if ($k >= 4) $ans += ($n) * ($n - 1) * ($n - 2) * ($n - 3) * 9 / 24; return $ans;} // Driver code$n = 5; $k = 2;echo(Permutations($n, $k)); // This code contributed by Code_Mech.?>
<script> // JavaScript implementation of the approach // Function to return the count of good permutationsfunction Permutations(n, k){ // For m = 0, ans is 1 var ans = 1; // If k is greater than 1 if (k >= 2) ans += (n) * (n - 1) / 2; // If k is greater than 2 if (k >= 3) ans += (n) * (n - 1) * (n - 2) * 2 / 6; // If k is greater than 3 if (k >= 4) ans += (n) * (n - 1) * (n - 2) * (n - 3) * 9 / 24; return ans;} // Driver Codevar n = 5, k = 2;document.write(Permutations(n, k)); // This code is contributed by Khushboogoyal499 </script>
11
rituraj_jain
Rajput-Ji
princiraj1992
Code_Mech
khushboogoyal499
Numbers
permutation
Combinatorial
Mathematical
Mathematical
Numbers
permutation
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Combinational Sum
Lexicographic rank of a string
Count of subsets with sum equal to X
Print all permutations in sorted (lexicographic) order
Print all possible strings of length k that can be formed from a set of n characters
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 25069,
"s": 25041,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 25280,
"s": 25069,
"text": "Given two integers N and K. The task is to find the number of good permutations of the first N natural numbers. A permutation is called good if there exist at least N β K indices i (1 β€ i β€ N) such that Pi = i."
},
{
"code": null,
"e": 25291,
"s": 25280,
"text": "Examples: "
},
{
"code": null,
"e": 25373,
"s": 25291,
"text": "Input: N = 4, K = 1 Output: 1 {1, 2, 3, 4} is the only possible good permutation."
},
{
"code": null,
"e": 25405,
"s": 25373,
"text": "Input: N = 5, K = 2 Output: 11 "
},
{
"code": null,
"e": 25957,
"s": 25405,
"text": "Approach: Letβs iterate on m which is the number of indices such that Pi does not equal i. Obviously, 0 β€ m β€ k. In order to count the number of permutations with fixed m, we need to choose the indices that have the property Pi not equals to i β there are nCm ways to do this, then we need to construct a permutation Q for chosen indices such that for every chosen index Qi is not equaled to i. Permutations with this property are called derangements and the number of derangements of fixed size can be calculated using an exhaustive search for m β€ 4."
},
{
"code": null,
"e": 26009,
"s": 25957,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26013,
"s": 26009,
"text": "C++"
},
{
"code": null,
"e": 26018,
"s": 26013,
"text": "Java"
},
{
"code": null,
"e": 26026,
"s": 26018,
"text": "Python3"
},
{
"code": null,
"e": 26029,
"s": 26026,
"text": "C#"
},
{
"code": null,
"e": 26033,
"s": 26029,
"text": "PHP"
},
{
"code": null,
"e": 26044,
"s": 26033,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of good permutationsint Permutations(int n, int k){ // For m = 0, ans is 1 int ans = 1; // If k is greater than 1 if (k >= 2) ans += (n) * (n - 1) / 2; // If k is greater than 2 if (k >= 3) ans += (n) * (n - 1) * (n - 2) * 2 / 6; // If k is greater than 3 if (k >= 4) ans += (n) * (n - 1) * (n - 2) * (n - 3) * 9 / 24; return ans;} // Driver codeint main(){ int n = 5, k = 2; cout << Permutations(n, k); return 0;}",
"e": 26635,
"s": 26044,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the count of good permutationsstatic int Permutations(int n, int k){ // For m = 0, ans is 1 int ans = 1; // If k is greater than 1 if (k >= 2) ans += (n) * (n - 1) / 2; // If k is greater than 2 if (k >= 3) ans += (n) * (n - 1) * (n - 2) * 2 / 6; // If k is greater than 3 if (k >= 4) ans += (n) * (n - 1) * (n - 2) * (n - 3) * 9 / 24; return ans;} // Driver codepublic static void main(String[] args){ int n = 5, k = 2; System.out.println(Permutations(n, k));}} // This code contributed by Rajput-Ji",
"e": 27265,
"s": 26635,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count# of good permutationsdef Permutations(n, k): # For m = 0, ans is 1 ans = 1 # If k is greater than 1 if k >= 2: ans += (n) * (n - 1) // 2 # If k is greater than 2 if k >= 3: ans += ((n) * (n - 1) * (n - 2) * 2 // 6) # If k is greater than 3 if k >= 4: ans += ((n) * (n - 1) * (n - 2) * (n - 3) * 9 // 24) return ans # Driver codeif __name__ == \"__main__\": n, k = 5, 2 print(Permutations(n, k)) # This code is contributed# by Rituraj Jain",
"e": 27874,
"s": 27265,
"text": null
},
{
"code": "// C# implementation of the above approach.using System; class GFG{ // Function to return the count of good permutationsstatic int Permutations(int n, int k){ // For m = 0, ans is 1 int ans = 1; // If k is greater than 1 if (k >= 2) ans += (n) * (n - 1) / 2; // If k is greater than 2 if (k >= 3) ans += (n) * (n - 1) * (n - 2) * 2 / 6; // If k is greater than 3 if (k >= 4) ans += (n) * (n - 1) * (n - 2) * (n - 3) * 9 / 24; return ans;} // Driver codepublic static void Main(){ int n = 5, k = 2; Console.WriteLine(Permutations(n, k));}} /* This code contributed by PrinciRaj1992 */",
"e": 28516,
"s": 27874,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the count// of good permutationsfunction Permutations($n, $k){ // For m = 0, ans is 1 $ans = 1; // If k is greater than 1 if ($k >= 2) $ans += ($n) * ($n - 1) / 2; // If k is greater than 2 if ($k >= 3) $ans += ($n) * ($n - 1) * ($n - 2) * 2 / 6; // If k is greater than 3 if ($k >= 4) $ans += ($n) * ($n - 1) * ($n - 2) * ($n - 3) * 9 / 24; return $ans;} // Driver code$n = 5; $k = 2;echo(Permutations($n, $k)); // This code contributed by Code_Mech.?>",
"e": 29131,
"s": 28516,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the count of good permutationsfunction Permutations(n, k){ // For m = 0, ans is 1 var ans = 1; // If k is greater than 1 if (k >= 2) ans += (n) * (n - 1) / 2; // If k is greater than 2 if (k >= 3) ans += (n) * (n - 1) * (n - 2) * 2 / 6; // If k is greater than 3 if (k >= 4) ans += (n) * (n - 1) * (n - 2) * (n - 3) * 9 / 24; return ans;} // Driver Codevar n = 5, k = 2;document.write(Permutations(n, k)); // This code is contributed by Khushboogoyal499 </script>",
"e": 29760,
"s": 29131,
"text": null
},
{
"code": null,
"e": 29763,
"s": 29760,
"text": "11"
},
{
"code": null,
"e": 29778,
"s": 29765,
"text": "rituraj_jain"
},
{
"code": null,
"e": 29788,
"s": 29778,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29802,
"s": 29788,
"text": "princiraj1992"
},
{
"code": null,
"e": 29812,
"s": 29802,
"text": "Code_Mech"
},
{
"code": null,
"e": 29829,
"s": 29812,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 29837,
"s": 29829,
"text": "Numbers"
},
{
"code": null,
"e": 29849,
"s": 29837,
"text": "permutation"
},
{
"code": null,
"e": 29863,
"s": 29849,
"text": "Combinatorial"
},
{
"code": null,
"e": 29876,
"s": 29863,
"text": "Mathematical"
},
{
"code": null,
"e": 29889,
"s": 29876,
"text": "Mathematical"
},
{
"code": null,
"e": 29897,
"s": 29889,
"text": "Numbers"
},
{
"code": null,
"e": 29909,
"s": 29897,
"text": "permutation"
},
{
"code": null,
"e": 29923,
"s": 29909,
"text": "Combinatorial"
},
{
"code": null,
"e": 30021,
"s": 29923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30039,
"s": 30021,
"text": "Combinational Sum"
},
{
"code": null,
"e": 30070,
"s": 30039,
"text": "Lexicographic rank of a string"
},
{
"code": null,
"e": 30107,
"s": 30070,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 30162,
"s": 30107,
"text": "Print all permutations in sorted (lexicographic) order"
},
{
"code": null,
"e": 30247,
"s": 30162,
"text": "Print all possible strings of length k that can be formed from a set of n characters"
},
{
"code": null,
"e": 30277,
"s": 30247,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30292,
"s": 30277,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30335,
"s": 30292,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30354,
"s": 30335,
"text": "Coin Change | DP-7"
}
]
|
Length of minimized Compressed String - GeeksforGeeks | 31 Mar, 2022
Given a string S, the task is to find the length of the shortest compressed string. The string can be compressed in the following way:
If S = βABCDABCDβ, then the string can be compressed as (ABCD)2, so the length of the compressed string will be 4.
If S = βAABBCCDDβ then the string compressed form will be A2B2C2D2 therefore, the length of the compressed string will be 4.
Examples:
Input: S = βaabaβOutput: 3Explanation : It can be rewritten as a2ba therefore the answer will be 3.
Input: S = βaaabaaabccdaaabaaabccdβOutput: 4Explanation: The string can be rewritten as (((a)3b)2(c)2d)2. Therefore, the answer will be 4.
Approach: The problem can be solved using dynamic programming because it has Optimal Substructure and Overlapping Subproblems. Follow the steps below to solve the problem:
Initialize a dp[][] vector, where dp[i][j] stores the length of compressed substring s[i], s[i+1], ..., s[j].
Iterate in the range [1, N] using the variable l and perform the following steps: Iterate in the range [0, N-l] using the variable i and perform the following steps:Initialize a variable say, j as i+l-1. If i is equal to j, then update dp[i][j] as 1 and continue.Iterate in the range [i, j-1] using the variable k and update dp[i][j] as min of dp[i][j] and dp[i][k] + dp[k][j].Initialize a variable say, temp as s.substr(i, l).Then, find the longest prefix that is also the suffix of the substring temp.If the substring is of the form of dp[i][k]^n(l%(l β pref[l-1]) = 0), then update the value of dp[i][j] as min(dp[i][j], dp[i][i + (l-pref[l-1] β 1)]).
Iterate in the range [0, N-l] using the variable i and perform the following steps:Initialize a variable say, j as i+l-1. If i is equal to j, then update dp[i][j] as 1 and continue.Iterate in the range [i, j-1] using the variable k and update dp[i][j] as min of dp[i][j] and dp[i][k] + dp[k][j].Initialize a variable say, temp as s.substr(i, l).Then, find the longest prefix that is also the suffix of the substring temp.If the substring is of the form of dp[i][k]^n(l%(l β pref[l-1]) = 0), then update the value of dp[i][j] as min(dp[i][j], dp[i][i + (l-pref[l-1] β 1)]).
Initialize a variable say, j as i+l-1.
If i is equal to j, then update dp[i][j] as 1 and continue.
Iterate in the range [i, j-1] using the variable k and update dp[i][j] as min of dp[i][j] and dp[i][k] + dp[k][j].
Initialize a variable say, temp as s.substr(i, l).
Then, find the longest prefix that is also the suffix of the substring temp.
If the substring is of the form of dp[i][k]^n(l%(l β pref[l-1]) = 0), then update the value of dp[i][j] as min(dp[i][j], dp[i][i + (l-pref[l-1] β 1)]).
Finally, print the value of dp[0][N-1] as the answer.
Below is the implementation of the above approach:
C++
Python3
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Prefix function to calculate// longest prefix that is also// the suffix of the substring Svector<int> prefix_function(string s){ int n = (int)s.length(); vector<int> pi(n); for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi;} // Function to find the length of the// shortest compressed stringvoid minLength(string s, int n){ // Declare a 2D dp vector vector<vector<int> > dp(n + 1, vector<int>(n + 1, 10000)); // Traversing substring on the basis of length for (int l = 1; l <= n; l++) { // For loop for each substring of length l for (int i = 0; i < n - l + 1; i++) { // Second substring coordinate int j = i + l - 1; // If the length of the string is 1 // then dp[i][j] = 1 if (i == j) { dp[i][j] = 1; continue; } // Finding smallest dp[i][j] value // by breaking it in two substrings for (int k = i; k < j; k++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]); } // Substring starting with i of length L string temp = s.substr(i, l); // Prefix function of the substring temp auto pref = prefix_function(temp); // Checking if the substring is // of the form of dp[i][k]^n if (l % (l - pref[l - 1]) == 0) { // If yes, check if dp[i][k] is // less than dp[i][j] dp[i][j] = min(dp[i][j], dp[i][i + (l - pref[l - 1] - 1)]); } } } // Finally, print the required answer cout << dp[0][n - 1] << endl;} // Driver Codeint main(){ // Given Input int n = 4; string s = "aaba"; // Function Call minLength(s, n);}
# Python program for the above approach # Prefix function to calculate# longest prefix that is also# the suffix of the substring Sdef prefix_function(s): n = len(s) pi = [0 for i in range(n)] for i in range(1,n): j = pi[i - 1] while (j > 0 and s[i] != s[j]): j = pi[j - 1] if (s[i] == s[j]): j += 1 pi[i] = j return pi # Function to find the length of the# shortest compressed stringdef minLength(s,n): # Declare a 2D dp vector dp = [[10000 for col in range(n+1)] for row in range(n + 1)] # Traversing substring on the basis of length for l in range(1,n+1): # For loop for each substring of length l for i in range(n - l + 1): # Second substring coordinate j = i + l - 1 # If the length of the string is 1 # then dp[i][j] = 1 if (i == j): dp[i][j] = 1 continue # Finding smallest dp[i][j] value # by breaking it in two substrings for k in range(i,j): dp[i][j] = min(dp[i][j],dp[i][k] + dp[k + 1][j]) # Substring starting with i of length L temp = s[i:i+l] # Prefix function of the substring temp pref = prefix_function(temp) # Checking if the substring is # of the form of dp[i][k]^n if (l % (l - pref[l - 1]) == 0): # If yes, check if dp[i][k] is # less than dp[i][j] dp[i][j] = min(dp[i][j],dp[i][i + (l - pref[l - 1] - 1)]) # Finally, print the required answer print(dp[0][n - 1]) # Driver Code # Given Inputn = 4s = "aaba" # Function CallminLength(s, n) # This code is contributed by shinjanpatra
3
Time Complexity: O(N^3)Auxiliary Space: O(N^2)
shinjanpatra
Dynamic Programming
Strings
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Optimal Substructure Property in Dynamic Programming | DP-2
Maximum sum such that no two elements are adjacent
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Gold Mine Problem
Reverse a string in Java
Write a program to reverse an array or string
Write a program to print all permutations of a given string
C++ Data Types
Python program to check if a string is palindrome or not | [
{
"code": null,
"e": 24281,
"s": 24253,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 24416,
"s": 24281,
"text": "Given a string S, the task is to find the length of the shortest compressed string. The string can be compressed in the following way:"
},
{
"code": null,
"e": 24531,
"s": 24416,
"text": "If S = βABCDABCDβ, then the string can be compressed as (ABCD)2, so the length of the compressed string will be 4."
},
{
"code": null,
"e": 24656,
"s": 24531,
"text": "If S = βAABBCCDDβ then the string compressed form will be A2B2C2D2 therefore, the length of the compressed string will be 4."
},
{
"code": null,
"e": 24666,
"s": 24656,
"text": "Examples:"
},
{
"code": null,
"e": 24766,
"s": 24666,
"text": "Input: S = βaabaβOutput: 3Explanation : It can be rewritten as a2ba therefore the answer will be 3."
},
{
"code": null,
"e": 24906,
"s": 24766,
"text": "Input: S = βaaabaaabccdaaabaaabccdβOutput: 4Explanation: The string can be rewritten as (((a)3b)2(c)2d)2. Therefore, the answer will be 4. "
},
{
"code": null,
"e": 25078,
"s": 24906,
"text": "Approach: The problem can be solved using dynamic programming because it has Optimal Substructure and Overlapping Subproblems. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25188,
"s": 25078,
"text": "Initialize a dp[][] vector, where dp[i][j] stores the length of compressed substring s[i], s[i+1], ..., s[j]."
},
{
"code": null,
"e": 25843,
"s": 25188,
"text": "Iterate in the range [1, N] using the variable l and perform the following steps: Iterate in the range [0, N-l] using the variable i and perform the following steps:Initialize a variable say, j as i+l-1. If i is equal to j, then update dp[i][j] as 1 and continue.Iterate in the range [i, j-1] using the variable k and update dp[i][j] as min of dp[i][j] and dp[i][k] + dp[k][j].Initialize a variable say, temp as s.substr(i, l).Then, find the longest prefix that is also the suffix of the substring temp.If the substring is of the form of dp[i][k]^n(l%(l β pref[l-1]) = 0), then update the value of dp[i][j] as min(dp[i][j], dp[i][i + (l-pref[l-1] β 1)])."
},
{
"code": null,
"e": 26416,
"s": 25843,
"text": "Iterate in the range [0, N-l] using the variable i and perform the following steps:Initialize a variable say, j as i+l-1. If i is equal to j, then update dp[i][j] as 1 and continue.Iterate in the range [i, j-1] using the variable k and update dp[i][j] as min of dp[i][j] and dp[i][k] + dp[k][j].Initialize a variable say, temp as s.substr(i, l).Then, find the longest prefix that is also the suffix of the substring temp.If the substring is of the form of dp[i][k]^n(l%(l β pref[l-1]) = 0), then update the value of dp[i][j] as min(dp[i][j], dp[i][i + (l-pref[l-1] β 1)])."
},
{
"code": null,
"e": 26456,
"s": 26416,
"text": "Initialize a variable say, j as i+l-1. "
},
{
"code": null,
"e": 26516,
"s": 26456,
"text": "If i is equal to j, then update dp[i][j] as 1 and continue."
},
{
"code": null,
"e": 26631,
"s": 26516,
"text": "Iterate in the range [i, j-1] using the variable k and update dp[i][j] as min of dp[i][j] and dp[i][k] + dp[k][j]."
},
{
"code": null,
"e": 26682,
"s": 26631,
"text": "Initialize a variable say, temp as s.substr(i, l)."
},
{
"code": null,
"e": 26759,
"s": 26682,
"text": "Then, find the longest prefix that is also the suffix of the substring temp."
},
{
"code": null,
"e": 26911,
"s": 26759,
"text": "If the substring is of the form of dp[i][k]^n(l%(l β pref[l-1]) = 0), then update the value of dp[i][j] as min(dp[i][j], dp[i][i + (l-pref[l-1] β 1)])."
},
{
"code": null,
"e": 26965,
"s": 26911,
"text": "Finally, print the value of dp[0][N-1] as the answer."
},
{
"code": null,
"e": 27017,
"s": 26965,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27021,
"s": 27017,
"text": "C++"
},
{
"code": null,
"e": 27029,
"s": 27021,
"text": "Python3"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Prefix function to calculate// longest prefix that is also// the suffix of the substring Svector<int> prefix_function(string s){ int n = (int)s.length(); vector<int> pi(n); for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi;} // Function to find the length of the// shortest compressed stringvoid minLength(string s, int n){ // Declare a 2D dp vector vector<vector<int> > dp(n + 1, vector<int>(n + 1, 10000)); // Traversing substring on the basis of length for (int l = 1; l <= n; l++) { // For loop for each substring of length l for (int i = 0; i < n - l + 1; i++) { // Second substring coordinate int j = i + l - 1; // If the length of the string is 1 // then dp[i][j] = 1 if (i == j) { dp[i][j] = 1; continue; } // Finding smallest dp[i][j] value // by breaking it in two substrings for (int k = i; k < j; k++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]); } // Substring starting with i of length L string temp = s.substr(i, l); // Prefix function of the substring temp auto pref = prefix_function(temp); // Checking if the substring is // of the form of dp[i][k]^n if (l % (l - pref[l - 1]) == 0) { // If yes, check if dp[i][k] is // less than dp[i][j] dp[i][j] = min(dp[i][j], dp[i][i + (l - pref[l - 1] - 1)]); } } } // Finally, print the required answer cout << dp[0][n - 1] << endl;} // Driver Codeint main(){ // Given Input int n = 4; string s = \"aaba\"; // Function Call minLength(s, n);}",
"e": 29095,
"s": 27029,
"text": null
},
{
"code": "# Python program for the above approach # Prefix function to calculate# longest prefix that is also# the suffix of the substring Sdef prefix_function(s): n = len(s) pi = [0 for i in range(n)] for i in range(1,n): j = pi[i - 1] while (j > 0 and s[i] != s[j]): j = pi[j - 1] if (s[i] == s[j]): j += 1 pi[i] = j return pi # Function to find the length of the# shortest compressed stringdef minLength(s,n): # Declare a 2D dp vector dp = [[10000 for col in range(n+1)] for row in range(n + 1)] # Traversing substring on the basis of length for l in range(1,n+1): # For loop for each substring of length l for i in range(n - l + 1): # Second substring coordinate j = i + l - 1 # If the length of the string is 1 # then dp[i][j] = 1 if (i == j): dp[i][j] = 1 continue # Finding smallest dp[i][j] value # by breaking it in two substrings for k in range(i,j): dp[i][j] = min(dp[i][j],dp[i][k] + dp[k + 1][j]) # Substring starting with i of length L temp = s[i:i+l] # Prefix function of the substring temp pref = prefix_function(temp) # Checking if the substring is # of the form of dp[i][k]^n if (l % (l - pref[l - 1]) == 0): # If yes, check if dp[i][k] is # less than dp[i][j] dp[i][j] = min(dp[i][j],dp[i][i + (l - pref[l - 1] - 1)]) # Finally, print the required answer print(dp[0][n - 1]) # Driver Code # Given Inputn = 4s = \"aaba\" # Function CallminLength(s, n) # This code is contributed by shinjanpatra",
"e": 30859,
"s": 29095,
"text": null
},
{
"code": null,
"e": 30861,
"s": 30859,
"text": "3"
},
{
"code": null,
"e": 30908,
"s": 30861,
"text": "Time Complexity: O(N^3)Auxiliary Space: O(N^2)"
},
{
"code": null,
"e": 30921,
"s": 30908,
"text": "shinjanpatra"
},
{
"code": null,
"e": 30941,
"s": 30921,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 30949,
"s": 30941,
"text": "Strings"
},
{
"code": null,
"e": 30957,
"s": 30949,
"text": "Strings"
},
{
"code": null,
"e": 30977,
"s": 30957,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31075,
"s": 30977,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31084,
"s": 31075,
"text": "Comments"
},
{
"code": null,
"e": 31097,
"s": 31084,
"text": "Old Comments"
},
{
"code": null,
"e": 31157,
"s": 31097,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 31208,
"s": 31157,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 31229,
"s": 31208,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 31285,
"s": 31229,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 31303,
"s": 31285,
"text": "Gold Mine Problem"
},
{
"code": null,
"e": 31328,
"s": 31303,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31374,
"s": 31328,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 31434,
"s": 31374,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31449,
"s": 31434,
"text": "C++ Data Types"
}
]
|
How to find the mean squared error for linear model in R? | To find the mean squared error for linear model, we can use predicted values of the model and find the error from dependent variable then take its square and the mean of the whole output. For example, if we have a linear model called M for a data frame df then we can find the mean squared error using the command mean((df$y-predict(M))^2).
Consider the below data frame β
Live Demo
x1<-rnorm(20)
y1<-rnorm(20)
df1<-data.frame(x1,y1)
df1
x1 y1
1 -0.64419775 -0.655535847
2 -2.02925533 -0.074246704
3 1.42639556 0.226413529
4 0.21841252 -0.799586646
5 -0.08272931 0.021258680
6 1.36349138 -0.358914344
7 0.58243090 0.334064031
8 -0.18839329 0.596566815
9 1.97993745 1.808762160
10 -0.31676008 0.812349831
11 -0.06732802 -0.189255661
12 1.76175840 -0.317888508
13 -0.29681017 0.947048363
14 -1.02210007 0.428273333
15 -0.33408154 2.273976129
16 0.49158882 -0.483902966
17 -0.71446066 0.001058688
18 -0.98031110 0.011280707
19 0.78912612 0.620691096
20 0.63751954 -0.668467539
Creating linear model for y1 and x1 then finding predicted values and the mean squared error β
Model1<-lm(y1~x1,data=df1)
predict(Model1)
1 2 3 4 5 6 7 8
0.1936091 0.1343150 0.2822509 0.2305373 0.2176455 0.2795580 0.2461209 0.2131220
9 10 11 12 13 14 15 16
0.3059479 0.2076267 0.2183048 0.2966077 0.2084807 0.1774312 0.2068852 0.2422320
17 18 19 20
0.1906012 0.1792202 0.2549695 0.2484792
mean((df1$y1-predict(Model1))^2)
[1] 0.6022432
Live Demo
iv1<-rpois(20,2)
iv2<-rpois(20,3)
iv3<-rpois(20,1)
Y<-rpois(20,6)
df2<-data.frame(iv1,iv2,iv3,Y)
df2
iv1 iv2 iv3 Y
1 3 5 1 5
2 6 2 0 12
3 1 1 0 10
4 5 2 1 6
5 5 1 0 6
6 4 4 0 5
7 1 2 0 2
8 1 1 0 6
9 2 5 0 5
10 2 4 0 6
11 4 6 2 8
12 3 4 1 4
13 2 5 2 6
14 4 3 1 4
15 3 3 2 10
16 2 2 1 7
17 2 4 0 14
18 2 1 0 7
19 1 3 1 7
20 2 4 1 4
Creating linear model for Y, iv1, iv2, iv3 then finding predicted values and the mean squared error β
Model2<-lm(Y~iv1+iv2+iv3,data=df2)
predict(Model2)
1 2 3 4 5 6 7 8
6.368896 7.886330 6.659550 7.545170 7.802283 6.911692 6.457914 6.659550
9 10 11 12 13 14 15 16
6.138690 6.340326 6.397466 6.570532 6.027735 7.057851 6.716690 6.688120
17 18 19 20
6.340326 6.945233 6.200801 6.284848
mean((df2$Y-predict(Model2))^2)
[1] 7.745138 | [
{
"code": null,
"e": 1403,
"s": 1062,
"text": "To find the mean squared error for linear model, we can use predicted values of the model and find the error from dependent variable then take its square and the mean of the whole output. For example, if we have a linear model called M for a data frame df then we can find the mean squared error using the command mean((df$y-predict(M))^2)."
},
{
"code": null,
"e": 1435,
"s": 1403,
"text": "Consider the below data frame β"
},
{
"code": null,
"e": 1446,
"s": 1435,
"text": " Live Demo"
},
{
"code": null,
"e": 1501,
"s": 1446,
"text": "x1<-rnorm(20)\ny1<-rnorm(20)\ndf1<-data.frame(x1,y1)\ndf1"
},
{
"code": null,
"e": 2102,
"s": 1501,
"text": " x1 y1\n1 -0.64419775 -0.655535847\n2 -2.02925533 -0.074246704\n3 1.42639556 0.226413529\n4 0.21841252 -0.799586646\n5 -0.08272931 0.021258680\n6 1.36349138 -0.358914344\n7 0.58243090 0.334064031\n8 -0.18839329 0.596566815\n9 1.97993745 1.808762160\n10 -0.31676008 0.812349831\n11 -0.06732802 -0.189255661\n12 1.76175840 -0.317888508\n13 -0.29681017 0.947048363\n14 -1.02210007 0.428273333\n15 -0.33408154 2.273976129\n16 0.49158882 -0.483902966\n17 -0.71446066 0.001058688\n18 -0.98031110 0.011280707\n19 0.78912612 0.620691096\n20 0.63751954 -0.668467539"
},
{
"code": null,
"e": 2197,
"s": 2102,
"text": "Creating linear model for y1 and x1 then finding predicted values and the mean squared error β"
},
{
"code": null,
"e": 2240,
"s": 2197,
"text": "Model1<-lm(y1~x1,data=df1)\npredict(Model1)"
},
{
"code": null,
"e": 2628,
"s": 2240,
"text": " 1 2 3 4 5 6 7 8\n0.1936091 0.1343150 0.2822509 0.2305373 0.2176455 0.2795580 0.2461209 0.2131220\n 9 10 11 12 13 14 15 16\n0.3059479 0.2076267 0.2183048 0.2966077 0.2084807 0.1774312 0.2068852 0.2422320\n 17 18 19 20\n0.1906012 0.1792202 0.2549695 0.2484792"
},
{
"code": null,
"e": 2661,
"s": 2628,
"text": "mean((df1$y1-predict(Model1))^2)"
},
{
"code": null,
"e": 2675,
"s": 2661,
"text": "[1] 0.6022432"
},
{
"code": null,
"e": 2686,
"s": 2675,
"text": " Live Demo"
},
{
"code": null,
"e": 2787,
"s": 2686,
"text": "iv1<-rpois(20,2)\niv2<-rpois(20,3)\niv3<-rpois(20,1)\nY<-rpois(20,6)\ndf2<-data.frame(iv1,iv2,iv3,Y)\ndf2"
},
{
"code": null,
"e": 3123,
"s": 2787,
"text": " iv1 iv2 iv3 Y\n1 3 5 1 5\n2 6 2 0 12\n3 1 1 0 10\n4 5 2 1 6\n5 5 1 0 6\n6 4 4 0 5\n7 1 2 0 2\n8 1 1 0 6\n9 2 5 0 5\n10 2 4 0 6\n11 4 6 2 8\n12 3 4 1 4\n13 2 5 2 6\n14 4 3 1 4\n15 3 3 2 10\n16 2 2 1 7\n17 2 4 0 14\n18 2 1 0 7\n19 1 3 1 7\n20 2 4 1 4"
},
{
"code": null,
"e": 3225,
"s": 3123,
"text": "Creating linear model for Y, iv1, iv2, iv3 then finding predicted values and the mean squared error β"
},
{
"code": null,
"e": 3276,
"s": 3225,
"text": "Model2<-lm(Y~iv1+iv2+iv3,data=df2)\npredict(Model2)"
},
{
"code": null,
"e": 3629,
"s": 3276,
"text": " 1 2 3 4 5 6 7 8\n6.368896 7.886330 6.659550 7.545170 7.802283 6.911692 6.457914 6.659550\n 9 10 11 12 13 14 15 16\n6.138690 6.340326 6.397466 6.570532 6.027735 7.057851 6.716690 6.688120\n 17 18 19 20\n6.340326 6.945233 6.200801 6.284848"
},
{
"code": null,
"e": 3661,
"s": 3629,
"text": "mean((df2$Y-predict(Model2))^2)"
},
{
"code": null,
"e": 3674,
"s": 3661,
"text": "[1] 7.745138"
}
]
|
How to Build a Matrix Module from Scratch | by Khuyen Tran | Towards Data Science | Numpy is a useful library that enables you to create a matrix and perform matrix operations with ease. If you want to know about tricks you could use to create a matrix with Numpy, check out my blog here. But what if you want to create a matrix class with features that are not included in the Numpy library? To be able to do that, we first should start with understanding how to build a matrix class that enables us to create a matrix that has basic functions of a matrix such as print, matrix addition, scalar, element-wise, or matrix multiplication, have access and set entries.
By the end of this tutorial, you should have the building block to create your own matrix module.
Creating a class allows new instances of a type of object to be made. Each class instance can have different attributes and methods. Thus, using a class will enable us to create an instance that has attributes and multiple functions of a matrix. For example, if A = [[2,1],[2,3]], B = [[0,1],[2,1]], A + B should give us a matrix [[2,3],[4,4]].
__method__ is a private method. Even though you cannot call the private method directly, these built-in methods in a class in Python will let the compiler know which one to access when you perform a specific function or operation. You just need to use the right method for your goal.
I will start from what we want to create then find the way to create the class according to our goal. I recommend you to test your class as you add more methods to see if the class acts like what you want.
What we want to achieve with our class is below
>>> A = Matrix(dims=(3,3), fill=1.0) >>> print( A ) ------------- output ------------- | 1.000, 1.000, 1.000| | 1.000, 1.000, 1.000| | 1.000, 1.000, 1.000| ----------------------------------
Thus, we want to create a Matrix object with parameters that are dims and fill.
class Matrix: def __init__(self, dims, fill): self.rows = dims[0] self.cols = dims[1] self.A = [[fill] * self.cols for i in range(self.rows)]
We use __init__ as a constructor to initialize the attributes of our class (rows, cols, and matrix A). The rows and cols are assigned by the first and second dimensions of the matrix. Matrix A is created with fill as the values and self.cols and self.rows as the shape of the matrix.
We should also create a __str__ method that enables us to print a readable format like above.
def __str__(self): m = len(self.A) # Get the first dimension mtxStr = '' mtxStr += '------------- output -------------\n' for i in range(m): mtxStr += ('|' + ', '.join( map(lambda x:'{0:8.3f}'.format(x), self.A[i])) + '| \n') mtxStr += '----------------------------------' return mtxStr
Goal:
Standard matrix-matrix addition
>>> A = Matrix(dims=(3,3), fill=1.0) >>> B = Matrix(dims=(3,3), fill=2.0) >>> C = A + B >>> print( C ) ------------- output ------------- | 3.000, 3.000, 3.000| | 3.000, 3.000, 3.000| | 3.000, 3.000, 3.000| ----------------------------------
Scaler-matrix addition (pointwise)
>>>A = Matrix(dims=(3,3), fill=1.0) >>> C = A + 2.0 >>> print( C ) ------------- output ------------- | 3.000, 3.000, 3.000| | 3.000, 3.000, 3.000| | 3.000, 3.000, 3.000| ----------------------------------
We use __add__ method to perform the right addition.
Since addition is commutative, we also want to be able to add on the right-hand-side of the matrix. This could be easily done by calling the left addition.
def __radd__(self, other): return self.__add__(other)
Goal:
Matrix-Matrix Pointwise Multiplication
>>> A = Matrix(dims=(3,3), fill=1.0) >>> B = Matrix(dims=(3,3), fill=2.0) >>> C = A * B >>> print( C ) ------------- output ------------- | 2.000, 2.000, 2.000| | 2.000, 2.000, 2.000| | 2.000, 2.000, 2.000| ----------------------------------
Scaler-matrix Pointwise Multiplication
>>> A = Matrix(dims=(3,3), fill=1.0) >>> C = 2.0 * A >>> C = A * 2.0 >>> print( C ) ------------- output ------------- | 2.000, 2.000, 2.000| | 2.000, 2.000, 2.000| | 2.000, 2.000, 2.000| ----------------------------------
Use __mul__ method and __rmul__ method to perform left and right point-wise
Goal:
>>> A = Matrix(dims=(3,3), fill=1.0) >>> B = Matrix(dims=(3,3), fill=2.0) >>> C = A @ B >>> print( C ) ------------- output ------------- | 6.000, 6.000, 6.000| | 6.000, 6.000, 6.000| | 6.000, 6.000, 6.000| ----------------------------------
Matrix multiplication could be achieved by __matmul__ method that is specific for matrix multiplication.
Goal:
>>> A = Matrix(dims=(3,3), fill=1.0) >>> A[i,j] >>> A[i,j] = 1.0
Use __setitem__ method to set the value for the matrix indices and use__getitem__ method to get value for the matrix indices.
After creating the class Matrix, it is time to turn it into a module. Rename the text that contains the class to __init__.py. Create a folder called Matrix. Putmain.py and another file calledlinearAlgebra inside this folder. Put__init__.py file inside the linearAlgebra file.
Use main.py to import and use our Matrix class.
Awesome! You have learned how to create a matrix class from scratch. There are other methods in Python class that would enable you to add more features for your matrix. As you have the basic knowledge of creating a class, you could create your own version of Matrix that fits your interest. Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: | [
{
"code": null,
"e": 629,
"s": 47,
"text": "Numpy is a useful library that enables you to create a matrix and perform matrix operations with ease. If you want to know about tricks you could use to create a matrix with Numpy, check out my blog here. But what if you want to create a matrix class with features that are not included in the Numpy library? To be able to do that, we first should start with understanding how to build a matrix class that enables us to create a matrix that has basic functions of a matrix such as print, matrix addition, scalar, element-wise, or matrix multiplication, have access and set entries."
},
{
"code": null,
"e": 727,
"s": 629,
"text": "By the end of this tutorial, you should have the building block to create your own matrix module."
},
{
"code": null,
"e": 1072,
"s": 727,
"text": "Creating a class allows new instances of a type of object to be made. Each class instance can have different attributes and methods. Thus, using a class will enable us to create an instance that has attributes and multiple functions of a matrix. For example, if A = [[2,1],[2,3]], B = [[0,1],[2,1]], A + B should give us a matrix [[2,3],[4,4]]."
},
{
"code": null,
"e": 1356,
"s": 1072,
"text": "__method__ is a private method. Even though you cannot call the private method directly, these built-in methods in a class in Python will let the compiler know which one to access when you perform a specific function or operation. You just need to use the right method for your goal."
},
{
"code": null,
"e": 1562,
"s": 1356,
"text": "I will start from what we want to create then find the way to create the class according to our goal. I recommend you to test your class as you add more methods to see if the class acts like what you want."
},
{
"code": null,
"e": 1610,
"s": 1562,
"text": "What we want to achieve with our class is below"
},
{
"code": null,
"e": 1836,
"s": 1610,
"text": " >>> A = Matrix(dims=(3,3), fill=1.0)\t>>> print( A )\t------------- output -------------\t| 1.000, 1.000, 1.000| \t| 1.000, 1.000, 1.000| \t| 1.000, 1.000, 1.000| \t----------------------------------"
},
{
"code": null,
"e": 1916,
"s": 1836,
"text": "Thus, we want to create a Matrix object with parameters that are dims and fill."
},
{
"code": null,
"e": 2082,
"s": 1916,
"text": "class Matrix: def __init__(self, dims, fill): self.rows = dims[0] self.cols = dims[1] self.A = [[fill] * self.cols for i in range(self.rows)]"
},
{
"code": null,
"e": 2366,
"s": 2082,
"text": "We use __init__ as a constructor to initialize the attributes of our class (rows, cols, and matrix A). The rows and cols are assigned by the first and second dimensions of the matrix. Matrix A is created with fill as the values and self.cols and self.rows as the shape of the matrix."
},
{
"code": null,
"e": 2460,
"s": 2366,
"text": "We should also create a __str__ method that enables us to print a readable format like above."
},
{
"code": null,
"e": 2786,
"s": 2460,
"text": "def __str__(self): m = len(self.A) # Get the first dimension mtxStr = '' mtxStr += '------------- output -------------\\n' for i in range(m): mtxStr += ('|' + ', '.join( map(lambda x:'{0:8.3f}'.format(x), self.A[i])) + '| \\n') mtxStr += '----------------------------------' return mtxStr"
},
{
"code": null,
"e": 2792,
"s": 2786,
"text": "Goal:"
},
{
"code": null,
"e": 2824,
"s": 2792,
"text": "Standard matrix-matrix addition"
},
{
"code": null,
"e": 3101,
"s": 2824,
"text": " >>> A = Matrix(dims=(3,3), fill=1.0)\t>>> B = Matrix(dims=(3,3), fill=2.0)\t>>> C = A + B\t>>> print( C )\t------------- output -------------\t| 3.000, 3.000, 3.000| \t| 3.000, 3.000, 3.000| \t| 3.000, 3.000, 3.000| \t----------------------------------"
},
{
"code": null,
"e": 3136,
"s": 3101,
"text": "Scaler-matrix addition (pointwise)"
},
{
"code": null,
"e": 3378,
"s": 3136,
"text": " >>>A = Matrix(dims=(3,3), fill=1.0)\t>>> C = A + 2.0\t>>> print( C )\t------------- output -------------\t| 3.000, 3.000, 3.000| \t| 3.000, 3.000, 3.000| \t| 3.000, 3.000, 3.000| \t---------------------------------- "
},
{
"code": null,
"e": 3431,
"s": 3378,
"text": "We use __add__ method to perform the right addition."
},
{
"code": null,
"e": 3587,
"s": 3431,
"text": "Since addition is commutative, we also want to be able to add on the right-hand-side of the matrix. This could be easily done by calling the left addition."
},
{
"code": null,
"e": 3644,
"s": 3587,
"text": "def __radd__(self, other): return self.__add__(other)"
},
{
"code": null,
"e": 3650,
"s": 3644,
"text": "Goal:"
},
{
"code": null,
"e": 3689,
"s": 3650,
"text": "Matrix-Matrix Pointwise Multiplication"
},
{
"code": null,
"e": 3966,
"s": 3689,
"text": " >>> A = Matrix(dims=(3,3), fill=1.0)\t>>> B = Matrix(dims=(3,3), fill=2.0)\t>>> C = A * B\t>>> print( C )\t------------- output -------------\t| 2.000, 2.000, 2.000| \t| 2.000, 2.000, 2.000| \t| 2.000, 2.000, 2.000| \t----------------------------------"
},
{
"code": null,
"e": 4005,
"s": 3966,
"text": "Scaler-matrix Pointwise Multiplication"
},
{
"code": null,
"e": 4263,
"s": 4005,
"text": " >>> A = Matrix(dims=(3,3), fill=1.0)\t>>> C = 2.0 * A\t>>> C = A * 2.0\t>>> print( C )\t------------- output -------------\t| 2.000, 2.000, 2.000| \t| 2.000, 2.000, 2.000| \t| 2.000, 2.000, 2.000| \t----------------------------------"
},
{
"code": null,
"e": 4339,
"s": 4263,
"text": "Use __mul__ method and __rmul__ method to perform left and right point-wise"
},
{
"code": null,
"e": 4345,
"s": 4339,
"text": "Goal:"
},
{
"code": null,
"e": 4622,
"s": 4345,
"text": " >>> A = Matrix(dims=(3,3), fill=1.0)\t>>> B = Matrix(dims=(3,3), fill=2.0)\t>>> C = A @ B\t>>> print( C )\t------------- output -------------\t| 6.000, 6.000, 6.000| \t| 6.000, 6.000, 6.000| \t| 6.000, 6.000, 6.000| \t----------------------------------"
},
{
"code": null,
"e": 4727,
"s": 4622,
"text": "Matrix multiplication could be achieved by __matmul__ method that is specific for matrix multiplication."
},
{
"code": null,
"e": 4733,
"s": 4727,
"text": "Goal:"
},
{
"code": null,
"e": 4806,
"s": 4733,
"text": " >>> A = Matrix(dims=(3,3), fill=1.0)\t>>> A[i,j]\t>>> A[i,j] = 1.0"
},
{
"code": null,
"e": 4932,
"s": 4806,
"text": "Use __setitem__ method to set the value for the matrix indices and use__getitem__ method to get value for the matrix indices."
},
{
"code": null,
"e": 5208,
"s": 4932,
"text": "After creating the class Matrix, it is time to turn it into a module. Rename the text that contains the class to __init__.py. Create a folder called Matrix. Putmain.py and another file calledlinearAlgebra inside this folder. Put__init__.py file inside the linearAlgebra file."
},
{
"code": null,
"e": 5256,
"s": 5208,
"text": "Use main.py to import and use our Matrix class."
},
{
"code": null,
"e": 5626,
"s": 5256,
"text": "Awesome! You have learned how to create a matrix class from scratch. There are other methods in Python class that would enable you to add more features for your matrix. As you have the basic knowledge of creating a class, you could create your own version of Matrix that fits your interest. Feel free to fork and play with the code for this article in this Github repo."
},
{
"code": null,
"e": 5786,
"s": 5626,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
]
|
Styling Links with CSS | To style links with CSS, at first we should know the following link states: link, visited, hover and active. Use the pseudo-classes of anchor element to style links β
a:link for link
a:visited forvisited link
a:link for hover on link
a:active for active link
Let us now see an example β
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
a:link {
color: orange;
text-decoration: underline;
}
a:hover {
color: red;
text-decoration: underline;
}
a:active {
color: green;
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Tutorials</h1>
<p><a href="https://www.tutorialspoint.com/java">Java</a></p>
<p><a href="https://www.tutorialspoint.com/chsharp">C#</a></p>
<p><a href="https://www.tutorialspoint.com/jquery">jQuery</a></p>
<p><a href="https://www.tutorialspoint.com/ruby">Ruby</a></p>
<p><a href="https://www.tutorialspoint.com/pytorch">PyTorch</a></p>
</body>
</html>
Let us now see another example β
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
a:link {
color: blue;
text-decoration: none;
}
a:hover {
color: blue;
text-decoration: none;
}
a:active {
color: blue;
text-decoration: none;
}
</style>
</head>
<body>
<h1>Demo Heading</h1>
<div>
<p>This is the <a href="https://tutorialspoint.com">reference</a></p>
</div>
</body>
</html> | [
{
"code": null,
"e": 1229,
"s": 1062,
"text": "To style links with CSS, at first we should know the following link states: link, visited, hover and active. Use the pseudo-classes of anchor element to style links β"
},
{
"code": null,
"e": 1321,
"s": 1229,
"text": "a:link for link\na:visited forvisited link\na:link for hover on link\na:active for active link"
},
{
"code": null,
"e": 1349,
"s": 1321,
"text": "Let us now see an example β"
},
{
"code": null,
"e": 1360,
"s": 1349,
"text": " Live Demo"
},
{
"code": null,
"e": 1957,
"s": 1360,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\na:link {\n color: orange;\n text-decoration: underline;\n}\na:hover {\n color: red;\n text-decoration: underline;\n}\na:active {\n color: green;\n text-decoration: underline;\n}\n</style>\n</head>\n<body>\n<h1>Tutorials</h1>\n<p><a href=\"https://www.tutorialspoint.com/java\">Java</a></p>\n<p><a href=\"https://www.tutorialspoint.com/chsharp\">C#</a></p>\n<p><a href=\"https://www.tutorialspoint.com/jquery\">jQuery</a></p>\n<p><a href=\"https://www.tutorialspoint.com/ruby\">Ruby</a></p>\n<p><a href=\"https://www.tutorialspoint.com/pytorch\">PyTorch</a></p>\n</body>\n</html>"
},
{
"code": null,
"e": 1990,
"s": 1957,
"text": "Let us now see another example β"
},
{
"code": null,
"e": 2001,
"s": 1990,
"text": " Live Demo"
},
{
"code": null,
"e": 2346,
"s": 2001,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\na:link {\n color: blue;\n text-decoration: none;\n}\na:hover {\n color: blue;\n text-decoration: none;\n}\na:active {\n color: blue;\n text-decoration: none;\n}\n</style>\n</head>\n<body>\n<h1>Demo Heading</h1>\n<div>\n<p>This is the <a href=\"https://tutorialspoint.com\">reference</a></p>\n</div>\n</body>\n</html>"
}
]
|
C library function - putchar() | The C library function int putchar(int char) writes a character (an unsigned char) specified by the argument char to stdout.
Following is the declaration for putchar() function.
int putchar(int char)
char β This is the character to be written. This is passed as its int promotion.
char β This is the character to be written. This is passed as its int promotion.
This function returns the character written as an unsigned char cast to an int or EOF on error.
The following example shows the usage of putchar() function.
#include <stdio.h>
int main () {
char ch;
for(ch = 'A' ; ch <= 'Z' ; ch++) {
putchar(ch);
}
return(0);
}
Let us compile and run the above program that will produce the following result β
ABCDEFGHIJKLMNOPQRSTUVWXYZ
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": 2132,
"s": 2007,
"text": "The C library function int putchar(int char) writes a character (an unsigned char) specified by the argument char to stdout."
},
{
"code": null,
"e": 2185,
"s": 2132,
"text": "Following is the declaration for putchar() function."
},
{
"code": null,
"e": 2207,
"s": 2185,
"text": "int putchar(int char)"
},
{
"code": null,
"e": 2288,
"s": 2207,
"text": "char β This is the character to be written. This is passed as its int promotion."
},
{
"code": null,
"e": 2369,
"s": 2288,
"text": "char β This is the character to be written. This is passed as its int promotion."
},
{
"code": null,
"e": 2465,
"s": 2369,
"text": "This function returns the character written as an unsigned char cast to an int or EOF on error."
},
{
"code": null,
"e": 2526,
"s": 2465,
"text": "The following example shows the usage of putchar() function."
},
{
"code": null,
"e": 2655,
"s": 2526,
"text": "#include <stdio.h>\n\nint main () {\n char ch;\n\n for(ch = 'A' ; ch <= 'Z' ; ch++) {\n putchar(ch);\n }\n \n return(0);\n}"
},
{
"code": null,
"e": 2737,
"s": 2655,
"text": "Let us compile and run the above program that will produce the following result β"
},
{
"code": null,
"e": 2765,
"s": 2737,
"text": "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
},
{
"code": null,
"e": 2798,
"s": 2765,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2813,
"s": 2798,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2848,
"s": 2813,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2863,
"s": 2848,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2898,
"s": 2863,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2912,
"s": 2898,
"text": " Asif Hussain"
},
{
"code": null,
"e": 2945,
"s": 2912,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2963,
"s": 2945,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 2998,
"s": 2963,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3017,
"s": 2998,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3050,
"s": 3017,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3062,
"s": 3050,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3069,
"s": 3062,
"text": " Print"
},
{
"code": null,
"e": 3080,
"s": 3069,
"text": " Add Notes"
}
]
|
Flutter - Important CLI commands - GeeksforGeeks | 09 Jul, 2021
Flutter is a mobile development UI kit managed by Google. It is powered by dart language which is used for the Flutter framework to make applications for mobile, web, and desktop with a single codebase. Flutter Command-Line (CLI) tool enables a user to interact with flutter SDK.
In this article, we are going to discuss all the commands flutter uses. We will see the most important commands which are used in almost all flutter projects with their explanation.
Syntax: flutter create APP_NAME
This command creates a new flutter app project, in the current directory. If you want to create the project in a specific folder then move to that directory first using the command cd FILE ADDRESS.
Syntax: flutter analyze -d <DEVICE_ID>
This command performs a static analysis of the projectβs Dart source code. Basically what it does is search for any missing code or errors. It can be performed for a specific file or the whole flutter project.
Syntax: flutter test [<DIRECTORY|DART_FILE>]
This command performs a test on the flutter project or a specific dart file. It checks if the application or code is flawed or not. This is very useful if our application is big and test it manually is not possible.
Syntax: flutter run <DART_FILE>
This command will run the dart file if mentioned or otherwise it will run the whole project in the device which the user chooses.
Syntax: flutter pub get
This command downloads all the packages or dependencies which are listed in the pubspeck.yaml file of the current or active project file.
Syntax: flutter pub update
This command will update the flutter packages used in the current project.
Syntax: flutter --help --verbose
This is a very useful command, especially for beginners. It shows a list of all the commands flutter uses.
Syntax: flutter doctor
This command will check the current status of the flutter information. If some software is missing or not working then it will show a warning.
Syntax: flutter version
It shows the version related information for flutter and dart SDKs.
Syntax: flutter channel <CHANNEL_NAME>
This command will list all the flutter channels available right now. You can see which one you are using or switch to another to access new features. Generally stable is the one most people use.
Syntax: flutter build <DIRECTORY>
This command is to build the flutter application in the directory we want. If we donβt assign directory then it will build inside the build folder. We can build web app with flutter build web command, an android app with flutter build apk or flutter build appbundel (more preferred), and an iOS app with flutter build ios command.
Syntax: flutter devices -d <DEVICE_ID>
This is the command to list all the connected device on which we can run our flutter application. Then we can connect to the device of our choice to run the flutter application.
Syntax: flutter upgrade
This command should be run globally in the system. It upgrades the copy of flutter SDK along with dart SKD in our machine. It is usually a good idea to run this command after every new release.
Syntax: flutter assemble -o <DIRECTORY>
This command fetches all the necessary package uses in the app (if not present already) and then builds the app.
Syntax: flutter attach -d <DEVICE_ID>
This command is similar to the flutter run command, but it provides certain other terminal functionalities other than whatβs present in the flutter run command when we are adding flutter to the app made using another framework. This Command should be used when we are adding flutter to a pre-existing application, if we simply give flutter run command then we will not get hot reload, DevTools and other functionalities.
Syntax: flutter symbolize --input=<STACK_TRACK_FILE>
This command is used to make stack trace human-readable. The stack trace could be a file which gets generated when an app crashes.
Syntax: flutter config --build-dir=<DIRECTORY>
This command is to configure the functionalities of flutter which you want in your project. Such as you can enable or disable flutter web.
Syntax: flutter downgrade
This command should be run globally in the system. It downgrades the copy of flutter SDK along with dart SKD in our machine to the previously available active version. This can be done if something in the present version of flutter is not working for you the way it should.
Syntax: flutter drive
If our flutter project access some hardware from the userβs device which requires the application of some drivers, then this is the command we shout run to test if our drivers are running well without and errors.
Syntax: flutter emulators
This command lists all the emulators currently installed in our machine gives us the option to launch the emulator and create a new emulator if we want.
Syntax: flutter format <DART_FILE | DIRECTORY>
This flutter command formats the dart file according to the pre-specified setting in the flutter SDK. But if you are using VS-Code or Android Studio with the flutter and dart extensions installed, then the dart is formatted automatically.
Syntax: flutter gen-l10n <DIRECTORY>
This command is used to generate a local file of flutter dependencies. For example, if we are using certain fonts of mages through an API this command will make them available locally. For all the options use this command flutter gen-l10n -h.
Syntax: flutter install -d <DEVICE_ID>
This is the command to install the flutter application on an attached device after building the application. The attached device can either be a physical one such as an android or iOS mobile or build in applications such as emulator or browser.
Syntax: flutter logs
This command shows us the log output in the terminal for running the flutter application. It is usually used to if some code in the app is breaking or giving exceptions.
Syntax: flutter precache <ARGUMENTS>
This command is to get all the assets that our flutter app is using present locally or globally.
surinderdawra388
Articles
TechTips
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
SQL | Date functions
Difference between Min Heap and Max Heap
How to Find the Wi-Fi Password Using CMD in Windows?
How to Run a Python Script using Docker?
Docker - COPY Instruction
Setting up the environment in Java
How to setup cron jobs in Ubuntu | [
{
"code": null,
"e": 24422,
"s": 24394,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 24703,
"s": 24422,
"text": "Flutter is a mobile development UI kit managed by Google. It is powered by dart language which is used for the Flutter framework to make applications for mobile, web, and desktop with a single codebase. Flutter Command-Line (CLI) tool enables a user to interact with flutter SDK. "
},
{
"code": null,
"e": 24885,
"s": 24703,
"text": "In this article, we are going to discuss all the commands flutter uses. We will see the most important commands which are used in almost all flutter projects with their explanation."
},
{
"code": null,
"e": 24918,
"s": 24885,
"text": "Syntax: flutter create APP_NAME "
},
{
"code": null,
"e": 25118,
"s": 24918,
"text": "This command creates a new flutter app project, in the current directory. If you want to create the project in a specific folder then move to that directory first using the command cd FILE ADDRESS. "
},
{
"code": null,
"e": 25157,
"s": 25118,
"text": "Syntax: flutter analyze -d <DEVICE_ID>"
},
{
"code": null,
"e": 25367,
"s": 25157,
"text": "This command performs a static analysis of the projectβs Dart source code. Basically what it does is search for any missing code or errors. It can be performed for a specific file or the whole flutter project."
},
{
"code": null,
"e": 25413,
"s": 25367,
"text": "Syntax: flutter test [<DIRECTORY|DART_FILE>] "
},
{
"code": null,
"e": 25629,
"s": 25413,
"text": "This command performs a test on the flutter project or a specific dart file. It checks if the application or code is flawed or not. This is very useful if our application is big and test it manually is not possible."
},
{
"code": null,
"e": 25661,
"s": 25629,
"text": "Syntax: flutter run <DART_FILE>"
},
{
"code": null,
"e": 25791,
"s": 25661,
"text": "This command will run the dart file if mentioned or otherwise it will run the whole project in the device which the user chooses."
},
{
"code": null,
"e": 25815,
"s": 25791,
"text": "Syntax: flutter pub get"
},
{
"code": null,
"e": 25953,
"s": 25815,
"text": "This command downloads all the packages or dependencies which are listed in the pubspeck.yaml file of the current or active project file."
},
{
"code": null,
"e": 25981,
"s": 25953,
"text": "Syntax: flutter pub update"
},
{
"code": null,
"e": 26056,
"s": 25981,
"text": "This command will update the flutter packages used in the current project."
},
{
"code": null,
"e": 26090,
"s": 26056,
"text": "Syntax: flutter --help --verbose "
},
{
"code": null,
"e": 26197,
"s": 26090,
"text": "This is a very useful command, especially for beginners. It shows a list of all the commands flutter uses."
},
{
"code": null,
"e": 26220,
"s": 26197,
"text": "Syntax: flutter doctor"
},
{
"code": null,
"e": 26363,
"s": 26220,
"text": "This command will check the current status of the flutter information. If some software is missing or not working then it will show a warning."
},
{
"code": null,
"e": 26388,
"s": 26363,
"text": "Syntax: flutter version"
},
{
"code": null,
"e": 26456,
"s": 26388,
"text": "It shows the version related information for flutter and dart SDKs."
},
{
"code": null,
"e": 26496,
"s": 26456,
"text": "Syntax: flutter channel <CHANNEL_NAME>"
},
{
"code": null,
"e": 26691,
"s": 26496,
"text": "This command will list all the flutter channels available right now. You can see which one you are using or switch to another to access new features. Generally stable is the one most people use."
},
{
"code": null,
"e": 26725,
"s": 26691,
"text": "Syntax: flutter build <DIRECTORY>"
},
{
"code": null,
"e": 27056,
"s": 26725,
"text": "This command is to build the flutter application in the directory we want. If we donβt assign directory then it will build inside the build folder. We can build web app with flutter build web command, an android app with flutter build apk or flutter build appbundel (more preferred), and an iOS app with flutter build ios command."
},
{
"code": null,
"e": 27095,
"s": 27056,
"text": "Syntax: flutter devices -d <DEVICE_ID>"
},
{
"code": null,
"e": 27273,
"s": 27095,
"text": "This is the command to list all the connected device on which we can run our flutter application. Then we can connect to the device of our choice to run the flutter application."
},
{
"code": null,
"e": 27299,
"s": 27273,
"text": "Syntax: flutter upgrade "
},
{
"code": null,
"e": 27493,
"s": 27299,
"text": "This command should be run globally in the system. It upgrades the copy of flutter SDK along with dart SKD in our machine. It is usually a good idea to run this command after every new release."
},
{
"code": null,
"e": 27534,
"s": 27493,
"text": "Syntax: flutter assemble -o <DIRECTORY>"
},
{
"code": null,
"e": 27647,
"s": 27534,
"text": "This command fetches all the necessary package uses in the app (if not present already) and then builds the app."
},
{
"code": null,
"e": 27685,
"s": 27647,
"text": "Syntax: flutter attach -d <DEVICE_ID>"
},
{
"code": null,
"e": 28107,
"s": 27685,
"text": "This command is similar to the flutter run command, but it provides certain other terminal functionalities other than whatβs present in the flutter run command when we are adding flutter to the app made using another framework. This Command should be used when we are adding flutter to a pre-existing application, if we simply give flutter run command then we will not get hot reload, DevTools and other functionalities. "
},
{
"code": null,
"e": 28160,
"s": 28107,
"text": "Syntax: flutter symbolize --input=<STACK_TRACK_FILE>"
},
{
"code": null,
"e": 28291,
"s": 28160,
"text": "This command is used to make stack trace human-readable. The stack trace could be a file which gets generated when an app crashes."
},
{
"code": null,
"e": 28338,
"s": 28291,
"text": "Syntax: flutter config --build-dir=<DIRECTORY>"
},
{
"code": null,
"e": 28477,
"s": 28338,
"text": "This command is to configure the functionalities of flutter which you want in your project. Such as you can enable or disable flutter web."
},
{
"code": null,
"e": 28503,
"s": 28477,
"text": "Syntax: flutter downgrade"
},
{
"code": null,
"e": 28777,
"s": 28503,
"text": "This command should be run globally in the system. It downgrades the copy of flutter SDK along with dart SKD in our machine to the previously available active version. This can be done if something in the present version of flutter is not working for you the way it should."
},
{
"code": null,
"e": 28800,
"s": 28777,
"text": "Syntax: flutter drive"
},
{
"code": null,
"e": 29013,
"s": 28800,
"text": "If our flutter project access some hardware from the userβs device which requires the application of some drivers, then this is the command we shout run to test if our drivers are running well without and errors."
},
{
"code": null,
"e": 29039,
"s": 29013,
"text": "Syntax: flutter emulators"
},
{
"code": null,
"e": 29192,
"s": 29039,
"text": "This command lists all the emulators currently installed in our machine gives us the option to launch the emulator and create a new emulator if we want."
},
{
"code": null,
"e": 29239,
"s": 29192,
"text": "Syntax: flutter format <DART_FILE | DIRECTORY>"
},
{
"code": null,
"e": 29478,
"s": 29239,
"text": "This flutter command formats the dart file according to the pre-specified setting in the flutter SDK. But if you are using VS-Code or Android Studio with the flutter and dart extensions installed, then the dart is formatted automatically."
},
{
"code": null,
"e": 29515,
"s": 29478,
"text": "Syntax: flutter gen-l10n <DIRECTORY>"
},
{
"code": null,
"e": 29758,
"s": 29515,
"text": "This command is used to generate a local file of flutter dependencies. For example, if we are using certain fonts of mages through an API this command will make them available locally. For all the options use this command flutter gen-l10n -h."
},
{
"code": null,
"e": 29798,
"s": 29758,
"text": "Syntax: flutter install -d <DEVICE_ID>"
},
{
"code": null,
"e": 30043,
"s": 29798,
"text": "This is the command to install the flutter application on an attached device after building the application. The attached device can either be a physical one such as an android or iOS mobile or build in applications such as emulator or browser."
},
{
"code": null,
"e": 30065,
"s": 30043,
"text": "Syntax: flutter logs"
},
{
"code": null,
"e": 30235,
"s": 30065,
"text": "This command shows us the log output in the terminal for running the flutter application. It is usually used to if some code in the app is breaking or giving exceptions."
},
{
"code": null,
"e": 30273,
"s": 30235,
"text": "Syntax: flutter precache <ARGUMENTS> "
},
{
"code": null,
"e": 30371,
"s": 30273,
"text": "This command is to get all the assets that our flutter app is using present locally or globally. "
},
{
"code": null,
"e": 30388,
"s": 30371,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30397,
"s": 30388,
"text": "Articles"
},
{
"code": null,
"e": 30406,
"s": 30397,
"text": "TechTips"
},
{
"code": null,
"e": 30423,
"s": 30406,
"text": "Web Technologies"
},
{
"code": null,
"e": 30450,
"s": 30423,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30548,
"s": 30450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30585,
"s": 30548,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 30611,
"s": 30585,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 30658,
"s": 30611,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 30679,
"s": 30658,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 30720,
"s": 30679,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 30773,
"s": 30720,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 30814,
"s": 30773,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 30840,
"s": 30814,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 30875,
"s": 30840,
"text": "Setting up the environment in Java"
}
]
|
Data Extraction from GitHub and Auto-run or Schedule Python Script | by Eklavya Saxena | Towards Data Science | This blog is a part of Automated ETL for LIVE Tableau Public Visualizations and is sub-divided into two parts, namely:
Extract Data from Raw .csv Files of GitHub User ContentAutomate Python Scripts with Task Scheduler on Windows
Extract Data from Raw .csv Files of GitHub User Content
Automate Python Scripts with Task Scheduler on Windows
Data Sourced from JHU CSSE GitHub Repository: https://github.com/CSSEGISandData/COVID-19
import numpy as npimport pandas as pd
Imported the relevant libraries.
df_names = ['confirmed_global', 'deaths_global', 'recovered_global'] df_list = [pd.DataFrame() for df in df_names]df_dict = dict(zip(df_names, df_list))
As we need to extract 3 .csv files, I have created a list βdf_namesβ holding the names of the dataframes. Note that, the names declared are chosen with respect to the url_part β explained below *.
Then, a list βdf_listβ is declared to hold 3 Empty Dataframes created. Note that, for df in df_names just confirm that number of Empty Dataframes created = number of elements in the list βdf_namesβ.
Then, a dictionary βdf_dictβ is created with key: value pair as βdf_names: df_listβ. That is, each name is linked to an empty dataframe with respective positions.
url_part = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_'
A URL part is created as required. * The names declared above will become suffix of the url_part declared.
for key, value in df_dict.items(): value = pd.read_csv(url_part+key+'.csv', parse_dates=[0]) value.rename(columns={'Province/State': 'Province_State', 'Country/Region': 'Country_Region'}, inplace=True) dim_col = value.columns[0:4] date_col = value.columns[4:] value = value.melt(id_vars = dim_col, value_vars = date_col, var_name = 'Date', value_name = key) value['Date'] = pd.to_datetime(value['Date']) df_dict[key] = value
In order to load the data, I have βfor loopedβ through the items in the dictionary βdf_dictβ declared above. The empty dataframes are fed one by one using pandas read_csv function, which reads the data from URL generated using url_part + key (which are the respective names declared) + β.csvβ. And then, the column names are renamed to make it Python friendly.
Now comes the interesting part β the pandas melt function, which did the magic, enabling me to transform the data for my Tableau dashboard. Basically, the melt function unpivots a Dataframe from wide to long format. Refer the debug print output below:
So, the melt function unpivots the 77 date columns from wide format to long format with heading of these columns being fed to a new column βDateβ created using value_vars = date_col, var_name = 'Date' parameter and numeric data being fed into a new column βconfirmed_globalβ created using value_name = key parameter of the melt function.
Then, the βDateβ column data type is changed to datetime and the key of the dictionary declared before is assigned with respective loaded and transformed dataframe.
join_on_col = ['Province_State','Country_Region','Lat','Long','Date']df_COVID = df_dict['confirmed_global'].merge(df_dict['deaths_global'], on=join_on_col, how='outer').merge(df_dict['recovered_global'], on=join_on_col, how='outer')df_COVID.rename(columns = {'confirmed_global':'Confirmed', 'deaths_global':'Deaths', 'recovered_global':'Recovered'}, inplace = True)
Now, the pandas merge function is used to merge 3 different files having βProvince_Stateβ, βCountry_Regionβ, βLatβ, βLongβ, βDateβ in common. Then, column names of the merged dataframe βdf_COVIDβ is renamed.
# to fill the NaN in 'Province_State' columns with Countries name in 'Country_Region'df_COVID['Province_State'] = np.where(df_COVID['Province_State'] == 'nan', df_COVID['Country_Region'], df_COVID['Province_State'])# to fill the NaN in last three columnsdf_COVID.iloc[0:,-3:] = df_COVID.iloc[0:,-3:].fillna(0)
This last line of code helps remove NaN from the dataframe βdf_COVIDβ as and where required. Later, this dataframe can be extracted to a .csv file using to_csv function of pandas.
But I planned to export it to Google Sheets β check how by following the second part of blog β Automated ETL for LIVE Tableau Public Visualizations
Now that I have created a .py python script file to ETL (Extract, Transform and Load) the data, I realized that the GitHub repository used to source the data is updated daily.
In search for need to run the python script daily, I came across a blog β Automate your Python Scripts with Task Scheduler written by Vincent Tatan. However, if you are a Linux user, please refer Scheduling Jobs With Crontab on macOS written by Ratik Sharma.
This section is briefly curated from the former blog:
Create Windows Executable .bat File to Run PythonConfigure Task in Windows Task Scheduler
Create Windows Executable .bat File to Run Python
Configure Task in Windows Task Scheduler
A BAT file is a DOS batch file used to execute commands with the Windows Command Prompt (cmd.exe). It contains a series of line commands that typically might be entered at the DOS command prompt. BAT files are most commonly used to start programs and run maintenance utilities within Windows. Source: https://fileinfo.com/extension/bat
Create a new .bat file (for e.g: etl-covid-data.bat) and edit it to write your command in following format:
<python.exe location> <python script location>
C:\Users\eklav\AppData\Local\Programs\Python\Python37\python.exe "C:\Users\eklav\Documents\My Tableau Repository\Datasources\COVID-DataSource\COVID-19\COVID-DataExtraction.py"
Please ensure that your Python37\Lib\site-packages has all the relevant libraries or modules installed. Else, execute pip install <module> on cmd.exe to download required dependencies.
For Debugging: Save and run this .bat file by double clicking it. You may type cmd /k before the command declared in .bat file. This will keep the Windows Command Prompt (cmd.exe) window open after execution of .bat file
Search and open βTask Schedulerβ from βStartβ menuClick on βCreate Basic Task...β located under βActionsβ tab on the right side of the βTask SchedulerβDeclare the βName:β (for e.g: COVID-ETL-PyScriptRun) and βDescription:β (for e.g: This task will execute the python script required for COVID live updates)Task Trigger:Choose βWhen do you want the task to start?β (for e.g: Daily)Declare frequency parameters for the previous selectionAction:Choose βWhat action do you want the task to perform?β (for e.g: Start a program)Declare βProgram/script:β by browsing it to the .bat file location created earlier. Additionally, you may declare βStart in (optional):β to the location of your application folder to access the relevant dependenciesFinish:This shows the βSummaryβ of all the declarations above. You may tick the checkbox βOpen the Properties dialog for this task when I click Finishβ to discover interesting and helpful changes to your scheduled task. One edit that helped when my code broke was β On βGeneralβ tab of the task properties, I checked the βRun with highest privilegesβ
Search and open βTask Schedulerβ from βStartβ menu
Click on βCreate Basic Task...β located under βActionsβ tab on the right side of the βTask SchedulerβDeclare the βName:β (for e.g: COVID-ETL-PyScriptRun) and βDescription:β (for e.g: This task will execute the python script required for COVID live updates)
Task Trigger:Choose βWhen do you want the task to start?β (for e.g: Daily)
Declare frequency parameters for the previous selection
Action:Choose βWhat action do you want the task to perform?β (for e.g: Start a program)
Declare βProgram/script:β by browsing it to the .bat file location created earlier. Additionally, you may declare βStart in (optional):β to the location of your application folder to access the relevant dependencies
Finish:This shows the βSummaryβ of all the declarations above. You may tick the checkbox βOpen the Properties dialog for this task when I click Finishβ to discover interesting and helpful changes to your scheduled task. One edit that helped when my code broke was β On βGeneralβ tab of the task properties, I checked the βRun with highest privilegesβ
Following is the .gif animation for 7 steps mentioned above:
About .BAT File Extension
A Blog written by Vincent Tatan @ Medium
Python Dataframe Constructor Documentation
Thank you for reading! I hope this blog revealed an interesting aspect on how to automate python script on windows. Let me know in a comment if you felt like this did or didnβt help. If this article was helpful, share it. | [
{
"code": null,
"e": 291,
"s": 172,
"text": "This blog is a part of Automated ETL for LIVE Tableau Public Visualizations and is sub-divided into two parts, namely:"
},
{
"code": null,
"e": 401,
"s": 291,
"text": "Extract Data from Raw .csv Files of GitHub User ContentAutomate Python Scripts with Task Scheduler on Windows"
},
{
"code": null,
"e": 457,
"s": 401,
"text": "Extract Data from Raw .csv Files of GitHub User Content"
},
{
"code": null,
"e": 512,
"s": 457,
"text": "Automate Python Scripts with Task Scheduler on Windows"
},
{
"code": null,
"e": 601,
"s": 512,
"text": "Data Sourced from JHU CSSE GitHub Repository: https://github.com/CSSEGISandData/COVID-19"
},
{
"code": null,
"e": 639,
"s": 601,
"text": "import numpy as npimport pandas as pd"
},
{
"code": null,
"e": 672,
"s": 639,
"text": "Imported the relevant libraries."
},
{
"code": null,
"e": 825,
"s": 672,
"text": "df_names = ['confirmed_global', 'deaths_global', 'recovered_global'] df_list = [pd.DataFrame() for df in df_names]df_dict = dict(zip(df_names, df_list))"
},
{
"code": null,
"e": 1022,
"s": 825,
"text": "As we need to extract 3 .csv files, I have created a list βdf_namesβ holding the names of the dataframes. Note that, the names declared are chosen with respect to the url_part β explained below *."
},
{
"code": null,
"e": 1221,
"s": 1022,
"text": "Then, a list βdf_listβ is declared to hold 3 Empty Dataframes created. Note that, for df in df_names just confirm that number of Empty Dataframes created = number of elements in the list βdf_namesβ."
},
{
"code": null,
"e": 1384,
"s": 1221,
"text": "Then, a dictionary βdf_dictβ is created with key: value pair as βdf_names: df_listβ. That is, each name is linked to an empty dataframe with respective positions."
},
{
"code": null,
"e": 1528,
"s": 1384,
"text": "url_part = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_'"
},
{
"code": null,
"e": 1635,
"s": 1528,
"text": "A URL part is created as required. * The names declared above will become suffix of the url_part declared."
},
{
"code": null,
"e": 2101,
"s": 1635,
"text": "for key, value in df_dict.items(): value = pd.read_csv(url_part+key+'.csv', parse_dates=[0]) value.rename(columns={'Province/State': 'Province_State', 'Country/Region': 'Country_Region'}, inplace=True) dim_col = value.columns[0:4] date_col = value.columns[4:] value = value.melt(id_vars = dim_col, value_vars = date_col, var_name = 'Date', value_name = key) value['Date'] = pd.to_datetime(value['Date']) df_dict[key] = value"
},
{
"code": null,
"e": 2462,
"s": 2101,
"text": "In order to load the data, I have βfor loopedβ through the items in the dictionary βdf_dictβ declared above. The empty dataframes are fed one by one using pandas read_csv function, which reads the data from URL generated using url_part + key (which are the respective names declared) + β.csvβ. And then, the column names are renamed to make it Python friendly."
},
{
"code": null,
"e": 2714,
"s": 2462,
"text": "Now comes the interesting part β the pandas melt function, which did the magic, enabling me to transform the data for my Tableau dashboard. Basically, the melt function unpivots a Dataframe from wide to long format. Refer the debug print output below:"
},
{
"code": null,
"e": 3052,
"s": 2714,
"text": "So, the melt function unpivots the 77 date columns from wide format to long format with heading of these columns being fed to a new column βDateβ created using value_vars = date_col, var_name = 'Date' parameter and numeric data being fed into a new column βconfirmed_globalβ created using value_name = key parameter of the melt function."
},
{
"code": null,
"e": 3217,
"s": 3052,
"text": "Then, the βDateβ column data type is changed to datetime and the key of the dictionary declared before is assigned with respective loaded and transformed dataframe."
},
{
"code": null,
"e": 3583,
"s": 3217,
"text": "join_on_col = ['Province_State','Country_Region','Lat','Long','Date']df_COVID = df_dict['confirmed_global'].merge(df_dict['deaths_global'], on=join_on_col, how='outer').merge(df_dict['recovered_global'], on=join_on_col, how='outer')df_COVID.rename(columns = {'confirmed_global':'Confirmed', 'deaths_global':'Deaths', 'recovered_global':'Recovered'}, inplace = True)"
},
{
"code": null,
"e": 3791,
"s": 3583,
"text": "Now, the pandas merge function is used to merge 3 different files having βProvince_Stateβ, βCountry_Regionβ, βLatβ, βLongβ, βDateβ in common. Then, column names of the merged dataframe βdf_COVIDβ is renamed."
},
{
"code": null,
"e": 4101,
"s": 3791,
"text": "# to fill the NaN in 'Province_State' columns with Countries name in 'Country_Region'df_COVID['Province_State'] = np.where(df_COVID['Province_State'] == 'nan', df_COVID['Country_Region'], df_COVID['Province_State'])# to fill the NaN in last three columnsdf_COVID.iloc[0:,-3:] = df_COVID.iloc[0:,-3:].fillna(0)"
},
{
"code": null,
"e": 4281,
"s": 4101,
"text": "This last line of code helps remove NaN from the dataframe βdf_COVIDβ as and where required. Later, this dataframe can be extracted to a .csv file using to_csv function of pandas."
},
{
"code": null,
"e": 4429,
"s": 4281,
"text": "But I planned to export it to Google Sheets β check how by following the second part of blog β Automated ETL for LIVE Tableau Public Visualizations"
},
{
"code": null,
"e": 4605,
"s": 4429,
"text": "Now that I have created a .py python script file to ETL (Extract, Transform and Load) the data, I realized that the GitHub repository used to source the data is updated daily."
},
{
"code": null,
"e": 4864,
"s": 4605,
"text": "In search for need to run the python script daily, I came across a blog β Automate your Python Scripts with Task Scheduler written by Vincent Tatan. However, if you are a Linux user, please refer Scheduling Jobs With Crontab on macOS written by Ratik Sharma."
},
{
"code": null,
"e": 4918,
"s": 4864,
"text": "This section is briefly curated from the former blog:"
},
{
"code": null,
"e": 5008,
"s": 4918,
"text": "Create Windows Executable .bat File to Run PythonConfigure Task in Windows Task Scheduler"
},
{
"code": null,
"e": 5058,
"s": 5008,
"text": "Create Windows Executable .bat File to Run Python"
},
{
"code": null,
"e": 5099,
"s": 5058,
"text": "Configure Task in Windows Task Scheduler"
},
{
"code": null,
"e": 5435,
"s": 5099,
"text": "A BAT file is a DOS batch file used to execute commands with the Windows Command Prompt (cmd.exe). It contains a series of line commands that typically might be entered at the DOS command prompt. BAT files are most commonly used to start programs and run maintenance utilities within Windows. Source: https://fileinfo.com/extension/bat"
},
{
"code": null,
"e": 5543,
"s": 5435,
"text": "Create a new .bat file (for e.g: etl-covid-data.bat) and edit it to write your command in following format:"
},
{
"code": null,
"e": 5590,
"s": 5543,
"text": "<python.exe location> <python script location>"
},
{
"code": null,
"e": 5766,
"s": 5590,
"text": "C:\\Users\\eklav\\AppData\\Local\\Programs\\Python\\Python37\\python.exe \"C:\\Users\\eklav\\Documents\\My Tableau Repository\\Datasources\\COVID-DataSource\\COVID-19\\COVID-DataExtraction.py\""
},
{
"code": null,
"e": 5951,
"s": 5766,
"text": "Please ensure that your Python37\\Lib\\site-packages has all the relevant libraries or modules installed. Else, execute pip install <module> on cmd.exe to download required dependencies."
},
{
"code": null,
"e": 6172,
"s": 5951,
"text": "For Debugging: Save and run this .bat file by double clicking it. You may type cmd /k before the command declared in .bat file. This will keep the Windows Command Prompt (cmd.exe) window open after execution of .bat file"
},
{
"code": null,
"e": 7260,
"s": 6172,
"text": "Search and open βTask Schedulerβ from βStartβ menuClick on βCreate Basic Task...β located under βActionsβ tab on the right side of the βTask SchedulerβDeclare the βName:β (for e.g: COVID-ETL-PyScriptRun) and βDescription:β (for e.g: This task will execute the python script required for COVID live updates)Task Trigger:Choose βWhen do you want the task to start?β (for e.g: Daily)Declare frequency parameters for the previous selectionAction:Choose βWhat action do you want the task to perform?β (for e.g: Start a program)Declare βProgram/script:β by browsing it to the .bat file location created earlier. Additionally, you may declare βStart in (optional):β to the location of your application folder to access the relevant dependenciesFinish:This shows the βSummaryβ of all the declarations above. You may tick the checkbox βOpen the Properties dialog for this task when I click Finishβ to discover interesting and helpful changes to your scheduled task. One edit that helped when my code broke was β On βGeneralβ tab of the task properties, I checked the βRun with highest privilegesβ"
},
{
"code": null,
"e": 7311,
"s": 7260,
"text": "Search and open βTask Schedulerβ from βStartβ menu"
},
{
"code": null,
"e": 7568,
"s": 7311,
"text": "Click on βCreate Basic Task...β located under βActionsβ tab on the right side of the βTask SchedulerβDeclare the βName:β (for e.g: COVID-ETL-PyScriptRun) and βDescription:β (for e.g: This task will execute the python script required for COVID live updates)"
},
{
"code": null,
"e": 7643,
"s": 7568,
"text": "Task Trigger:Choose βWhen do you want the task to start?β (for e.g: Daily)"
},
{
"code": null,
"e": 7699,
"s": 7643,
"text": "Declare frequency parameters for the previous selection"
},
{
"code": null,
"e": 7787,
"s": 7699,
"text": "Action:Choose βWhat action do you want the task to perform?β (for e.g: Start a program)"
},
{
"code": null,
"e": 8003,
"s": 7787,
"text": "Declare βProgram/script:β by browsing it to the .bat file location created earlier. Additionally, you may declare βStart in (optional):β to the location of your application folder to access the relevant dependencies"
},
{
"code": null,
"e": 8354,
"s": 8003,
"text": "Finish:This shows the βSummaryβ of all the declarations above. You may tick the checkbox βOpen the Properties dialog for this task when I click Finishβ to discover interesting and helpful changes to your scheduled task. One edit that helped when my code broke was β On βGeneralβ tab of the task properties, I checked the βRun with highest privilegesβ"
},
{
"code": null,
"e": 8415,
"s": 8354,
"text": "Following is the .gif animation for 7 steps mentioned above:"
},
{
"code": null,
"e": 8441,
"s": 8415,
"text": "About .BAT File Extension"
},
{
"code": null,
"e": 8482,
"s": 8441,
"text": "A Blog written by Vincent Tatan @ Medium"
},
{
"code": null,
"e": 8525,
"s": 8482,
"text": "Python Dataframe Constructor Documentation"
}
]
|
Creating Web Applications with D3 Observable | by Sean McClure | Towards Data Science | Iβve written previously about bringing D3 into web applications here, looking at how to bind D3 visuals to UI elements. The purpose was to encourage moving beyond stand-alone visuals and get people prototyping fuller applications. Real applications solicit feedback because they get used, helping us validate analyses beyond usual statistical measures. IMO if youβre not building a real product youβre not really learning/doing data science.
The previous article still stands, but D3 is changing directions towards what it calls Observable (formally known as d3.express). Observable provides a playground of sorts, allowing users to modify D3 code online inside a notebook. For those who use Jupyter Notebooks you will find the experience similar. Itβs essentially a REPL for doing D3.
Observable opens D3 up to true development since it now provides the ability to download your tailored D3 visual as a standalone βpackageβ (a tarball file) that you can embed inside your application. Observable comes with its own runtime and a standard library, which provides helpful functions for working with HTML, SVG, generators, files and promises.
Here is the Observable documentation:
observablehq.com
...and an opinionated writeup about their approach:
medium.com
You can find examples of visuals here, which you can immediately start playing around with in your browser. When youβre looking to create a new visualization visit the following site, choose a project, edit the visual as needed, and embed inside your application.
In this article weβll look at the following topics:
creating a quick app layout based off 2 simple mockups;
crafting components for our appβs UI elements;
embedding Observable inside our app;
sending data between our app and Observable;
using Googleβs Book API.
You can view the simple application here.
Letβs get started.
Letβs make a simple app that uses the Goodreads dataset hosted on Kaggle to allow people to explore book titles. The dataset lists book titles, their authors, ISBNs, and a few simple features like ratings.
Weβll allow the user to see a table of the original data and provide filtering functionality so users can search the table by author, ISBN number, and language.
Weβll also fetch book attributes from Googleβs Book API and showcase them in a bar chart. The API also provides an image URL of the selected book, so we will show the book cover when the user searches by ISBN:
Weβll stitch together Observable and Googleβs Book API into a real application using Azle.
We first create the following directory structure for our application:
appβββ dataβββ scriptsβββ d3_visuals ββ table ββ bar_chartβββ index.html
Bold names are empty folders and the index.html file is the usual Azle starting point:
Weβll add the needed files throughout this article. For now start a simple web server inside the app folder by running the following in a terminal session:
python3 -m http.server
...then point your browser to localhost:
http://localhost:8000
Iβll use Azle to create the scaffolding of my application. I created Azle because itβs fast to use, easy to understand, lightweight, flexible and free, and makes stitching together libraries and frameworks easy. But you can use whatever JS tools you like.
We create layouts using Azleβs az.add_layout function. This is how we create a grid on our page. Iβll place my layout code in Azleβs index.html file:
Read through the above code and you can easily tell how the page is being constructed. Every Azle function takes a βtarget_classβ and target_instance to add an element to the DOM. It also takes an object with properties. If weβre adding an element itβs a content object, and if weβre styling an element itβs a style object (usual CSS styles).
The above code produces the following:
We can see how layouts will allow us to position elements by demarcating areas on the screen. Letβs color our main section so it blends with the body color. We pass in usual CSS styling as properties to the style object:
az.style_sections('my_sections', 1, { "background": "rgb(51, 47, 47)", "height": "auto" })
Letβs also add a dark color to the background of our visual_layout:
az.style_layout('visual_layout', 1, { "align": "center", "background": "rgb(39, 36, 36)", "border-radius": "4px", "height": "460px", "margin-top": "10px", "column_widths": ['65%', '35%'], "border": 3 })
Now our application looks like this:
All our layout cells are waiting for their content. Thatβs where components come in.
Components are combined UI elements, styling, and events. Itβs like packaging up all the code necessary to create a specific part of our application. For example, if we wanted to have a calendar in our app we would create a calendar component and place it in one of our layout cells.
Creating components makes our code modular, easy to reuse, easier to maintain, and enables us to pivot our application more readily when ideas change. While we will be creating our components in Azle, these could also be React components added to Azle layouts.
From our mockup above we know we need search bars, icons, a dropdown menu, an image, and the D3 visuals. Showing how we create every component for this application is beyond the scope of this article. You can view the full application code here. Weβll create a few of the main ones in this article.
We place all component code inside the az.components object:
az.components = {}
Create a file called component.js and add the following code:
Looks like a lot but it reads easily. Note how we first add and style a layout, just like we did above, this time to hold our input box and search icon. We then add and style an input element into the first layout cell, then add and style the search icon into the second layout cell. Finally we add an event to our search icon so when the user clicks it, something happens.
Donβt worry about all the things being done inside our click event, we will address those after we embed our D3 visuals. Letβs now create our components for adding D3 visuals to our app. Hereβs the table example:
It looks a tad callback hellish but itβs readable. We add and style an iframe, wait until the iframe is done loading, ensure the full dataset is available, then post our message to the iframe. Message posting is how we communicate with D3. We will discuss this in the next section.
Adding our components works the same way Azle adds elements to an application:
az.components.d3_table(target_class, target_instance)
The above line will thus add our iframe to one of the cells in our app scaffolding. There arenβt any visuals to show inside those frames yet, so letβs go grab our Observable visuals, then weβll target them into their proper cells.
Embedding Observable is as simple as downloading the tarball of the desired visual, then hosting its index.html file inside an iframe. This isnβt the only way to bring Observable into an application, but itβs quick and works well for rapid prototyping.
We need a table and bar chart. These are both available with a little online searching:
observablehq.com
observablehq.com
We download their tarballs by clicking on the 3 dots in the upper right:
Once downloaded, unzip the tarball and place inside its respective folder:
We need our application to communicate with our Observable visuals. In the previous section we alluded to the use of az.post_message_to_frame to do this. Here is the function:
Azleβs post_message_to_frame allows our application to send data and functions inside iframes (as long as everything is on the same server there should be no CORS issues).
The main.redefine comes from Observable itself, and is how we can redefine variables and data in the D3 visual. The D3 table started with its data object called βfakeDataβ, thus we need to replace this with our book data from the Kaggle dataset. Youβll notice we are passing in a parent function called filter_by_author, rather than the data itself. Weβll discuss this shortly.
The other half of this equation is how D3 accepts the posted message. For our hosted Observable to accept incoming messages from our application we must add an event listener to the index.html file of the Observable:
And the Azle library to the top:
<script src='https://azlejs.com/v2/azle.min.js'></script>
So our D3 table index.html file should look like this:
To be clear, we are adding to this file:
The communication works because we are sending Observableβs main.redefine inside our frame using Azleβs post_message_to_frame, at which point our frame accepts that message and executes the parent.filter_by_author function (as shown in codeblock 5). The following figure depicts the concept:
Before we discuss parent functions letβs style our D3 visuals.
Since we downloaded the entire notebook there will be notebook cells we do not want to appear in our app (they are used to tailor the visual as a REPL). We should remove those cells.
We can do that by removing the following line from Observableβs index.html file:
const main = runtime.module(define, Inspector.into(document.body));
with the following:
const main = runtime.module(define, name => { if (name == 'chart') { return new Inspector(document.body) }});
This way only the chart will be drawn.
We can also style the D3 visual to make it look more modern. Check out the table-with-nested-data.js file inside the table folder. Compare the original file to the one I have prepared here to see styles Iβve added.
Here is the difference:
If you inspect the bar-chart.js file inside the bar_chart folder youβll see similar changes made.
We mentioned above the use of parent functions. In Figure 7 we see a 2-way communication between our application and Observable. Parent functions are how we call functions in our application from Observable.
We want Observable to redraw its D3 visual using new, filtered data. So weβll filter the original dataset (that we read in previously) using functions called from inside our iframes.
Create a file called parent_functions.js and place inside the scripts folder:
appβββ dataβββ scripts ββ parent_functions.jsβββ imgβββ d3_visuals ββ table ββ bar_chartβββ index.html
Here are the first 3 parent functions that return either the full dataset, data filtered by language, or data filtered by author.
Our frames will call these functions via codeblock 6 and replace the default visual dataset with the newly returned data.
Ai this point weβve built a simple app layout based on our mockup, crafted our components, set up our click events inside our components containing main.redefine, added event handlers to our D3 index files, and created parent functions for returning full and filtered data. Also, we have our D3 Observable visuals waiting in their folders.
All thatβs left for the D3 piece is to place our components into their target cells. We target our components like any other Azle function, using the target_class and target_instance of the destination layout cell.
First, we need to load our dataset into the application.
I downloaded the Kaggle Goodreads dataset as a CSV, then converted it into JSON using an online converter. I then downloaded the new JSON file and saved into the data folder of our app directory as books.json.
Now we can just use Azleβs read_local_file function to read in our dataset. Place it at the top of the index.html file:
I am saving the data as a new object called az.hold_value.full_dataset. You can use az.hold_value.[variable name] to make any variable or object globally available within the Azle namespace. Notice I am also βslicingβ the data to limit the number of rows shown in the app. You can remove this to show all data (or better, make a component that allows users to control how many rows are loaded :) )
Now I will use Azleβs call_once_satisfied function to ensure the full dataset has been loaded prior to calling our components:
This will add all components to our app layout once the condition of an existing data object is defined.
Our table looks like this:
If you play with the app youβll see users can filter the D3 table by author name and language. Many B2B applications benefit from this kind of functionality.
We still need to fulfill our mockup promise of showing a bar chart of information and the cover of the book, when a user searches by ISBN. Letβs do that now.
As mentioned earlier we can fetch book covers from ISBNs using the free Google Book API. A quick Google search points us to Stack Overflow answers showing how to use it (often faster than the usual documentation):
stackoverflow.com
We want the bar chart and book cover to appear after the user searches by ISBN. If you look at the search_by_isbn function inside components.js and inspect its click event youβll see how this is handled.
When a user pastes in an ISBN # and clicks the search icon 4 things happen:
the fetch_book_cover component is called;
the iframes have their displays toggled using the CSS display property inside az.style_iframe;
a message is posted to the iframe holding the bar chart, with the data filtered by ISBN;
the add_chart_buttons component is called to accompany the bar chart.
The fetch_book_cover component parses the data returned from Googleβs Book API and retrieves the required image URL:
data.items[0].volumeInfo.imageLinks.thumbnail
...which we can use as the image URL when we add the book cover to our app:
az.add_image('visual_layout_cells', 2, { "this_class": "cover_img", "image_path": data.items[0].volumeInfo.imageLinks.thumbnail})
If you look in component.js of the app code you will see a function for calling Googleβs Book API. It uses Azleβs call_api function along with the following URL:
"https://www.googleapis.com/books/v1/volumes?q=isbn:" + az.grab_value('search_isbn_bar', 1)
This simply concatenates the API url with the ISBN added by the user to the input field with class name βsearch_isbn_barβ.
Users can thus copy an ISBN number from the table and paste it into the search by isbn input field, which will draw the bar chart and show the bookβs cover:
Users can also change the bar chart view using the thin buttons below the bar chart. Here is the app gif again:
As mentioned earlier, you can read through the full codebase to see how the full app has been constructed. If you see a function that looks unfamiliar simply refer to Azleβs documentation. This article wanted to show the core pieces needed to bring D3 Observable into a real web application.
In this article we looked at embedding D3 Observable inside a web application. We used Azle to stitch together Observable and Googleβs Book API to create a real application that allows users to search and explore book titles.
Our tasks involved creating a quick layout based off 2 simple mockups, crafting and targeting components, embedding an Observable table and bar chart inside frames, communicating between app and Observable using message posting and event handlers, and finally using Googleβs Book API to populate the bar chart and show the book cover after searching by ISBN.
We only covered the major parts needed to connect D3 to apps. There is more code you can explore on the GitHub project. I encourage you to create your own applications, and find ways to bring your analyses to users via real products.
If you enjoyed this article you might also like: | [
{
"code": null,
"e": 614,
"s": 172,
"text": "Iβve written previously about bringing D3 into web applications here, looking at how to bind D3 visuals to UI elements. The purpose was to encourage moving beyond stand-alone visuals and get people prototyping fuller applications. Real applications solicit feedback because they get used, helping us validate analyses beyond usual statistical measures. IMO if youβre not building a real product youβre not really learning/doing data science."
},
{
"code": null,
"e": 958,
"s": 614,
"text": "The previous article still stands, but D3 is changing directions towards what it calls Observable (formally known as d3.express). Observable provides a playground of sorts, allowing users to modify D3 code online inside a notebook. For those who use Jupyter Notebooks you will find the experience similar. Itβs essentially a REPL for doing D3."
},
{
"code": null,
"e": 1313,
"s": 958,
"text": "Observable opens D3 up to true development since it now provides the ability to download your tailored D3 visual as a standalone βpackageβ (a tarball file) that you can embed inside your application. Observable comes with its own runtime and a standard library, which provides helpful functions for working with HTML, SVG, generators, files and promises."
},
{
"code": null,
"e": 1351,
"s": 1313,
"text": "Here is the Observable documentation:"
},
{
"code": null,
"e": 1368,
"s": 1351,
"text": "observablehq.com"
},
{
"code": null,
"e": 1420,
"s": 1368,
"text": "...and an opinionated writeup about their approach:"
},
{
"code": null,
"e": 1431,
"s": 1420,
"text": "medium.com"
},
{
"code": null,
"e": 1695,
"s": 1431,
"text": "You can find examples of visuals here, which you can immediately start playing around with in your browser. When youβre looking to create a new visualization visit the following site, choose a project, edit the visual as needed, and embed inside your application."
},
{
"code": null,
"e": 1747,
"s": 1695,
"text": "In this article weβll look at the following topics:"
},
{
"code": null,
"e": 1803,
"s": 1747,
"text": "creating a quick app layout based off 2 simple mockups;"
},
{
"code": null,
"e": 1850,
"s": 1803,
"text": "crafting components for our appβs UI elements;"
},
{
"code": null,
"e": 1887,
"s": 1850,
"text": "embedding Observable inside our app;"
},
{
"code": null,
"e": 1932,
"s": 1887,
"text": "sending data between our app and Observable;"
},
{
"code": null,
"e": 1957,
"s": 1932,
"text": "using Googleβs Book API."
},
{
"code": null,
"e": 1999,
"s": 1957,
"text": "You can view the simple application here."
},
{
"code": null,
"e": 2018,
"s": 1999,
"text": "Letβs get started."
},
{
"code": null,
"e": 2224,
"s": 2018,
"text": "Letβs make a simple app that uses the Goodreads dataset hosted on Kaggle to allow people to explore book titles. The dataset lists book titles, their authors, ISBNs, and a few simple features like ratings."
},
{
"code": null,
"e": 2385,
"s": 2224,
"text": "Weβll allow the user to see a table of the original data and provide filtering functionality so users can search the table by author, ISBN number, and language."
},
{
"code": null,
"e": 2595,
"s": 2385,
"text": "Weβll also fetch book attributes from Googleβs Book API and showcase them in a bar chart. The API also provides an image URL of the selected book, so we will show the book cover when the user searches by ISBN:"
},
{
"code": null,
"e": 2686,
"s": 2595,
"text": "Weβll stitch together Observable and Googleβs Book API into a real application using Azle."
},
{
"code": null,
"e": 2757,
"s": 2686,
"text": "We first create the following directory structure for our application:"
},
{
"code": null,
"e": 2832,
"s": 2757,
"text": "appβββ dataβββ scriptsβββ d3_visuals ββ table ββ bar_chartβββ index.html"
},
{
"code": null,
"e": 2919,
"s": 2832,
"text": "Bold names are empty folders and the index.html file is the usual Azle starting point:"
},
{
"code": null,
"e": 3075,
"s": 2919,
"text": "Weβll add the needed files throughout this article. For now start a simple web server inside the app folder by running the following in a terminal session:"
},
{
"code": null,
"e": 3098,
"s": 3075,
"text": "python3 -m http.server"
},
{
"code": null,
"e": 3139,
"s": 3098,
"text": "...then point your browser to localhost:"
},
{
"code": null,
"e": 3161,
"s": 3139,
"text": "http://localhost:8000"
},
{
"code": null,
"e": 3417,
"s": 3161,
"text": "Iβll use Azle to create the scaffolding of my application. I created Azle because itβs fast to use, easy to understand, lightweight, flexible and free, and makes stitching together libraries and frameworks easy. But you can use whatever JS tools you like."
},
{
"code": null,
"e": 3567,
"s": 3417,
"text": "We create layouts using Azleβs az.add_layout function. This is how we create a grid on our page. Iβll place my layout code in Azleβs index.html file:"
},
{
"code": null,
"e": 3910,
"s": 3567,
"text": "Read through the above code and you can easily tell how the page is being constructed. Every Azle function takes a βtarget_classβ and target_instance to add an element to the DOM. It also takes an object with properties. If weβre adding an element itβs a content object, and if weβre styling an element itβs a style object (usual CSS styles)."
},
{
"code": null,
"e": 3949,
"s": 3910,
"text": "The above code produces the following:"
},
{
"code": null,
"e": 4170,
"s": 3949,
"text": "We can see how layouts will allow us to position elements by demarcating areas on the screen. Letβs color our main section so it blends with the body color. We pass in usual CSS styling as properties to the style object:"
},
{
"code": null,
"e": 4263,
"s": 4170,
"text": "az.style_sections('my_sections', 1, { \"background\": \"rgb(51, 47, 47)\", \"height\": \"auto\" })"
},
{
"code": null,
"e": 4331,
"s": 4263,
"text": "Letβs also add a dark color to the background of our visual_layout:"
},
{
"code": null,
"e": 4541,
"s": 4331,
"text": "az.style_layout('visual_layout', 1, { \"align\": \"center\", \"background\": \"rgb(39, 36, 36)\", \"border-radius\": \"4px\", \"height\": \"460px\", \"margin-top\": \"10px\", \"column_widths\": ['65%', '35%'], \"border\": 3 })"
},
{
"code": null,
"e": 4578,
"s": 4541,
"text": "Now our application looks like this:"
},
{
"code": null,
"e": 4663,
"s": 4578,
"text": "All our layout cells are waiting for their content. Thatβs where components come in."
},
{
"code": null,
"e": 4947,
"s": 4663,
"text": "Components are combined UI elements, styling, and events. Itβs like packaging up all the code necessary to create a specific part of our application. For example, if we wanted to have a calendar in our app we would create a calendar component and place it in one of our layout cells."
},
{
"code": null,
"e": 5208,
"s": 4947,
"text": "Creating components makes our code modular, easy to reuse, easier to maintain, and enables us to pivot our application more readily when ideas change. While we will be creating our components in Azle, these could also be React components added to Azle layouts."
},
{
"code": null,
"e": 5507,
"s": 5208,
"text": "From our mockup above we know we need search bars, icons, a dropdown menu, an image, and the D3 visuals. Showing how we create every component for this application is beyond the scope of this article. You can view the full application code here. Weβll create a few of the main ones in this article."
},
{
"code": null,
"e": 5568,
"s": 5507,
"text": "We place all component code inside the az.components object:"
},
{
"code": null,
"e": 5587,
"s": 5568,
"text": "az.components = {}"
},
{
"code": null,
"e": 5649,
"s": 5587,
"text": "Create a file called component.js and add the following code:"
},
{
"code": null,
"e": 6023,
"s": 5649,
"text": "Looks like a lot but it reads easily. Note how we first add and style a layout, just like we did above, this time to hold our input box and search icon. We then add and style an input element into the first layout cell, then add and style the search icon into the second layout cell. Finally we add an event to our search icon so when the user clicks it, something happens."
},
{
"code": null,
"e": 6236,
"s": 6023,
"text": "Donβt worry about all the things being done inside our click event, we will address those after we embed our D3 visuals. Letβs now create our components for adding D3 visuals to our app. Hereβs the table example:"
},
{
"code": null,
"e": 6518,
"s": 6236,
"text": "It looks a tad callback hellish but itβs readable. We add and style an iframe, wait until the iframe is done loading, ensure the full dataset is available, then post our message to the iframe. Message posting is how we communicate with D3. We will discuss this in the next section."
},
{
"code": null,
"e": 6597,
"s": 6518,
"text": "Adding our components works the same way Azle adds elements to an application:"
},
{
"code": null,
"e": 6651,
"s": 6597,
"text": "az.components.d3_table(target_class, target_instance)"
},
{
"code": null,
"e": 6882,
"s": 6651,
"text": "The above line will thus add our iframe to one of the cells in our app scaffolding. There arenβt any visuals to show inside those frames yet, so letβs go grab our Observable visuals, then weβll target them into their proper cells."
},
{
"code": null,
"e": 7135,
"s": 6882,
"text": "Embedding Observable is as simple as downloading the tarball of the desired visual, then hosting its index.html file inside an iframe. This isnβt the only way to bring Observable into an application, but itβs quick and works well for rapid prototyping."
},
{
"code": null,
"e": 7223,
"s": 7135,
"text": "We need a table and bar chart. These are both available with a little online searching:"
},
{
"code": null,
"e": 7240,
"s": 7223,
"text": "observablehq.com"
},
{
"code": null,
"e": 7257,
"s": 7240,
"text": "observablehq.com"
},
{
"code": null,
"e": 7330,
"s": 7257,
"text": "We download their tarballs by clicking on the 3 dots in the upper right:"
},
{
"code": null,
"e": 7405,
"s": 7330,
"text": "Once downloaded, unzip the tarball and place inside its respective folder:"
},
{
"code": null,
"e": 7581,
"s": 7405,
"text": "We need our application to communicate with our Observable visuals. In the previous section we alluded to the use of az.post_message_to_frame to do this. Here is the function:"
},
{
"code": null,
"e": 7753,
"s": 7581,
"text": "Azleβs post_message_to_frame allows our application to send data and functions inside iframes (as long as everything is on the same server there should be no CORS issues)."
},
{
"code": null,
"e": 8131,
"s": 7753,
"text": "The main.redefine comes from Observable itself, and is how we can redefine variables and data in the D3 visual. The D3 table started with its data object called βfakeDataβ, thus we need to replace this with our book data from the Kaggle dataset. Youβll notice we are passing in a parent function called filter_by_author, rather than the data itself. Weβll discuss this shortly."
},
{
"code": null,
"e": 8348,
"s": 8131,
"text": "The other half of this equation is how D3 accepts the posted message. For our hosted Observable to accept incoming messages from our application we must add an event listener to the index.html file of the Observable:"
},
{
"code": null,
"e": 8381,
"s": 8348,
"text": "And the Azle library to the top:"
},
{
"code": null,
"e": 8439,
"s": 8381,
"text": "<script src='https://azlejs.com/v2/azle.min.js'></script>"
},
{
"code": null,
"e": 8494,
"s": 8439,
"text": "So our D3 table index.html file should look like this:"
},
{
"code": null,
"e": 8535,
"s": 8494,
"text": "To be clear, we are adding to this file:"
},
{
"code": null,
"e": 8827,
"s": 8535,
"text": "The communication works because we are sending Observableβs main.redefine inside our frame using Azleβs post_message_to_frame, at which point our frame accepts that message and executes the parent.filter_by_author function (as shown in codeblock 5). The following figure depicts the concept:"
},
{
"code": null,
"e": 8890,
"s": 8827,
"text": "Before we discuss parent functions letβs style our D3 visuals."
},
{
"code": null,
"e": 9073,
"s": 8890,
"text": "Since we downloaded the entire notebook there will be notebook cells we do not want to appear in our app (they are used to tailor the visual as a REPL). We should remove those cells."
},
{
"code": null,
"e": 9154,
"s": 9073,
"text": "We can do that by removing the following line from Observableβs index.html file:"
},
{
"code": null,
"e": 9222,
"s": 9154,
"text": "const main = runtime.module(define, Inspector.into(document.body));"
},
{
"code": null,
"e": 9242,
"s": 9222,
"text": "with the following:"
},
{
"code": null,
"e": 9357,
"s": 9242,
"text": "const main = runtime.module(define, name => { if (name == 'chart') { return new Inspector(document.body) }});"
},
{
"code": null,
"e": 9396,
"s": 9357,
"text": "This way only the chart will be drawn."
},
{
"code": null,
"e": 9611,
"s": 9396,
"text": "We can also style the D3 visual to make it look more modern. Check out the table-with-nested-data.js file inside the table folder. Compare the original file to the one I have prepared here to see styles Iβve added."
},
{
"code": null,
"e": 9635,
"s": 9611,
"text": "Here is the difference:"
},
{
"code": null,
"e": 9733,
"s": 9635,
"text": "If you inspect the bar-chart.js file inside the bar_chart folder youβll see similar changes made."
},
{
"code": null,
"e": 9941,
"s": 9733,
"text": "We mentioned above the use of parent functions. In Figure 7 we see a 2-way communication between our application and Observable. Parent functions are how we call functions in our application from Observable."
},
{
"code": null,
"e": 10124,
"s": 9941,
"text": "We want Observable to redraw its D3 visual using new, filtered data. So weβll filter the original dataset (that we read in previously) using functions called from inside our iframes."
},
{
"code": null,
"e": 10202,
"s": 10124,
"text": "Create a file called parent_functions.js and place inside the scripts folder:"
},
{
"code": null,
"e": 10308,
"s": 10202,
"text": "appβββ dataβββ scripts ββ parent_functions.jsβββ imgβββ d3_visuals ββ table ββ bar_chartβββ index.html"
},
{
"code": null,
"e": 10438,
"s": 10308,
"text": "Here are the first 3 parent functions that return either the full dataset, data filtered by language, or data filtered by author."
},
{
"code": null,
"e": 10560,
"s": 10438,
"text": "Our frames will call these functions via codeblock 6 and replace the default visual dataset with the newly returned data."
},
{
"code": null,
"e": 10900,
"s": 10560,
"text": "Ai this point weβve built a simple app layout based on our mockup, crafted our components, set up our click events inside our components containing main.redefine, added event handlers to our D3 index files, and created parent functions for returning full and filtered data. Also, we have our D3 Observable visuals waiting in their folders."
},
{
"code": null,
"e": 11115,
"s": 10900,
"text": "All thatβs left for the D3 piece is to place our components into their target cells. We target our components like any other Azle function, using the target_class and target_instance of the destination layout cell."
},
{
"code": null,
"e": 11172,
"s": 11115,
"text": "First, we need to load our dataset into the application."
},
{
"code": null,
"e": 11382,
"s": 11172,
"text": "I downloaded the Kaggle Goodreads dataset as a CSV, then converted it into JSON using an online converter. I then downloaded the new JSON file and saved into the data folder of our app directory as books.json."
},
{
"code": null,
"e": 11502,
"s": 11382,
"text": "Now we can just use Azleβs read_local_file function to read in our dataset. Place it at the top of the index.html file:"
},
{
"code": null,
"e": 11900,
"s": 11502,
"text": "I am saving the data as a new object called az.hold_value.full_dataset. You can use az.hold_value.[variable name] to make any variable or object globally available within the Azle namespace. Notice I am also βslicingβ the data to limit the number of rows shown in the app. You can remove this to show all data (or better, make a component that allows users to control how many rows are loaded :) )"
},
{
"code": null,
"e": 12027,
"s": 11900,
"text": "Now I will use Azleβs call_once_satisfied function to ensure the full dataset has been loaded prior to calling our components:"
},
{
"code": null,
"e": 12132,
"s": 12027,
"text": "This will add all components to our app layout once the condition of an existing data object is defined."
},
{
"code": null,
"e": 12159,
"s": 12132,
"text": "Our table looks like this:"
},
{
"code": null,
"e": 12317,
"s": 12159,
"text": "If you play with the app youβll see users can filter the D3 table by author name and language. Many B2B applications benefit from this kind of functionality."
},
{
"code": null,
"e": 12475,
"s": 12317,
"text": "We still need to fulfill our mockup promise of showing a bar chart of information and the cover of the book, when a user searches by ISBN. Letβs do that now."
},
{
"code": null,
"e": 12689,
"s": 12475,
"text": "As mentioned earlier we can fetch book covers from ISBNs using the free Google Book API. A quick Google search points us to Stack Overflow answers showing how to use it (often faster than the usual documentation):"
},
{
"code": null,
"e": 12707,
"s": 12689,
"text": "stackoverflow.com"
},
{
"code": null,
"e": 12911,
"s": 12707,
"text": "We want the bar chart and book cover to appear after the user searches by ISBN. If you look at the search_by_isbn function inside components.js and inspect its click event youβll see how this is handled."
},
{
"code": null,
"e": 12987,
"s": 12911,
"text": "When a user pastes in an ISBN # and clicks the search icon 4 things happen:"
},
{
"code": null,
"e": 13029,
"s": 12987,
"text": "the fetch_book_cover component is called;"
},
{
"code": null,
"e": 13124,
"s": 13029,
"text": "the iframes have their displays toggled using the CSS display property inside az.style_iframe;"
},
{
"code": null,
"e": 13213,
"s": 13124,
"text": "a message is posted to the iframe holding the bar chart, with the data filtered by ISBN;"
},
{
"code": null,
"e": 13283,
"s": 13213,
"text": "the add_chart_buttons component is called to accompany the bar chart."
},
{
"code": null,
"e": 13400,
"s": 13283,
"text": "The fetch_book_cover component parses the data returned from Googleβs Book API and retrieves the required image URL:"
},
{
"code": null,
"e": 13446,
"s": 13400,
"text": "data.items[0].volumeInfo.imageLinks.thumbnail"
},
{
"code": null,
"e": 13522,
"s": 13446,
"text": "...which we can use as the image URL when we add the book cover to our app:"
},
{
"code": null,
"e": 13660,
"s": 13522,
"text": "az.add_image('visual_layout_cells', 2, { \"this_class\": \"cover_img\", \"image_path\": data.items[0].volumeInfo.imageLinks.thumbnail})"
},
{
"code": null,
"e": 13822,
"s": 13660,
"text": "If you look in component.js of the app code you will see a function for calling Googleβs Book API. It uses Azleβs call_api function along with the following URL:"
},
{
"code": null,
"e": 13914,
"s": 13822,
"text": "\"https://www.googleapis.com/books/v1/volumes?q=isbn:\" + az.grab_value('search_isbn_bar', 1)"
},
{
"code": null,
"e": 14037,
"s": 13914,
"text": "This simply concatenates the API url with the ISBN added by the user to the input field with class name βsearch_isbn_barβ."
},
{
"code": null,
"e": 14194,
"s": 14037,
"text": "Users can thus copy an ISBN number from the table and paste it into the search by isbn input field, which will draw the bar chart and show the bookβs cover:"
},
{
"code": null,
"e": 14306,
"s": 14194,
"text": "Users can also change the bar chart view using the thin buttons below the bar chart. Here is the app gif again:"
},
{
"code": null,
"e": 14598,
"s": 14306,
"text": "As mentioned earlier, you can read through the full codebase to see how the full app has been constructed. If you see a function that looks unfamiliar simply refer to Azleβs documentation. This article wanted to show the core pieces needed to bring D3 Observable into a real web application."
},
{
"code": null,
"e": 14824,
"s": 14598,
"text": "In this article we looked at embedding D3 Observable inside a web application. We used Azle to stitch together Observable and Googleβs Book API to create a real application that allows users to search and explore book titles."
},
{
"code": null,
"e": 15183,
"s": 14824,
"text": "Our tasks involved creating a quick layout based off 2 simple mockups, crafting and targeting components, embedding an Observable table and bar chart inside frames, communicating between app and Observable using message posting and event handlers, and finally using Googleβs Book API to populate the bar chart and show the book cover after searching by ISBN."
},
{
"code": null,
"e": 15417,
"s": 15183,
"text": "We only covered the major parts needed to connect D3 to apps. There is more code you can explore on the GitHub project. I encourage you to create your own applications, and find ways to bring your analyses to users via real products."
}
]
|
Neon Text Display Using HTML & CSS - GeeksforGeeks | 31 Jul, 2019
In this article, you will learn to create a neon text display using HTML & CSS.The neon text display is the simplest yet one of the most striking effects used to give cool designing to your texts on your web pages. In the neon display, the color of the text glows continuously that you can control by animation time. The text gets glowing effect using the text-shadow property with some color combinations.Approach: First of all, we will add the text which we want to display in neon style in a span class. Then in this class, we set the font color according to our desire. Then we have to use the animation property and give it a name. In the animation, we set the animation-timing to ease-in-out for a slow start and slow end of the animation, the animation iteration to infinite for continuous display, and finally the animation direction to alternate so that the animation goes forwards first, then backward.
Then we use the @keyframes to specify the animation code. In the @keyframes we use the text-shadow property, and apply various color combinations to create the neon light effect.
Example 1:
<!DOCTYPE HTML><html lang="en"> <head> <meta charset="UTF-8"> <title>Neon text Display Using HTML and CSS</title> <style> body { margin: 10px; font-family: sans-sarif; height: 100%; } /* values of properties of animation assigned */ .neon-header { text-align: center; line-height: 2; color: green; animation: neon 1s ease-in-out infinite alternate; margin-left: 200px; } /* various colour combinations used to create neon effect */ @keyframes neon { from { text-shadow: 0 0 35px #85FF64, 0 0 40px #2BBF03, 0 0 55px #141ae2; } </style></head> <body> <center> <!-- text we want to display --> <span class="neon-header"> <h1>GeeksforGeeks</h1> </span> <p1>A Computer Science Portal for Geeks</p1> </center></body> </html>
Output:
Note: You can out the displayed text in any tag not necessary to contain the text in the <span> tag.
Example:2: In this example, you will see that the text is glowing from shade to other shades this one is more eye attractive.
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Neon text Display Using HTML and CSS</title> <style> body { background-color: black; } .glow { font-size: 60px; color: green; text-align: center; animation: glow 2s ease-in-out infinite alternate; } /* Text glowing from onw shade to other shade */ @-webkit-keyframes glow { from { text-shadow: 0 0 10px rgb(43, 255, 0), 0 0 20px rgb(43, 255, 0), 0 0 30px #26e600, 0 0 40px #26e600, 0 0 50px #26e600, 0 0 60px #26e600, 0 0 70px #26e600; } to { text-shadow: 0 0 20px #4dff7a; 0 0 30px #4dff7a, 0 0 40px #4dff7a, 0 0 50px #4dff7a, 0 0 60px #4dff7a, 0 0 70px #4dff7a, 0 0 80px #4dff7a; } } </style></head> <body> <!-- Content will Glow --> <h1 class="glow">GeeksforGeeks</h1> </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.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Making a div vertically scrollable using CSS
Build a Survey Form using HTML and CSS
CSS | Text Formatting
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 24279,
"s": 24251,
"text": "\n31 Jul, 2019"
},
{
"code": null,
"e": 25192,
"s": 24279,
"text": "In this article, you will learn to create a neon text display using HTML & CSS.The neon text display is the simplest yet one of the most striking effects used to give cool designing to your texts on your web pages. In the neon display, the color of the text glows continuously that you can control by animation time. The text gets glowing effect using the text-shadow property with some color combinations.Approach: First of all, we will add the text which we want to display in neon style in a span class. Then in this class, we set the font color according to our desire. Then we have to use the animation property and give it a name. In the animation, we set the animation-timing to ease-in-out for a slow start and slow end of the animation, the animation iteration to infinite for continuous display, and finally the animation direction to alternate so that the animation goes forwards first, then backward."
},
{
"code": null,
"e": 25371,
"s": 25192,
"text": "Then we use the @keyframes to specify the animation code. In the @keyframes we use the text-shadow property, and apply various color combinations to create the neon light effect."
},
{
"code": null,
"e": 25382,
"s": 25371,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE HTML><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Neon text Display Using HTML and CSS</title> <style> body { margin: 10px; font-family: sans-sarif; height: 100%; } /* values of properties of animation assigned */ .neon-header { text-align: center; line-height: 2; color: green; animation: neon 1s ease-in-out infinite alternate; margin-left: 200px; } /* various colour combinations used to create neon effect */ @keyframes neon { from { text-shadow: 0 0 35px #85FF64, 0 0 40px #2BBF03, 0 0 55px #141ae2; } </style></head> <body> <center> <!-- text we want to display --> <span class=\"neon-header\"> <h1>GeeksforGeeks</h1> </span> <p1>A Computer Science Portal for Geeks</p1> </center></body> </html>",
"e": 26396,
"s": 25382,
"text": null
},
{
"code": null,
"e": 26404,
"s": 26396,
"text": "Output:"
},
{
"code": null,
"e": 26505,
"s": 26404,
"text": "Note: You can out the displayed text in any tag not necessary to contain the text in the <span> tag."
},
{
"code": null,
"e": 26631,
"s": 26505,
"text": "Example:2: In this example, you will see that the text is glowing from shade to other shades this one is more eye attractive."
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <title>Neon text Display Using HTML and CSS</title> <style> body { background-color: black; } .glow { font-size: 60px; color: green; text-align: center; animation: glow 2s ease-in-out infinite alternate; } /* Text glowing from onw shade to other shade */ @-webkit-keyframes glow { from { text-shadow: 0 0 10px rgb(43, 255, 0), 0 0 20px rgb(43, 255, 0), 0 0 30px #26e600, 0 0 40px #26e600, 0 0 50px #26e600, 0 0 60px #26e600, 0 0 70px #26e600; } to { text-shadow: 0 0 20px #4dff7a; 0 0 30px #4dff7a, 0 0 40px #4dff7a, 0 0 50px #4dff7a, 0 0 60px #4dff7a, 0 0 70px #4dff7a, 0 0 80px #4dff7a; } } </style></head> <body> <!-- Content will Glow --> <h1 class=\"glow\">GeeksforGeeks</h1> </body> </html>",
"e": 27998,
"s": 26631,
"text": null
},
{
"code": null,
"e": 28006,
"s": 27998,
"text": "Output:"
},
{
"code": null,
"e": 28143,
"s": 28006,
"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": 28152,
"s": 28143,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28162,
"s": 28152,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28166,
"s": 28162,
"text": "CSS"
},
{
"code": null,
"e": 28171,
"s": 28166,
"text": "HTML"
},
{
"code": null,
"e": 28188,
"s": 28171,
"text": "Web Technologies"
},
{
"code": null,
"e": 28193,
"s": 28188,
"text": "HTML"
},
{
"code": null,
"e": 28291,
"s": 28193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28300,
"s": 28291,
"text": "Comments"
},
{
"code": null,
"e": 28313,
"s": 28300,
"text": "Old Comments"
},
{
"code": null,
"e": 28371,
"s": 28313,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28408,
"s": 28371,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28453,
"s": 28408,
"text": "Making a div vertically scrollable using CSS"
},
{
"code": null,
"e": 28492,
"s": 28453,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 28514,
"s": 28492,
"text": "CSS | Text Formatting"
},
{
"code": null,
"e": 28574,
"s": 28514,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28635,
"s": 28574,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28672,
"s": 28635,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28725,
"s": 28672,
"text": "Hide or show elements in HTML using display property"
}
]
|
VBScript - Syntax | Let us write a VBScript to print out "Hello World".
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>
In the above example, we called a function document.write, which writes a string into the HTML document. This function can be used to write text, HTML or both. So, above code will display following result β
Hello World!
VBScript ignores spaces, tabs, and newlines that appear within VBScript programs. One can use spaces, tabs, and newlines freely within the program, so you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.
VBScript is based on Microsoft's Visual Basic. Unlike JavaScript, no statement terminators such as semicolon is used to terminate a particular statement.
Colons are used when two or more lines of VBScript ought to be written in a single line. Hence, in VBScript, Colons act as a line separator.
<script language = "vbscript" type = "text/vbscript">
var1 = 10 : var2 = 20
</script>
When a statement in VBScript is lengthy and if user wishes to break it into multiple lines, then the user has to use underscore "_". This improves the readability of the code. The following example illustrates how to work with multiple lines.
<script language = "vbscript" type = "text/vbscript">
var1 = 10
var2 = 20
Sum = var1 + var2
document.write("The Sum of two numbers"&_"var1 and var2 is " & Sum)
</script>
The following list shows the reserved words in VBScript. These reserved words SHOULD NOT be used as a constant or variable or any other identifier names.
VBScript is a case-insensitive language. This means that language keywords, variables, function names and any other identifiers need NOT be typed with a consistent capitalization of letters. So identifiers int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript.
Comments are used to document the program logic and the user information with which other programmers can seamlessly work on the same code in future. It can include information such as developed by, modified by and it can also include incorporated logic. Comments are ignored by the interpreter while execution. Comments in VBScript are denoted by two methods.
1. Any statement that starts with a Single Quote (β) is treated as comment.
Following is the example β
<script language = "vbscript" type = "text/vbscript">
<!β
' This Script is invoked after successful login
' Written by : TutorialsPoint
' Return Value : True / False
//- >
</script>
2. Any statement that starts with the keyword βREMβ.
Following is the example β
<script language = "vbscript" type = "text/vbscript">
<!β
REM This Script is written to Validate the Entered Input
REM Modified by : Tutorials point/user2
//- >
</script>
63 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2132,
"s": 2080,
"text": "Let us write a VBScript to print out \"Hello World\"."
},
{
"code": null,
"e": 2284,
"s": 2132,
"text": "<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n document.write(\"Hello World!\")\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2491,
"s": 2284,
"text": "In the above example, we called a function document.write, which writes a string into the HTML document. This function can be used to write text, HTML or both. So, above code will display following result β"
},
{
"code": null,
"e": 2505,
"s": 2491,
"text": "Hello World!\n"
},
{
"code": null,
"e": 2782,
"s": 2505,
"text": "VBScript ignores spaces, tabs, and newlines that appear within VBScript programs. One can use spaces, tabs, and newlines freely within the program, so you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand."
},
{
"code": null,
"e": 2936,
"s": 2782,
"text": "VBScript is based on Microsoft's Visual Basic. Unlike JavaScript, no statement terminators such as semicolon is used to terminate a particular statement."
},
{
"code": null,
"e": 3077,
"s": 2936,
"text": "Colons are used when two or more lines of VBScript ought to be written in a single line. Hence, in VBScript, Colons act as a line separator."
},
{
"code": null,
"e": 3167,
"s": 3077,
"text": "<script language = \"vbscript\" type = \"text/vbscript\">\n var1 = 10 : var2 = 20\n</script>\n"
},
{
"code": null,
"e": 3410,
"s": 3167,
"text": "When a statement in VBScript is lengthy and if user wishes to break it into multiple lines, then the user has to use underscore \"_\". This improves the readability of the code. The following example illustrates how to work with multiple lines."
},
{
"code": null,
"e": 3595,
"s": 3410,
"text": "<script language = \"vbscript\" type = \"text/vbscript\">\n var1 = 10 \n var2 = 20\n Sum = var1 + var2 \n document.write(\"The Sum of two numbers\"&_\"var1 and var2 is \" & Sum)\n</script>"
},
{
"code": null,
"e": 3749,
"s": 3595,
"text": "The following list shows the reserved words in VBScript. These reserved words SHOULD NOT be used as a constant or variable or any other identifier names."
},
{
"code": null,
"e": 4035,
"s": 3749,
"text": "VBScript is a case-insensitive language. This means that language keywords, variables, function names and any other identifiers need NOT be typed with a consistent capitalization of letters. So identifiers int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript."
},
{
"code": null,
"e": 4396,
"s": 4035,
"text": "Comments are used to document the program logic and the user information with which other programmers can seamlessly work on the same code in future. It can include information such as developed by, modified by and it can also include incorporated logic. Comments are ignored by the interpreter while execution. Comments in VBScript are denoted by two methods."
},
{
"code": null,
"e": 4472,
"s": 4396,
"text": "1. Any statement that starts with a Single Quote (β) is treated as comment."
},
{
"code": null,
"e": 4499,
"s": 4472,
"text": "Following is the example β"
},
{
"code": null,
"e": 4705,
"s": 4499,
"text": "<script language = \"vbscript\" type = \"text/vbscript\">\n <!β\n ' This Script is invoked after successful login\n ' Written by : TutorialsPoint\n ' Return Value : True / False\n //- >\n</script>"
},
{
"code": null,
"e": 4758,
"s": 4705,
"text": "2. Any statement that starts with the keyword βREMβ."
},
{
"code": null,
"e": 4785,
"s": 4758,
"text": "Following is the example β"
},
{
"code": null,
"e": 4975,
"s": 4785,
"text": "<script language = \"vbscript\" type = \"text/vbscript\">\n <!β\n REM This Script is written to Validate the Entered Input\n REM Modified by : Tutorials point/user2\n //- >\n</script>"
},
{
"code": null,
"e": 5008,
"s": 4975,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5025,
"s": 5008,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5032,
"s": 5025,
"text": " Print"
},
{
"code": null,
"e": 5043,
"s": 5032,
"text": " Add Notes"
}
]
|
XML - WhiteSpaces | In this chapter, we will discuss whitespace handling in XML documents. Whitespace is a collection of spaces, tabs, and newlines. They are generally used to make a document more readable.
XML document contains two types of whitespaces - Significant Whitespace and Insignificant Whitespace. Both are explained below with examples.
A significant Whitespace occurs within the element which contains text and markup present together. For example β
<name>TanmayPatil</name>
and
<name>Tanmay Patil</name>
The above two elements are different because of the space between Tanmay and Patil. Any program reading this element in an XML file is obliged to maintain the distinction.
Insignificant whitespace means the space where only element content is allowed. For example β
<address.category = "residence">
<address....category = "..residence">
The above examples are same. Here, the space is represented by dots (.). In the above
example, the space between address and category is insignificant.
A special attribute named xml:space may be attached to an element. This indicates that whitespace should not be removed for that element by the application. You can set this attribute to default or preserve as shown in the following example β
<!ATTLIST address xml:space (default|preserve) 'preserve'>
Where,
The value default signals that the default whitespace processing modes of an application are acceptable for this element.
The value default signals that the default whitespace processing modes of an application are acceptable for this element.
The value preserve indicates the application to preserve all the whitespaces.
The value preserve indicates the application to preserve all the whitespaces.
84 Lectures
6 hours
Frahaan Hussain
29 Lectures
2 hours
YouAccel
27 Lectures
1 hours
Jordan Stanchev
16 Lectures
2 hours
Simon Sez IT
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2148,
"s": 1961,
"text": "In this chapter, we will discuss whitespace handling in XML documents. Whitespace is a collection of spaces, tabs, and newlines. They are generally used to make a document more readable."
},
{
"code": null,
"e": 2290,
"s": 2148,
"text": "XML document contains two types of whitespaces - Significant Whitespace and Insignificant Whitespace. Both are explained below with examples."
},
{
"code": null,
"e": 2404,
"s": 2290,
"text": "A significant Whitespace occurs within the element which contains text and markup present together. For example β"
},
{
"code": null,
"e": 2429,
"s": 2404,
"text": "<name>TanmayPatil</name>"
},
{
"code": null,
"e": 2433,
"s": 2429,
"text": "and"
},
{
"code": null,
"e": 2459,
"s": 2433,
"text": "<name>Tanmay Patil</name>"
},
{
"code": null,
"e": 2631,
"s": 2459,
"text": "The above two elements are different because of the space between Tanmay and Patil. Any program reading this element in an XML file is obliged to maintain the distinction."
},
{
"code": null,
"e": 2725,
"s": 2631,
"text": "Insignificant whitespace means the space where only element content is allowed. For example β"
},
{
"code": null,
"e": 2758,
"s": 2725,
"text": "<address.category = \"residence\">"
},
{
"code": null,
"e": 2796,
"s": 2758,
"text": "<address....category = \"..residence\">"
},
{
"code": null,
"e": 2948,
"s": 2796,
"text": "The above examples are same. Here, the space is represented by dots (.). In the above\nexample, the space between address and category is insignificant."
},
{
"code": null,
"e": 3191,
"s": 2948,
"text": "A special attribute named xml:space may be attached to an element. This indicates that whitespace should not be removed for that element by the application. You can set this attribute to default or preserve as shown in the following example β"
},
{
"code": null,
"e": 3252,
"s": 3191,
"text": "<!ATTLIST address xml:space (default|preserve) 'preserve'>\n"
},
{
"code": null,
"e": 3259,
"s": 3252,
"text": "Where,"
},
{
"code": null,
"e": 3381,
"s": 3259,
"text": "The value default signals that the default whitespace processing modes of an application are acceptable for this element."
},
{
"code": null,
"e": 3503,
"s": 3381,
"text": "The value default signals that the default whitespace processing modes of an application are acceptable for this element."
},
{
"code": null,
"e": 3581,
"s": 3503,
"text": "The value preserve indicates the application to preserve all the whitespaces."
},
{
"code": null,
"e": 3659,
"s": 3581,
"text": "The value preserve indicates the application to preserve all the whitespaces."
},
{
"code": null,
"e": 3692,
"s": 3659,
"text": "\n 84 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3709,
"s": 3692,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3742,
"s": 3709,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3752,
"s": 3742,
"text": " YouAccel"
},
{
"code": null,
"e": 3785,
"s": 3752,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3802,
"s": 3785,
"text": " Jordan Stanchev"
},
{
"code": null,
"e": 3835,
"s": 3802,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3849,
"s": 3835,
"text": " Simon Sez IT"
},
{
"code": null,
"e": 3856,
"s": 3849,
"text": " Print"
},
{
"code": null,
"e": 3867,
"s": 3856,
"text": " Add Notes"
}
]
|
How to subtract one polynomial to another using NumPy in Python? - GeeksforGeeks | 29 Aug, 2020
In this article, letβs discuss how to subtract one polynomial to another. Two polynomials are given as input and the result is the subtraction of two polynomials.
The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}.
Let take two polynomials p(x) and q(x) then subtract these to get r(x) = p(x) β q(x) as a result of subtraction of two input polynomials.
If p(x) = A3 x2 + A2 x + A1
and
q(x) = B3 x2 + B2 x + B1
then result is
r(x) = p(x) - q(x) i.e;
r(x) = (A3 - B3) x2 + (A2 - B2) x + (A1 - B1)
and output is
( (A1 - B1), (A2 - B2), (A3 - B3) ).
In NumPy, it can be solved using the polysub() method. This function helps to find the difference of two polynomials and then returning the result as a polynomial
Below is the implementation with some examples :
Example 1: Using polysub()
Python3
# importing packageimport numpy # define the polynomials# p(x) = 5(x**2) + (-2)x +5px = (5,-2,5) # q(x) = 2(x**2) + (-5)x +2qx = (2,-5,2) # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx) # print the resultant polynomialprint(rx)
Output :
[ 3. 3. 3.]
Example 2: sub_with_decimals
Python3
# importing packageimport numpy # define the polynomials# p(x) = 2.2px = (0,0,2.2) # q(x) = 9.8(x**2) + 4qx = (9.8,0,4) # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx) # print the resultant polynomialprint(rx)
Output :
[-9.8 0. -1.8]
Example 3: #eval_then_sub
Python3
# importing packageimport numpy # define the polynomials# p(x) = (5/3)xpx = (0,5/3,0) # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4,0,9/5) # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx) # print the resultant polynomialprint(rx)
Output :
[ 1.75 1.66666667 -1.8 ]
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 24455,
"s": 24292,
"text": "In this article, letβs discuss how to subtract one polynomial to another. Two polynomials are given as input and the result is the subtraction of two polynomials."
},
{
"code": null,
"e": 24573,
"s": 24455,
"text": "The polynomial p(x) = C3 x2 + C2 x + C1 is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}."
},
{
"code": null,
"e": 24711,
"s": 24573,
"text": "Let take two polynomials p(x) and q(x) then subtract these to get r(x) = p(x) β q(x) as a result of subtraction of two input polynomials."
},
{
"code": null,
"e": 24912,
"s": 24711,
"text": "If p(x) = A3 x2 + A2 x + A1 \nand\nq(x) = B3 x2 + B2 x + B1 \n\nthen result is \nr(x) = p(x) - q(x) i.e;\nr(x) = (A3 - B3) x2 + (A2 - B2) x + (A1 - B1) \n\nand output is \n( (A1 - B1), (A2 - B2), (A3 - B3) ).\n"
},
{
"code": null,
"e": 25075,
"s": 24912,
"text": "In NumPy, it can be solved using the polysub() method. This function helps to find the difference of two polynomials and then returning the result as a polynomial"
},
{
"code": null,
"e": 25124,
"s": 25075,
"text": "Below is the implementation with some examples :"
},
{
"code": null,
"e": 25153,
"s": 25124,
"text": "Example 1: Using polysub()"
},
{
"code": null,
"e": 25161,
"s": 25153,
"text": "Python3"
},
{
"code": "# importing packageimport numpy # define the polynomials# p(x) = 5(x**2) + (-2)x +5px = (5,-2,5) # q(x) = 2(x**2) + (-5)x +2qx = (2,-5,2) # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx) # print the resultant polynomialprint(rx)",
"e": 25419,
"s": 25161,
"text": null
},
{
"code": null,
"e": 25428,
"s": 25419,
"text": "Output :"
},
{
"code": null,
"e": 25442,
"s": 25428,
"text": "[ 3. 3. 3.]"
},
{
"code": null,
"e": 25471,
"s": 25442,
"text": "Example 2: sub_with_decimals"
},
{
"code": null,
"e": 25479,
"s": 25471,
"text": "Python3"
},
{
"code": "# importing packageimport numpy # define the polynomials# p(x) = 2.2px = (0,0,2.2) # q(x) = 9.8(x**2) + 4qx = (9.8,0,4) # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx) # print the resultant polynomialprint(rx)",
"e": 25719,
"s": 25479,
"text": null
},
{
"code": null,
"e": 25728,
"s": 25719,
"text": "Output :"
},
{
"code": null,
"e": 25746,
"s": 25728,
"text": "[-9.8 0. -1.8]\n"
},
{
"code": null,
"e": 25773,
"s": 25746,
"text": "Example 3: #eval_then_sub"
},
{
"code": null,
"e": 25781,
"s": 25773,
"text": "Python3"
},
{
"code": "# importing packageimport numpy # define the polynomials# p(x) = (5/3)xpx = (0,5/3,0) # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4,0,9/5) # subtract the polynomialsrx = numpy.polynomial.polynomial.polysub(px,qx) # print the resultant polynomialprint(rx)",
"e": 26034,
"s": 25781,
"text": null
},
{
"code": null,
"e": 26043,
"s": 26034,
"text": "Output :"
},
{
"code": null,
"e": 26089,
"s": 26043,
"text": "[ 1.75 1.66666667 -1.8 ] \n"
},
{
"code": null,
"e": 26124,
"s": 26089,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 26137,
"s": 26124,
"text": "Python-numpy"
},
{
"code": null,
"e": 26144,
"s": 26137,
"text": "Python"
},
{
"code": null,
"e": 26242,
"s": 26144,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26274,
"s": 26242,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26316,
"s": 26274,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26372,
"s": 26316,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26414,
"s": 26372,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26445,
"s": 26414,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26500,
"s": 26445,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26522,
"s": 26500,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26561,
"s": 26522,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26590,
"s": 26561,
"text": "Create a directory in Python"
}
]
|
How To Fit A Random Forest Classifier In Julia | by Emmett Boudreau | Towards Data Science | Within the past few years of very rapid development in data science technology, we have seen the dramatic escalation and adoption of a multitude of open-source tools. Among these are well-known tools like SkLearn and Tensorflow. With the recent early adoption of Julia, however, there are oppurtunities to dramatically improve our strategic approaches to solving machine-learning problems. The problem that effects the Julia language most is easily the lack of mature packages for various science or data related operations.
notebook
While this has been a long road that is certainly still being traveled, I think it is work taking a look at what Julia has to offer in its current state that hadnβt been there before. One recent addition I have been excited about is the addition of a Random Forest Classifier to Lathe. Using Lathe, DataFrames, and CSV, we can now easily explore, encode, and predict with various features!
Of course, in order to work with a machine-learning model, we are first going to need to take a look at getting some categorical data to train it with. For this example, I am going to be using some UCLA Data that has been published on European Cars. Since the data is in comma separated value (CSV) format, we are going to use the CSV.jl package. One fantastic attribute of Juliaβs ecosystem is the level of segmentation β though it can be a burden. CSV.jl is a package exclusively developed to read CSV.jl and return a data frame just as JSON.jl is a package exclusively developed to read JSON formatted data. While we are at it, we are going to want to also import DataFrames.jl, which will allow us to actually visualize our data in a tabular spreadsheet.
using DataFramesusing CSV
Now I will read in our CSV file:
df = CSV.read("car data.csv")
In the very near future, this method of reading .CSV files will be deprecated, so it is probably best to use a sink argument:
using DataFrames; df = CSV.read("car data.csv", DataFrame)
The easiest way to get a great view of our DataFrame is to use the show() method. In order to visualize our features better, we can use the allcols key-word argument, which will take a Bool type:
show(df, allcols = true)
Given that the purpose here is demonstration, not much thought is going be given towards the features other than what will work for this application. In order to see unique categories, we can use the Set() type:
Set(df[!, :Transmission])
Given that Gini-Index based models like this classifier that work off of impurity often do better with higher categorical counts, I selected the fuel type to be my target. As for the feature in this application, it was quite a difficult decision to make. I decided to go with a continuous target, since it would be quite hard to predict off of one set of 0's and 1βs and the dispatch for DataFrame data still has yet to be implemented in Lathe (meaning we can only support one feature in this unstable version.)
The first thing I decided to do was extract these two features I wanted to work with into a new and smaller DataFrame, like so:
mldf = DataFrame(:Fuel => df[!, :Fuel_Type], :Kms => df[!, :Kms_Driven])
If you would like to learn more about the DataFrames.jl package, I have a recent and effective article that might do some work to help you in getting started!:
An important step of working with any model is preprocessing, and evaluation. This is where you might want to question whether or not a model could actually help to solve this problem. This can be done with a majority class baseline. A majority class baseline is a simple measurement of how effective of an approach it might be to guess the most common category for every scenario. Letβs start with evaluation. The first step in approaching this problem is probably going to be to get our data into simple one-dimensional arrays that can be put into some functions. I like to do this with symbols and DataFrame calls because it seems effective to me:
X = :KmsY = :Fuel
Next, we will split the data into both a train and a test set. This is so we have both data to load the model with and data to get a solid evaluation out of. In order to do this we will use the TrainTestSplit() function from Lathe.jl:
using Lathe.preprocess: TrainTestSplittrain, test = TrainTestSplit(mldf)
Now we have two DataFrames, train and test, which we can extract our one dimensional arrays from.
trainX = train[!, X]trainy = train[!, Y]testX = test[!, X]testy = test[!, Y]
Next, weβre going to get our majority class baseline:
using Lathe.models: majClassBaseline
Since this is Julia, we can always check input by using the ?() method:
As seen in the documentation, the function takes one parameter, y, and will return a Lathe model object. This object will then have the function predict(), which we can use to return a prediction. Letβs create that object by providing our trainy, and then predicting with our testX:
evaluation = majClassBaseline(trainy)yhat = evaluation.predict(testX)
As you can see, the most common fuel type among these cars is clearly Petrol. Letβs evaluate this basic prediction using the catacc function from Lathe.lstats:
using Lathe.lstats: catacccatacc(yhat, testy)
81 percent is quite a high accuracy level for this test, and commonly problems like this might not even require a model to be solved, but merely an assumption. That being said, we came here to fit a Random Forest Classifier, and that is what we are going to do! Another cool thing we can look at is the counts in our new baseline model, which might give us some insights into why that accuracy is so high:
evaluation.counts()
Before we go on with preprocessing, it might be wise to do a basic evaluation of our minimum viable product model. Letβs put together a classifier and we may continue onto tuning it afterwards.
The model we are going to we working with today is the RandomForestClassifier object from Lathe.models:
using Lathe.models: RandomForestClassifier
Like before, we can use the ?() method in order to view the in-code documentation on this particular object:
As seen in the documentation, the model takes both key-word arguments and positional parameters as input. Our first model is going to simply provide the X and Y as parameters.
model = RandomForestClassifier(trainX, trainy)
Now we can go ahead and evaluate it in the same way as we did with the majority class baseline:
yhat = model.predict(testX)
And evaluate it using catacc:
Oh dear!
As I expressed prior, this certainly isnβt an optimal application for this model, but there are some simple and interesting things we could attempt to boost this accuracy. First, given the low number of categories, we could be over-fitting with our max_depth at 6. To test this theory, I would first give it a bump up, then down. If the suspected theory is correct, then it is likely that bumping it up is going to result in a serious drop in accuracy:
model = RandomForestClassifier(trainX, trainy, n_trees = 100, max_depth = 11)yhat = model.predict(testX)
Just as well, bringing the parameter low results in the dramatic opposite:
model = RandomForestClassifier(trainX, trainy, n_trees = 100, max_depth = 2)yhat = model.predict(testX)
While a basic reaction might be to turn the depth down and work with the model in that way, I imagine that the model might do better if there is a more balanced solution on depth with more trees instead:
model = RandomForestClassifier(trainX, trainy, n_trees = 1000, max_depth = 5)yhat = model.predict(testX)
Well great! A little bit of tuning, and our model, we have raised the accuracy dramatically! For one last trick, we can try scaling our feature. In order to do so, we are going to use the StandardScalar from Lathe.preprocess:
scaler = StandardScaler(trainX)trainX = scaler.predict(trainX)
Next, we will run the same on our testX:
testX = scaler.predict(testX)
This is going to return an array of complex numbers. In order to fix their imaginary bounds, we can change the data back to real numbers buy using the real() method. Of course, this needs to be casted onto the entire array, so we can do that by changing the requirements of the data types inside the array to be real:
trainX = Array{Real}(trainX)testX = Array{Real}(testX)
Now pass that through the same code as before, and we can see if that registers a further accuracy boost:
model = RandomForestClassifier(trainX, trainy, n_trees = 1500, max_depth = 5)yhat = model.predict(testX)catacc(yhat, testy)
So we lost accuracy?
Allow me to explain. Whenever we normalized the data using the standard scalar, we created less depth to the problem by counting our observations as standard deviations (from the mean) rather than arbitrary numbers that apply to whatever domain the data is extracted from. That being said, our accuracy gain might be felt with a quick tuning of the depth:
model = RandomForestClassifier(trainX, trainy, n_trees = 1500, max_depth = 3)yhat = model.predict(testX)
After some hyper-parameter optimization, these are the results recorded:
model = RandomForestClassifier(trainX, trainy, n_trees = 10, max_depth = 2, min_node_records = 4)yhat = model.predict(testX)catacc(yhat, testy)
Categorical problems have been somewhat of a chore in the Julia ecosystem for a while now. Fortunately, thanks to the further development of many Julia packages, there are ways to get quite accurate categorical predictions quite effectively in Julia. While this feature might be lacking, and there certainly are some issues that need to be addressed, this early preview into Lathe 0.2.0βs future is exciting for the future of machine-learning in Julia, especially when it comes to types. Another related article you could be interested in is this one, where I test the speed of this new classifier against similar solutions in the industry!
https://medium.com/@emmettgb/performance-testing-python-and-sklearn-with-julia-and-lathe-f5516fa497d7
Thank you for reading, and happy learning! | [
{
"code": null,
"e": 697,
"s": 172,
"text": "Within the past few years of very rapid development in data science technology, we have seen the dramatic escalation and adoption of a multitude of open-source tools. Among these are well-known tools like SkLearn and Tensorflow. With the recent early adoption of Julia, however, there are oppurtunities to dramatically improve our strategic approaches to solving machine-learning problems. The problem that effects the Julia language most is easily the lack of mature packages for various science or data related operations."
},
{
"code": null,
"e": 706,
"s": 697,
"text": "notebook"
},
{
"code": null,
"e": 1096,
"s": 706,
"text": "While this has been a long road that is certainly still being traveled, I think it is work taking a look at what Julia has to offer in its current state that hadnβt been there before. One recent addition I have been excited about is the addition of a Random Forest Classifier to Lathe. Using Lathe, DataFrames, and CSV, we can now easily explore, encode, and predict with various features!"
},
{
"code": null,
"e": 1855,
"s": 1096,
"text": "Of course, in order to work with a machine-learning model, we are first going to need to take a look at getting some categorical data to train it with. For this example, I am going to be using some UCLA Data that has been published on European Cars. Since the data is in comma separated value (CSV) format, we are going to use the CSV.jl package. One fantastic attribute of Juliaβs ecosystem is the level of segmentation β though it can be a burden. CSV.jl is a package exclusively developed to read CSV.jl and return a data frame just as JSON.jl is a package exclusively developed to read JSON formatted data. While we are at it, we are going to want to also import DataFrames.jl, which will allow us to actually visualize our data in a tabular spreadsheet."
},
{
"code": null,
"e": 1881,
"s": 1855,
"text": "using DataFramesusing CSV"
},
{
"code": null,
"e": 1914,
"s": 1881,
"text": "Now I will read in our CSV file:"
},
{
"code": null,
"e": 1944,
"s": 1914,
"text": "df = CSV.read(\"car data.csv\")"
},
{
"code": null,
"e": 2070,
"s": 1944,
"text": "In the very near future, this method of reading .CSV files will be deprecated, so it is probably best to use a sink argument:"
},
{
"code": null,
"e": 2129,
"s": 2070,
"text": "using DataFrames; df = CSV.read(\"car data.csv\", DataFrame)"
},
{
"code": null,
"e": 2325,
"s": 2129,
"text": "The easiest way to get a great view of our DataFrame is to use the show() method. In order to visualize our features better, we can use the allcols key-word argument, which will take a Bool type:"
},
{
"code": null,
"e": 2350,
"s": 2325,
"text": "show(df, allcols = true)"
},
{
"code": null,
"e": 2562,
"s": 2350,
"text": "Given that the purpose here is demonstration, not much thought is going be given towards the features other than what will work for this application. In order to see unique categories, we can use the Set() type:"
},
{
"code": null,
"e": 2588,
"s": 2562,
"text": "Set(df[!, :Transmission])"
},
{
"code": null,
"e": 3100,
"s": 2588,
"text": "Given that Gini-Index based models like this classifier that work off of impurity often do better with higher categorical counts, I selected the fuel type to be my target. As for the feature in this application, it was quite a difficult decision to make. I decided to go with a continuous target, since it would be quite hard to predict off of one set of 0's and 1βs and the dispatch for DataFrame data still has yet to be implemented in Lathe (meaning we can only support one feature in this unstable version.)"
},
{
"code": null,
"e": 3228,
"s": 3100,
"text": "The first thing I decided to do was extract these two features I wanted to work with into a new and smaller DataFrame, like so:"
},
{
"code": null,
"e": 3301,
"s": 3228,
"text": "mldf = DataFrame(:Fuel => df[!, :Fuel_Type], :Kms => df[!, :Kms_Driven])"
},
{
"code": null,
"e": 3461,
"s": 3301,
"text": "If you would like to learn more about the DataFrames.jl package, I have a recent and effective article that might do some work to help you in getting started!:"
},
{
"code": null,
"e": 4112,
"s": 3461,
"text": "An important step of working with any model is preprocessing, and evaluation. This is where you might want to question whether or not a model could actually help to solve this problem. This can be done with a majority class baseline. A majority class baseline is a simple measurement of how effective of an approach it might be to guess the most common category for every scenario. Letβs start with evaluation. The first step in approaching this problem is probably going to be to get our data into simple one-dimensional arrays that can be put into some functions. I like to do this with symbols and DataFrame calls because it seems effective to me:"
},
{
"code": null,
"e": 4130,
"s": 4112,
"text": "X = :KmsY = :Fuel"
},
{
"code": null,
"e": 4365,
"s": 4130,
"text": "Next, we will split the data into both a train and a test set. This is so we have both data to load the model with and data to get a solid evaluation out of. In order to do this we will use the TrainTestSplit() function from Lathe.jl:"
},
{
"code": null,
"e": 4438,
"s": 4365,
"text": "using Lathe.preprocess: TrainTestSplittrain, test = TrainTestSplit(mldf)"
},
{
"code": null,
"e": 4536,
"s": 4438,
"text": "Now we have two DataFrames, train and test, which we can extract our one dimensional arrays from."
},
{
"code": null,
"e": 4613,
"s": 4536,
"text": "trainX = train[!, X]trainy = train[!, Y]testX = test[!, X]testy = test[!, Y]"
},
{
"code": null,
"e": 4667,
"s": 4613,
"text": "Next, weβre going to get our majority class baseline:"
},
{
"code": null,
"e": 4704,
"s": 4667,
"text": "using Lathe.models: majClassBaseline"
},
{
"code": null,
"e": 4776,
"s": 4704,
"text": "Since this is Julia, we can always check input by using the ?() method:"
},
{
"code": null,
"e": 5059,
"s": 4776,
"text": "As seen in the documentation, the function takes one parameter, y, and will return a Lathe model object. This object will then have the function predict(), which we can use to return a prediction. Letβs create that object by providing our trainy, and then predicting with our testX:"
},
{
"code": null,
"e": 5129,
"s": 5059,
"text": "evaluation = majClassBaseline(trainy)yhat = evaluation.predict(testX)"
},
{
"code": null,
"e": 5289,
"s": 5129,
"text": "As you can see, the most common fuel type among these cars is clearly Petrol. Letβs evaluate this basic prediction using the catacc function from Lathe.lstats:"
},
{
"code": null,
"e": 5335,
"s": 5289,
"text": "using Lathe.lstats: catacccatacc(yhat, testy)"
},
{
"code": null,
"e": 5741,
"s": 5335,
"text": "81 percent is quite a high accuracy level for this test, and commonly problems like this might not even require a model to be solved, but merely an assumption. That being said, we came here to fit a Random Forest Classifier, and that is what we are going to do! Another cool thing we can look at is the counts in our new baseline model, which might give us some insights into why that accuracy is so high:"
},
{
"code": null,
"e": 5761,
"s": 5741,
"text": "evaluation.counts()"
},
{
"code": null,
"e": 5955,
"s": 5761,
"text": "Before we go on with preprocessing, it might be wise to do a basic evaluation of our minimum viable product model. Letβs put together a classifier and we may continue onto tuning it afterwards."
},
{
"code": null,
"e": 6059,
"s": 5955,
"text": "The model we are going to we working with today is the RandomForestClassifier object from Lathe.models:"
},
{
"code": null,
"e": 6102,
"s": 6059,
"text": "using Lathe.models: RandomForestClassifier"
},
{
"code": null,
"e": 6211,
"s": 6102,
"text": "Like before, we can use the ?() method in order to view the in-code documentation on this particular object:"
},
{
"code": null,
"e": 6387,
"s": 6211,
"text": "As seen in the documentation, the model takes both key-word arguments and positional parameters as input. Our first model is going to simply provide the X and Y as parameters."
},
{
"code": null,
"e": 6434,
"s": 6387,
"text": "model = RandomForestClassifier(trainX, trainy)"
},
{
"code": null,
"e": 6530,
"s": 6434,
"text": "Now we can go ahead and evaluate it in the same way as we did with the majority class baseline:"
},
{
"code": null,
"e": 6558,
"s": 6530,
"text": "yhat = model.predict(testX)"
},
{
"code": null,
"e": 6588,
"s": 6558,
"text": "And evaluate it using catacc:"
},
{
"code": null,
"e": 6597,
"s": 6588,
"text": "Oh dear!"
},
{
"code": null,
"e": 7050,
"s": 6597,
"text": "As I expressed prior, this certainly isnβt an optimal application for this model, but there are some simple and interesting things we could attempt to boost this accuracy. First, given the low number of categories, we could be over-fitting with our max_depth at 6. To test this theory, I would first give it a bump up, then down. If the suspected theory is correct, then it is likely that bumping it up is going to result in a serious drop in accuracy:"
},
{
"code": null,
"e": 7155,
"s": 7050,
"text": "model = RandomForestClassifier(trainX, trainy, n_trees = 100, max_depth = 11)yhat = model.predict(testX)"
},
{
"code": null,
"e": 7230,
"s": 7155,
"text": "Just as well, bringing the parameter low results in the dramatic opposite:"
},
{
"code": null,
"e": 7334,
"s": 7230,
"text": "model = RandomForestClassifier(trainX, trainy, n_trees = 100, max_depth = 2)yhat = model.predict(testX)"
},
{
"code": null,
"e": 7538,
"s": 7334,
"text": "While a basic reaction might be to turn the depth down and work with the model in that way, I imagine that the model might do better if there is a more balanced solution on depth with more trees instead:"
},
{
"code": null,
"e": 7643,
"s": 7538,
"text": "model = RandomForestClassifier(trainX, trainy, n_trees = 1000, max_depth = 5)yhat = model.predict(testX)"
},
{
"code": null,
"e": 7869,
"s": 7643,
"text": "Well great! A little bit of tuning, and our model, we have raised the accuracy dramatically! For one last trick, we can try scaling our feature. In order to do so, we are going to use the StandardScalar from Lathe.preprocess:"
},
{
"code": null,
"e": 7932,
"s": 7869,
"text": "scaler = StandardScaler(trainX)trainX = scaler.predict(trainX)"
},
{
"code": null,
"e": 7973,
"s": 7932,
"text": "Next, we will run the same on our testX:"
},
{
"code": null,
"e": 8003,
"s": 7973,
"text": "testX = scaler.predict(testX)"
},
{
"code": null,
"e": 8321,
"s": 8003,
"text": "This is going to return an array of complex numbers. In order to fix their imaginary bounds, we can change the data back to real numbers buy using the real() method. Of course, this needs to be casted onto the entire array, so we can do that by changing the requirements of the data types inside the array to be real:"
},
{
"code": null,
"e": 8376,
"s": 8321,
"text": "trainX = Array{Real}(trainX)testX = Array{Real}(testX)"
},
{
"code": null,
"e": 8482,
"s": 8376,
"text": "Now pass that through the same code as before, and we can see if that registers a further accuracy boost:"
},
{
"code": null,
"e": 8606,
"s": 8482,
"text": "model = RandomForestClassifier(trainX, trainy, n_trees = 1500, max_depth = 5)yhat = model.predict(testX)catacc(yhat, testy)"
},
{
"code": null,
"e": 8627,
"s": 8606,
"text": "So we lost accuracy?"
},
{
"code": null,
"e": 8983,
"s": 8627,
"text": "Allow me to explain. Whenever we normalized the data using the standard scalar, we created less depth to the problem by counting our observations as standard deviations (from the mean) rather than arbitrary numbers that apply to whatever domain the data is extracted from. That being said, our accuracy gain might be felt with a quick tuning of the depth:"
},
{
"code": null,
"e": 9088,
"s": 8983,
"text": "model = RandomForestClassifier(trainX, trainy, n_trees = 1500, max_depth = 3)yhat = model.predict(testX)"
},
{
"code": null,
"e": 9161,
"s": 9088,
"text": "After some hyper-parameter optimization, these are the results recorded:"
},
{
"code": null,
"e": 9305,
"s": 9161,
"text": "model = RandomForestClassifier(trainX, trainy, n_trees = 10, max_depth = 2, min_node_records = 4)yhat = model.predict(testX)catacc(yhat, testy)"
},
{
"code": null,
"e": 9946,
"s": 9305,
"text": "Categorical problems have been somewhat of a chore in the Julia ecosystem for a while now. Fortunately, thanks to the further development of many Julia packages, there are ways to get quite accurate categorical predictions quite effectively in Julia. While this feature might be lacking, and there certainly are some issues that need to be addressed, this early preview into Lathe 0.2.0βs future is exciting for the future of machine-learning in Julia, especially when it comes to types. Another related article you could be interested in is this one, where I test the speed of this new classifier against similar solutions in the industry!"
},
{
"code": null,
"e": 10048,
"s": 9946,
"text": "https://medium.com/@emmettgb/performance-testing-python-and-sklearn-with-julia-and-lathe-f5516fa497d7"
}
]
|
Fine-Tuning Pre-trained Model VGG-16 | by Muriel Kosaka | Towards Data Science | In my previous article, I explored using the pre-trained model VGG-16 as a feature extractor for transfer learning on the RAVDESS Audio Dataset. As a newcomer to Data Science, I read through articles here on Medium and came across this handy article by Pedro Marcelino in which he describes the process of transfer learning, but most insightful was the three strategies in which one can fine-tune their selected pre-trained model. Pedro Marcelino also provides a helpful Size Similarity Matrix to help determine which strategy to use. After reading his article, Iβve come to realize that rather than using pre-trained models as feature extractors, I should be fine-tuning the model by training some layers and leaving other layers frozen as my dataset is small (1,440 files) and not similar to the VGG-16 model dataset. Here I will explore this type of fine-tuning of the VGG-16 pre-trained model on the RAVDESS Audio Dataset and determine its effect on model accuracy.
After importing the necessary libraries, our train/test set, and preprocessing the data (described here), we dive into modeling:
First, import VGG16 and pass the necessary arguments:
First, import VGG16 and pass the necessary arguments:
from keras.applications import VGG16vgg_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
2. Next, we set some layers frozen, I decided to unfreeze the last block so that their weights get updated in each epoch
# Freeze four convolution blocksfor layer in vgg_model.layers[:15]: layer.trainable = False# Make sure you have frozen the correct layersfor i, layer in enumerate(vgg_model.layers): print(i, layer.name, layer.trainable)
Perfect, so we will be training our dataset on the last four layers of the pre-trained VGG-16 model.
3) I used the same model architecture from my previous VGG-16 model as a feature extractor:
x = vgg_model.outputx = Flatten()(x) # Flatten dimensions to for use in FC layersx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x) # Dropout layer to reduce overfittingx = Dense(256, activation='relu')(x)x = Dense(8, activation='softmax')(x) # Softmax for multiclasstransfer_model = Model(inputs=vgg_model.input, outputs=x)
4) Letβs set some callbacks, such as ReduceLROnPlateau and ModelCheckpoint. ReduceLROnPlateau is helpful especially in fine-tuning our model because as described by Pedro Marcelino, high learning rates increase the risk of losing previous knowledge so it is best to set a low learning rate, and with ReduceLROnPlateau, this can help us out with that! ModelCheckpoint is always helpful since it allows us to define where to checkpoint our model weights.
from keras.callbacks import ReduceLROnPlateaulr_reduce = ReduceLROnPlateau(monitor='val_accuracy', factor=0.6, patience=8, verbose=1, mode='max', min_lr=5e-5)checkpoint = ModelCheckpoint('vgg16_finetune.h15', monitor= 'val_accuracy', mode= 'max', save_best_only = True, verbose= 1)
4) Next, we compile and fit our model
from tensorflow.keras import layers, models, Model, optimizerslearning_rate= 5e-5transfer_model.compile(loss="categorical_crossentropy", optimizer=optimizers.Adam(lr=learning_rate), metrics=["accuracy"])history = transfer_model.fit(X_train, y_train, batch_size = 1, epochs=50, validation_data=(X_test,y_test), callbacks=[lr_reduce,checkpoint])
As we can see the model is largely overfitting to the training data. After 50 epochs, our model achieved an accuracy of 78% which is 9% higher than our previous classifier, where we used the pre-trained VGG-16 model used as a feature extractor, but performed the same as our pre-trained VGG-16 model used as a feature extractor with image augmentation.
Now let's try fine-tuning VGG-16 model with image augmentation to see if that will improve model accuracy. Using the same VGG-16 model object stored in the transfer_model variable from our previous model and unfreeze the fifth convolution block while keeping the first four blocks frozen.
for layer in vgg_model.layers[:15]:layer.trainable = Falsex = vgg_model.outputx = Flatten()(x) # Flatten dimensions to for use in FC layersx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x) # Dropout layer to reduce overfittingx = Dense(256, activation='relu')(x)x = Dense(8, activation='softmax')(x) # Softmax for multiclasstransfer_model = Model(inputs=vgg_model.input, outputs=x)for i, layer in enumerate(transfer_model.layers):print(i, layer.name, layer.trainable)
Great, so the fifth convolution block is now trainable and weβve added our own classifier. Now, we will augment our images using ImageDataGenerator of Kerasβ image preprocessing module, fit it to our training set, compile the model, then fit the model.
#Augment imagestrain_datagen = ImageDataGenerator(zoom_range=0.2, rotation_range=30, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2)#Fit augmentation to training imagestrain_generator = train_datagen.flow(X_train,y_train,batch_size=1)#Compile modeltransfer_model.compile(loss="categorical_crossentropy", optimizer='adam', metrics=["accuracy"])#Fit modelhistory = transfer_model.fit_generator(train_generator, validation_data=(X_test,y_test), epochs=100, shuffle=True, callbacks=[lr_reduce],verbose=1)
After 100 epochs, we achieved an accuracy score of 70%, that is an 8% decrease from our previous model and performed the same as our VGG-16 model as a feature extractor (*insert huge sad face here*).
As can be clearly seen, the model is overfitting to the training data and accuracy seems to plateau after about 40 epochs. With fine-tuning, I did not see much improvement in model accuracy over using the pre-trained model as a feature extractor which I did not expect as per the dissimilarity and smaller dataset I am using compared to the VGG-16 model.
I have tried to adjust the parameters of the ImageDataGenerator class and was unsuccessful in improving model accuracy. If anyone has any suggestions as to how/if my VGG-19 model fine-tuned with image augmentation can improve, please let me know! Thank you for reading :) | [
{
"code": null,
"e": 1141,
"s": 171,
"text": "In my previous article, I explored using the pre-trained model VGG-16 as a feature extractor for transfer learning on the RAVDESS Audio Dataset. As a newcomer to Data Science, I read through articles here on Medium and came across this handy article by Pedro Marcelino in which he describes the process of transfer learning, but most insightful was the three strategies in which one can fine-tune their selected pre-trained model. Pedro Marcelino also provides a helpful Size Similarity Matrix to help determine which strategy to use. After reading his article, Iβve come to realize that rather than using pre-trained models as feature extractors, I should be fine-tuning the model by training some layers and leaving other layers frozen as my dataset is small (1,440 files) and not similar to the VGG-16 model dataset. Here I will explore this type of fine-tuning of the VGG-16 pre-trained model on the RAVDESS Audio Dataset and determine its effect on model accuracy."
},
{
"code": null,
"e": 1270,
"s": 1141,
"text": "After importing the necessary libraries, our train/test set, and preprocessing the data (described here), we dive into modeling:"
},
{
"code": null,
"e": 1324,
"s": 1270,
"text": "First, import VGG16 and pass the necessary arguments:"
},
{
"code": null,
"e": 1378,
"s": 1324,
"text": "First, import VGG16 and pass the necessary arguments:"
},
{
"code": null,
"e": 1498,
"s": 1378,
"text": "from keras.applications import VGG16vgg_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))"
},
{
"code": null,
"e": 1619,
"s": 1498,
"text": "2. Next, we set some layers frozen, I decided to unfreeze the last block so that their weights get updated in each epoch"
},
{
"code": null,
"e": 1845,
"s": 1619,
"text": "# Freeze four convolution blocksfor layer in vgg_model.layers[:15]: layer.trainable = False# Make sure you have frozen the correct layersfor i, layer in enumerate(vgg_model.layers): print(i, layer.name, layer.trainable)"
},
{
"code": null,
"e": 1946,
"s": 1845,
"text": "Perfect, so we will be training our dataset on the last four layers of the pre-trained VGG-16 model."
},
{
"code": null,
"e": 2038,
"s": 1946,
"text": "3) I used the same model architecture from my previous VGG-16 model as a feature extractor:"
},
{
"code": null,
"e": 2368,
"s": 2038,
"text": "x = vgg_model.outputx = Flatten()(x) # Flatten dimensions to for use in FC layersx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x) # Dropout layer to reduce overfittingx = Dense(256, activation='relu')(x)x = Dense(8, activation='softmax')(x) # Softmax for multiclasstransfer_model = Model(inputs=vgg_model.input, outputs=x)"
},
{
"code": null,
"e": 2821,
"s": 2368,
"text": "4) Letβs set some callbacks, such as ReduceLROnPlateau and ModelCheckpoint. ReduceLROnPlateau is helpful especially in fine-tuning our model because as described by Pedro Marcelino, high learning rates increase the risk of losing previous knowledge so it is best to set a low learning rate, and with ReduceLROnPlateau, this can help us out with that! ModelCheckpoint is always helpful since it allows us to define where to checkpoint our model weights."
},
{
"code": null,
"e": 3103,
"s": 2821,
"text": "from keras.callbacks import ReduceLROnPlateaulr_reduce = ReduceLROnPlateau(monitor='val_accuracy', factor=0.6, patience=8, verbose=1, mode='max', min_lr=5e-5)checkpoint = ModelCheckpoint('vgg16_finetune.h15', monitor= 'val_accuracy', mode= 'max', save_best_only = True, verbose= 1)"
},
{
"code": null,
"e": 3141,
"s": 3103,
"text": "4) Next, we compile and fit our model"
},
{
"code": null,
"e": 3485,
"s": 3141,
"text": "from tensorflow.keras import layers, models, Model, optimizerslearning_rate= 5e-5transfer_model.compile(loss=\"categorical_crossentropy\", optimizer=optimizers.Adam(lr=learning_rate), metrics=[\"accuracy\"])history = transfer_model.fit(X_train, y_train, batch_size = 1, epochs=50, validation_data=(X_test,y_test), callbacks=[lr_reduce,checkpoint])"
},
{
"code": null,
"e": 3838,
"s": 3485,
"text": "As we can see the model is largely overfitting to the training data. After 50 epochs, our model achieved an accuracy of 78% which is 9% higher than our previous classifier, where we used the pre-trained VGG-16 model used as a feature extractor, but performed the same as our pre-trained VGG-16 model used as a feature extractor with image augmentation."
},
{
"code": null,
"e": 4127,
"s": 3838,
"text": "Now let's try fine-tuning VGG-16 model with image augmentation to see if that will improve model accuracy. Using the same VGG-16 model object stored in the transfer_model variable from our previous model and unfreeze the fifth convolution block while keeping the first four blocks frozen."
},
{
"code": null,
"e": 4601,
"s": 4127,
"text": "for layer in vgg_model.layers[:15]:layer.trainable = Falsex = vgg_model.outputx = Flatten()(x) # Flatten dimensions to for use in FC layersx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x) # Dropout layer to reduce overfittingx = Dense(256, activation='relu')(x)x = Dense(8, activation='softmax')(x) # Softmax for multiclasstransfer_model = Model(inputs=vgg_model.input, outputs=x)for i, layer in enumerate(transfer_model.layers):print(i, layer.name, layer.trainable)"
},
{
"code": null,
"e": 4854,
"s": 4601,
"text": "Great, so the fifth convolution block is now trainable and weβve added our own classifier. Now, we will augment our images using ImageDataGenerator of Kerasβ image preprocessing module, fit it to our training set, compile the model, then fit the model."
},
{
"code": null,
"e": 5371,
"s": 4854,
"text": "#Augment imagestrain_datagen = ImageDataGenerator(zoom_range=0.2, rotation_range=30, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2)#Fit augmentation to training imagestrain_generator = train_datagen.flow(X_train,y_train,batch_size=1)#Compile modeltransfer_model.compile(loss=\"categorical_crossentropy\", optimizer='adam', metrics=[\"accuracy\"])#Fit modelhistory = transfer_model.fit_generator(train_generator, validation_data=(X_test,y_test), epochs=100, shuffle=True, callbacks=[lr_reduce],verbose=1)"
},
{
"code": null,
"e": 5571,
"s": 5371,
"text": "After 100 epochs, we achieved an accuracy score of 70%, that is an 8% decrease from our previous model and performed the same as our VGG-16 model as a feature extractor (*insert huge sad face here*)."
},
{
"code": null,
"e": 5926,
"s": 5571,
"text": "As can be clearly seen, the model is overfitting to the training data and accuracy seems to plateau after about 40 epochs. With fine-tuning, I did not see much improvement in model accuracy over using the pre-trained model as a feature extractor which I did not expect as per the dissimilarity and smaller dataset I am using compared to the VGG-16 model."
}
]
|
Python | Ways to change keys in dictionary - GeeksforGeeks | 28 Feb, 2019
Given a dictionary, the task is to change the key based on the requirement. Letβs see different methods we can do this task.
Method #1 : Using naive method
# Python code to demonstrate# changing keys of dictionary# using naive method # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # printing initial jsonprint ("initial 1st dictionary", ini_dict) # changing keys of dictionaryini_dict['akash'] = ini_dict['akshat']del ini_dict['akshat'] # printing final resultprint ("final dictionary", str(ini_dict))
initial 1st dictionary {βakshatβ: 15, βnikhilβ: 1, βmanjeetβ: 10, βvashuβ: 5}final dictionary {βakashβ: 15, βnikhilβ: 1, βmanjeetβ: 10, βvashuβ: 5}
Method #2: Using pop()
# Python code to demonstrate# changing keys of dictionary# using pop() method # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # printing initial jsonprint ("initial 1st dictionary", ini_dict) # changing keys of dictionaryini_dict['akash'] = ini_dict.pop('akshat') # printing final resultprint ("final dictionary", str(ini_dict))
initial 1st dictionary {βakshatβ: 15, βmanjeetβ: 10, βvashuβ: 5, βnikhilβ: 1}final dictionary {βakashβ: 15, βmanjeetβ: 10, βvashuβ: 5, βnikhilβ: 1}
Method #3: Using zip()
Suppose we want to change all keys of dictionary.
# Python code to demonstrate# changing all keys of dictionary# corresponding to list using zip() # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # initialising listini_list = ['a', 'b', 'c', 'd'] # printing initial jsonprint ("initial 1st dictionary", ini_dict) # changing keys of dictionaryfinal_dict = dict(zip(ini_list, list(ini_dict.values()))) # printing final resultprint ("final dictionary", str(final_dict))
initial 1st dictionary {βakshatβ: 15, βmanjeetβ: 10, βvashuβ: 5, βnikhilβ: 1}final dictionary {βcβ: 5, βdβ: 1, βaβ: 15, βbβ: 10}
Marketing
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.
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
Python program to convert a list to string
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": 23752,
"s": 23724,
"text": "\n28 Feb, 2019"
},
{
"code": null,
"e": 23877,
"s": 23752,
"text": "Given a dictionary, the task is to change the key based on the requirement. Letβs see different methods we can do this task."
},
{
"code": null,
"e": 23908,
"s": 23877,
"text": "Method #1 : Using naive method"
},
{
"code": "# Python code to demonstrate# changing keys of dictionary# using naive method # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # printing initial jsonprint (\"initial 1st dictionary\", ini_dict) # changing keys of dictionaryini_dict['akash'] = ini_dict['akshat']del ini_dict['akshat'] # printing final resultprint (\"final dictionary\", str(ini_dict))",
"e": 24320,
"s": 23908,
"text": null
},
{
"code": null,
"e": 24468,
"s": 24320,
"text": "initial 1st dictionary {βakshatβ: 15, βnikhilβ: 1, βmanjeetβ: 10, βvashuβ: 5}final dictionary {βakashβ: 15, βnikhilβ: 1, βmanjeetβ: 10, βvashuβ: 5}"
},
{
"code": null,
"e": 24492,
"s": 24468,
"text": " Method #2: Using pop()"
},
{
"code": "# Python code to demonstrate# changing keys of dictionary# using pop() method # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # printing initial jsonprint (\"initial 1st dictionary\", ini_dict) # changing keys of dictionaryini_dict['akash'] = ini_dict.pop('akshat') # printing final resultprint (\"final dictionary\", str(ini_dict))",
"e": 24885,
"s": 24492,
"text": null
},
{
"code": null,
"e": 25033,
"s": 24885,
"text": "initial 1st dictionary {βakshatβ: 15, βmanjeetβ: 10, βvashuβ: 5, βnikhilβ: 1}final dictionary {βakashβ: 15, βmanjeetβ: 10, βvashuβ: 5, βnikhilβ: 1}"
},
{
"code": null,
"e": 25057,
"s": 25033,
"text": " Method #3: Using zip()"
},
{
"code": null,
"e": 25107,
"s": 25057,
"text": "Suppose we want to change all keys of dictionary."
},
{
"code": "# Python code to demonstrate# changing all keys of dictionary# corresponding to list using zip() # inititialising dictionaryini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # initialising listini_list = ['a', 'b', 'c', 'd'] # printing initial jsonprint (\"initial 1st dictionary\", ini_dict) # changing keys of dictionaryfinal_dict = dict(zip(ini_list, list(ini_dict.values()))) # printing final resultprint (\"final dictionary\", str(final_dict))",
"e": 25588,
"s": 25107,
"text": null
},
{
"code": null,
"e": 25717,
"s": 25588,
"text": "initial 1st dictionary {βakshatβ: 15, βmanjeetβ: 10, βvashuβ: 5, βnikhilβ: 1}final dictionary {βcβ: 5, βdβ: 1, βaβ: 15, βbβ: 10}"
},
{
"code": null,
"e": 25727,
"s": 25717,
"text": "Marketing"
},
{
"code": null,
"e": 25754,
"s": 25727,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 25766,
"s": 25754,
"text": "python-dict"
},
{
"code": null,
"e": 25773,
"s": 25766,
"text": "Python"
},
{
"code": null,
"e": 25789,
"s": 25773,
"text": "Python Programs"
},
{
"code": null,
"e": 25801,
"s": 25789,
"text": "python-dict"
},
{
"code": null,
"e": 25899,
"s": 25801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25908,
"s": 25899,
"text": "Comments"
},
{
"code": null,
"e": 25921,
"s": 25908,
"text": "Old Comments"
},
{
"code": null,
"e": 25939,
"s": 25921,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25974,
"s": 25939,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25996,
"s": 25974,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26028,
"s": 25996,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26058,
"s": 26028,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26101,
"s": 26058,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26140,
"s": 26101,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26186,
"s": 26140,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26243,
"s": 26186,
"text": "Python program to check whether a number is Prime or not"
}
]
|
Difference between Class and Structure in C# - GeeksforGeeks | 18 May, 2020
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit.
Example:
// C# program to illustrate the// concept of classusing System; // Class Declarationpublic class Author { // Data members of class public string name; public string language; public int article_no; public int improv_no; // Method of class public void Details(string name, string language, int article_no, int improv_no) { this.name = name; this.language = language; this.article_no = article_no; this.improv_no = improv_no; Console.WriteLine("The name of the author is : " + name + "\nThe name of language is : " + language + "\nTotal number of article published " + article_no + "\nTotal number of Improvements:" +" done by author is : " + improv_no); } // Main Method public static void Main(String[] args) { // Creating object Author obj = new Author(); // Calling method of class // using class object obj.Details("Ankita", "C#", 80, 50); }}
The name of the author is : Ankita
The name of language is : C#
Total number of article published 80
Total number of Improvements: done by author is : 50
A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.
Example:
// C# program to illustrate the// concept of structureusing System; // Defining structurepublic struct Car{ // Declaring different data types public string Brand; public string Model; public string Color;} class GFG { // Main Method static void Main(string[] args) { // Declare c1 of type Car // no need to create an // instance using 'new' keyword Car c1; // c1's data c1.Brand = "Bugatti"; c1.Model = "Bugatti Veyron EB 16.4"; c1.Color = "Gray"; // Displaying the values Console.WriteLine("Name of brand: " + c1.Brand + "\nModel name: " + c1.Model + "\nColor of car: " + c1.Color); }}
Name of brand: Bugatti
Model name: Bugatti Veyron EB 16.4
Color of car: Gray
zeuss
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Destructors in C#
C# | Delegates
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers | [
{
"code": null,
"e": 24286,
"s": 24258,
"text": "\n18 May, 2020"
},
{
"code": null,
"e": 24477,
"s": 24286,
"text": "A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit."
},
{
"code": null,
"e": 24486,
"s": 24477,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// concept of classusing System; // Class Declarationpublic class Author { // Data members of class public string name; public string language; public int article_no; public int improv_no; // Method of class public void Details(string name, string language, int article_no, int improv_no) { this.name = name; this.language = language; this.article_no = article_no; this.improv_no = improv_no; Console.WriteLine(\"The name of the author is : \" + name + \"\\nThe name of language is : \" + language + \"\\nTotal number of article published \" + article_no + \"\\nTotal number of Improvements:\" +\" done by author is : \" + improv_no); } // Main Method public static void Main(String[] args) { // Creating object Author obj = new Author(); // Calling method of class // using class object obj.Details(\"Ankita\", \"C#\", 80, 50); }}",
"e": 25580,
"s": 24486,
"text": null
},
{
"code": null,
"e": 25737,
"s": 25580,
"text": "The name of the author is : Ankita\nThe name of language is : C#\nTotal number of article published 80\nTotal number of Improvements: done by author is : 50\n"
},
{
"code": null,
"e": 25943,
"s": 25737,
"text": "A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types."
},
{
"code": null,
"e": 25952,
"s": 25943,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// concept of structureusing System; // Defining structurepublic struct Car{ // Declaring different data types public string Brand; public string Model; public string Color;} class GFG { // Main Method static void Main(string[] args) { // Declare c1 of type Car // no need to create an // instance using 'new' keyword Car c1; // c1's data c1.Brand = \"Bugatti\"; c1.Model = \"Bugatti Veyron EB 16.4\"; c1.Color = \"Gray\"; // Displaying the values Console.WriteLine(\"Name of brand: \" + c1.Brand + \"\\nModel name: \" + c1.Model + \"\\nColor of car: \" + c1.Color); }}",
"e": 26698,
"s": 25952,
"text": null
},
{
"code": null,
"e": 26776,
"s": 26698,
"text": "Name of brand: Bugatti\nModel name: Bugatti Veyron EB 16.4\nColor of car: Gray\n"
},
{
"code": null,
"e": 26782,
"s": 26776,
"text": "zeuss"
},
{
"code": null,
"e": 26793,
"s": 26782,
"text": "CSharp-OOP"
},
{
"code": null,
"e": 26796,
"s": 26793,
"text": "C#"
},
{
"code": null,
"e": 26894,
"s": 26796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26922,
"s": 26894,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 26940,
"s": 26922,
"text": "Destructors in C#"
},
{
"code": null,
"e": 26955,
"s": 26940,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26978,
"s": 26955,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27018,
"s": 26978,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27049,
"s": 27018,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27071,
"s": 27049,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27087,
"s": 27071,
"text": "C# | Data Types"
},
{
"code": null,
"e": 27115,
"s": 27087,
"text": "HashSet in C# with Examples"
}
]
|
Matrix operations using operator overloading - GeeksforGeeks | 16 Aug, 2021
Pre-requisite: Operator OverloadingGiven two matrix mat1[][] and mat2[][] of NxN dimensions, the task is to perform Matrix Operations using Operator Overloading.Examples:
Input: arr1[][] = { {1, 2, 3}, {4, 5, 6}, {1, 2, 3}}, arr2[][] = { {1, 2, 3}, {4, 5, 16}, {1, 2, 3}} Output: Addition of two given Matrices is: 2 4 6 8 10 22 2 4 6 Subtraction of two given Matrices is: 0 0 0 0 0 -10 0 0 0 Multiplication of two given Matrices is: 12 18 44 30 45 110 12 18 44 Input: arr1[][] = { {11, 2, 3}, {4, 5, 0}, {1, 12, 3}}, arr2[][] = { {1, 2, 3}, {41, 5, 16}, {1, 22, 3}} Output: Addition of two given Matrices is : 12 4 6 45 10 16 2 34 6 Subtraction of two given Matrices is : 10 0 0 -37 0 -16 0 -10 0 Multiplication of two given Matrices is : 96 98 74 209 33 92 496 128 204
Approach: To overload +, β, * operators, we will create a class named matrix and then make a public function to overload the operators.
To overload operator β+β use prototype:
Return_Type classname :: operator +(Argument list)
{
// Function Body
}
For Example:
Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 + M2.
In the above statement M1 is treated hai global and M2[][] is passed as an argument to the function βvoid Matrix::operator+(Matrix x)β.
In the above overloaded function, the approach for addition of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments).
To overload operator β-β use prototype:
Return_Type classname :: operator -(Argument list)
{
// Function Body
}
For Example:
Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 β M2
In the above statement M1 is treated hai global and M2[][] is passed as an argument to the function βvoid Matrix::operator-(Matrix x)β.
In the above overloaded function, the approach for subtraction of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments).
To overload operator β*β use prototype:
Return_Type classname :: operator *(Argument list)
{
// Function Body
}
Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 * M2.
In the above statement M1 is treated hai global and M2[][] is passed as an argument to the function βvoid Matrix::operator*(Matrix x)β.
In the above overloaded function, the approach for multiplication of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments).
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include "bits/stdc++.h"#define rows 50#define cols 50using namespace std; int N; // Class for Matrix operator overloadingclass Matrix { // For input Matrix int arr[rows][cols]; public: // Function to take input to arr[][] void input(vector<vector<int> >& A); void display(); // Functions for operator overloading void operator+(Matrix x); void operator-(Matrix x); void operator*(Matrix x);}; // Functions to get input to Matrix// array arr[][]void Matrix::input(vector<vector<int> >& A){ // Traverse the vector A[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { arr[i][j] = A[i][j]; } }} // Function to display the element// of Matrixvoid Matrix::display(){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print the element cout << arr[i][j] << ' '; } cout << endl; }} // Function for addition of two Matrix// using operator overloadingvoid Matrix::operator+(Matrix x){ // To store the sum of Matrices int mat[N][N]; // Traverse the Matrix x for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Add the corresponding // blocks of Matrices mat[i][j] = arr[i][j] + x.arr[i][j]; } } // Display the sum of Matrices for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print the element cout << mat[i][j] << ' '; } cout << endl; }} // Function for subtraction of two Matrix// using operator overloadingvoid Matrix::operator-(Matrix x){ // To store the difference of Matrices int mat[N][N]; // Traverse the Matrix x for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Subtract the corresponding // blocks of Matrices mat[i][j] = arr[i][j] - x.arr[i][j]; } } // Display the difference of Matrices for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print the element cout << mat[i][j] << ' '; } cout << endl; }} // Function for multiplication of// two Matrix using operator// overloadingvoid Matrix::operator*(Matrix x){ // To store the multiplication // of Matrices int mat[N][N]; // Traverse the Matrix x for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Initialise current block // with value zero mat[i][j] = 0; for (int k = 0; k < N; k++) { mat[i][j] += arr[i][k] * (x.arr[k][j]); } } } // Display the multiplication // of Matrices for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print the element cout << mat[i][j] << ' '; } cout << endl; }} // Driver Codeint main(){ // Dimension of Matrix N = 3; vector<vector<int> > arr1 = { { 1, 2, 3 }, { 4, 5, 6 }, { 1, 2, 3 } }; vector<vector<int> > arr2 = { { 1, 2, 3 }, { 4, 5, 16 }, { 1, 2, 3 } }; // Declare Matrices Matrix mat1, mat2; // Take Input to matrix mat1 mat1.input(arr1); // Take Input to matrix mat2 mat2.input(arr2); // For addition of matrix cout << "Addition of two given" << " Matrices is : \n"; mat1 + mat2; // For subtraction of matrix cout << "Subtraction of two given" << " Matrices is : \n"; mat1 - mat2; // For multiplication of matrix cout << "Multiplication of two" << " given Matrices is : \n"; mat1* mat2; return 0;}
Addition of two given Matrices is :
2 4 6
8 10 22
2 4 6
Subtraction of two given Matrices is :
0 0 0
0 0 -10
0 0 0
Multiplication of two given Matrices is :
12 18 44
30 45 110
12 18 44
saurabh1990aror
anikakapoor
ruhelaa48
Operator Overloading
Matrix
Programming Language
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flood fill Algorithm - how to implement fill() in paint?
Multiplication of Matrix using threads
Python program to add two Matrices
Mathematics | L U Decomposition of a System of Linear Equations
Program to find the Sum of each Row and each Column of a Matrix
Modulo Operator (%) in C/C++ with Examples
Differences between Procedural and Object Oriented Programming
Arrow operator -> in C/C++ with Examples
Structures in C++
Top 10 Programming Languages to Learn in 2022 | [
{
"code": null,
"e": 24840,
"s": 24812,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 25013,
"s": 24840,
"text": "Pre-requisite: Operator OverloadingGiven two matrix mat1[][] and mat2[][] of NxN dimensions, the task is to perform Matrix Operations using Operator Overloading.Examples: "
},
{
"code": null,
"e": 25615,
"s": 25013,
"text": "Input: arr1[][] = { {1, 2, 3}, {4, 5, 6}, {1, 2, 3}}, arr2[][] = { {1, 2, 3}, {4, 5, 16}, {1, 2, 3}} Output: Addition of two given Matrices is: 2 4 6 8 10 22 2 4 6 Subtraction of two given Matrices is: 0 0 0 0 0 -10 0 0 0 Multiplication of two given Matrices is: 12 18 44 30 45 110 12 18 44 Input: arr1[][] = { {11, 2, 3}, {4, 5, 0}, {1, 12, 3}}, arr2[][] = { {1, 2, 3}, {41, 5, 16}, {1, 22, 3}} Output: Addition of two given Matrices is : 12 4 6 45 10 16 2 34 6 Subtraction of two given Matrices is : 10 0 0 -37 0 -16 0 -10 0 Multiplication of two given Matrices is : 96 98 74 209 33 92 496 128 204 "
},
{
"code": null,
"e": 25753,
"s": 25615,
"text": "Approach: To overload +, β, * operators, we will create a class named matrix and then make a public function to overload the operators. "
},
{
"code": null,
"e": 25795,
"s": 25753,
"text": "To overload operator β+β use prototype: "
},
{
"code": null,
"e": 25871,
"s": 25795,
"text": "Return_Type classname :: operator +(Argument list)\n{\n // Function Body\n}"
},
{
"code": null,
"e": 25885,
"s": 25871,
"text": "For Example: "
},
{
"code": null,
"e": 26020,
"s": 25885,
"text": "Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 + M2. "
},
{
"code": null,
"e": 26158,
"s": 26020,
"text": "In the above statement M1 is treated hai global and M2[][] is passed as an argument to the function βvoid Matrix::operator+(Matrix x)β. "
},
{
"code": null,
"e": 26339,
"s": 26158,
"text": "In the above overloaded function, the approach for addition of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments). "
},
{
"code": null,
"e": 26380,
"s": 26339,
"text": "To overload operator β-β use prototype: "
},
{
"code": null,
"e": 26456,
"s": 26380,
"text": "Return_Type classname :: operator -(Argument list)\n{\n // Function Body\n}"
},
{
"code": null,
"e": 26470,
"s": 26456,
"text": "For Example: "
},
{
"code": null,
"e": 26604,
"s": 26470,
"text": "Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 β M2 "
},
{
"code": null,
"e": 26742,
"s": 26604,
"text": "In the above statement M1 is treated hai global and M2[][] is passed as an argument to the function βvoid Matrix::operator-(Matrix x)β. "
},
{
"code": null,
"e": 26926,
"s": 26742,
"text": "In the above overloaded function, the approach for subtraction of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments). "
},
{
"code": null,
"e": 26967,
"s": 26926,
"text": "To overload operator β*β use prototype: "
},
{
"code": null,
"e": 27043,
"s": 26967,
"text": "Return_Type classname :: operator *(Argument list)\n{\n // Function Body\n}"
},
{
"code": null,
"e": 27178,
"s": 27043,
"text": "Let there are two matrix M1[][] and M2[][] of same dimensions. Using Operator Overloading M1[][] and M2[][] can be added as M1 * M2. "
},
{
"code": null,
"e": 27316,
"s": 27178,
"text": "In the above statement M1 is treated hai global and M2[][] is passed as an argument to the function βvoid Matrix::operator*(Matrix x)β. "
},
{
"code": null,
"e": 27503,
"s": 27316,
"text": "In the above overloaded function, the approach for multiplication of two matrix is implemented by treating M1[][] as first and M2[][] as second Matrix i.e., Matrix x(as the arguments). "
},
{
"code": null,
"e": 27555,
"s": 27503,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27559,
"s": 27555,
"text": "C++"
},
{
"code": "// C++ program for the above approach #include \"bits/stdc++.h\"#define rows 50#define cols 50using namespace std; int N; // Class for Matrix operator overloadingclass Matrix { // For input Matrix int arr[rows][cols]; public: // Function to take input to arr[][] void input(vector<vector<int> >& A); void display(); // Functions for operator overloading void operator+(Matrix x); void operator-(Matrix x); void operator*(Matrix x);}; // Functions to get input to Matrix// array arr[][]void Matrix::input(vector<vector<int> >& A){ // Traverse the vector A[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { arr[i][j] = A[i][j]; } }} // Function to display the element// of Matrixvoid Matrix::display(){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print the element cout << arr[i][j] << ' '; } cout << endl; }} // Function for addition of two Matrix// using operator overloadingvoid Matrix::operator+(Matrix x){ // To store the sum of Matrices int mat[N][N]; // Traverse the Matrix x for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Add the corresponding // blocks of Matrices mat[i][j] = arr[i][j] + x.arr[i][j]; } } // Display the sum of Matrices for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print the element cout << mat[i][j] << ' '; } cout << endl; }} // Function for subtraction of two Matrix// using operator overloadingvoid Matrix::operator-(Matrix x){ // To store the difference of Matrices int mat[N][N]; // Traverse the Matrix x for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Subtract the corresponding // blocks of Matrices mat[i][j] = arr[i][j] - x.arr[i][j]; } } // Display the difference of Matrices for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print the element cout << mat[i][j] << ' '; } cout << endl; }} // Function for multiplication of// two Matrix using operator// overloadingvoid Matrix::operator*(Matrix x){ // To store the multiplication // of Matrices int mat[N][N]; // Traverse the Matrix x for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Initialise current block // with value zero mat[i][j] = 0; for (int k = 0; k < N; k++) { mat[i][j] += arr[i][k] * (x.arr[k][j]); } } } // Display the multiplication // of Matrices for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Print the element cout << mat[i][j] << ' '; } cout << endl; }} // Driver Codeint main(){ // Dimension of Matrix N = 3; vector<vector<int> > arr1 = { { 1, 2, 3 }, { 4, 5, 6 }, { 1, 2, 3 } }; vector<vector<int> > arr2 = { { 1, 2, 3 }, { 4, 5, 16 }, { 1, 2, 3 } }; // Declare Matrices Matrix mat1, mat2; // Take Input to matrix mat1 mat1.input(arr1); // Take Input to matrix mat2 mat2.input(arr2); // For addition of matrix cout << \"Addition of two given\" << \" Matrices is : \\n\"; mat1 + mat2; // For subtraction of matrix cout << \"Subtraction of two given\" << \" Matrices is : \\n\"; mat1 - mat2; // For multiplication of matrix cout << \"Multiplication of two\" << \" given Matrices is : \\n\"; mat1* mat2; return 0;}",
"e": 31331,
"s": 27559,
"text": null
},
{
"code": null,
"e": 31528,
"s": 31331,
"text": "Addition of two given Matrices is : \n2 4 6 \n8 10 22 \n2 4 6 \nSubtraction of two given Matrices is : \n0 0 0 \n0 0 -10 \n0 0 0 \nMultiplication of two given Matrices is : \n12 18 44 \n30 45 110 \n12 18 44 "
},
{
"code": null,
"e": 31544,
"s": 31528,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 31556,
"s": 31544,
"text": "anikakapoor"
},
{
"code": null,
"e": 31566,
"s": 31556,
"text": "ruhelaa48"
},
{
"code": null,
"e": 31587,
"s": 31566,
"text": "Operator Overloading"
},
{
"code": null,
"e": 31594,
"s": 31587,
"text": "Matrix"
},
{
"code": null,
"e": 31615,
"s": 31594,
"text": "Programming Language"
},
{
"code": null,
"e": 31622,
"s": 31615,
"text": "Matrix"
},
{
"code": null,
"e": 31720,
"s": 31622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31729,
"s": 31720,
"text": "Comments"
},
{
"code": null,
"e": 31742,
"s": 31729,
"text": "Old Comments"
},
{
"code": null,
"e": 31799,
"s": 31742,
"text": "Flood fill Algorithm - how to implement fill() in paint?"
},
{
"code": null,
"e": 31838,
"s": 31799,
"text": "Multiplication of Matrix using threads"
},
{
"code": null,
"e": 31873,
"s": 31838,
"text": "Python program to add two Matrices"
},
{
"code": null,
"e": 31937,
"s": 31873,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
},
{
"code": null,
"e": 32001,
"s": 31937,
"text": "Program to find the Sum of each Row and each Column of a Matrix"
},
{
"code": null,
"e": 32044,
"s": 32001,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32107,
"s": 32044,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 32148,
"s": 32107,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 32166,
"s": 32148,
"text": "Structures in C++"
}
]
|
java.lang.reflect.Field.getType() Method Example | The java.lang.reflect.Field.getType() method returns a Class object that identifies the declared type for the field represented by this Field object.
Following is the declaration for java.lang.reflect.Field.getType() method.
public Class<?> getType()
a Class object identifying the declared type of the field represented by this object.
The following example shows the usage of java.lang.reflect.Field.getType() method.
package com.tutorialspoint;
import java.lang.reflect.Field;
public class FieldDemo {
public static void main(String[] args) throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Field field = SampleClass.class.getField("sampleField");
System.out.println(field.getType());
}
}
class SampleClass {
public static long sampleField = 5;
}
Let us compile and run the above program, this will produce the following result β
long
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1604,
"s": 1454,
"text": "The java.lang.reflect.Field.getType() method returns a Class object that identifies the declared type for the field represented by this Field object."
},
{
"code": null,
"e": 1679,
"s": 1604,
"text": "Following is the declaration for java.lang.reflect.Field.getType() method."
},
{
"code": null,
"e": 1706,
"s": 1679,
"text": "public Class<?> getType()\n"
},
{
"code": null,
"e": 1792,
"s": 1706,
"text": "a Class object identifying the declared type of the field represented by this object."
},
{
"code": null,
"e": 1875,
"s": 1792,
"text": "The following example shows the usage of java.lang.reflect.Field.getType() method."
},
{
"code": null,
"e": 2297,
"s": 1875,
"text": "package com.tutorialspoint;\n\nimport java.lang.reflect.Field;\n\npublic class FieldDemo {\n\n public static void main(String[] args) throws NoSuchFieldException, \n SecurityException, IllegalArgumentException, IllegalAccessException {\n \n Field field = SampleClass.class.getField(\"sampleField\");\n System.out.println(field.getType());\n }\n}\n\nclass SampleClass {\n public static long sampleField = 5;\n}"
},
{
"code": null,
"e": 2380,
"s": 2297,
"text": "Let us compile and run the above program, this will produce the following result β"
},
{
"code": null,
"e": 2386,
"s": 2380,
"text": "long\n"
},
{
"code": null,
"e": 2393,
"s": 2386,
"text": " Print"
},
{
"code": null,
"e": 2404,
"s": 2393,
"text": " Add Notes"
}
]
|
Python | Pandas Series.ffill() | 13 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.ffill() function is synonym for forward fill. This function is used t fill the missing values in the given series object using forward fill method.
Syntax: Series.ffill(axis=None, inplace=False, limit=None, downcast=None)
Parameter :axis : {0 or βindexβ}inplace : If True, fill in place.limit : If method is specified, this is the maximum number of consecutive NaN values to forward/backward filldowncast : dict, default is None
Returns : filled : Series
Example #1: Use Series.ffill() function to fill out the missing values in the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio']) # Create the Indexsr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.ffill() function to fill out the missing values in the given series object.
# fill the missing valuesresult = sr.ffill() # Print the resultprint(result)
Output :As we can see in the output, the Series.ffill() function has successfully filled out the missing values in the given series object. Example #2 : Use Series.ffill() function to fill out the missing values in the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.ffill() function to fill out the missing values in the given series object.
# fill the missing valuesresult = sr.ffill() # Print the resultprint(result)
Output :As we can see in the output, the Series.ffill() function has successfully filled out the missing values in the given series object.
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.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 447,
"s": 285,
"text": "Pandas Series.ffill() function is synonym for forward fill. This function is used t fill the missing values in the given series object using forward fill method."
},
{
"code": null,
"e": 521,
"s": 447,
"text": "Syntax: Series.ffill(axis=None, inplace=False, limit=None, downcast=None)"
},
{
"code": null,
"e": 728,
"s": 521,
"text": "Parameter :axis : {0 or βindexβ}inplace : If True, fill in place.limit : If method is specified, this is the maximum number of consecutive NaN values to forward/backward filldowncast : dict, default is None"
},
{
"code": null,
"e": 754,
"s": 728,
"text": "Returns : filled : Series"
},
{
"code": null,
"e": 853,
"s": 754,
"text": "Example #1: Use Series.ffill() function to fill out the missing values in the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio']) # Create the Indexsr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 1128,
"s": 853,
"text": null
},
{
"code": null,
"e": 1137,
"s": 1128,
"text": "Output :"
},
{
"code": null,
"e": 1236,
"s": 1137,
"text": "Now we will use Series.ffill() function to fill out the missing values in the given series object."
},
{
"code": "# fill the missing valuesresult = sr.ffill() # Print the resultprint(result)",
"e": 1314,
"s": 1236,
"text": null
},
{
"code": null,
"e": 1554,
"s": 1314,
"text": "Output :As we can see in the output, the Series.ffill() function has successfully filled out the missing values in the given series object. Example #2 : Use Series.ffill() function to fill out the missing values in the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 1833,
"s": 1554,
"text": null
},
{
"code": null,
"e": 1842,
"s": 1833,
"text": "Output :"
},
{
"code": null,
"e": 1941,
"s": 1842,
"text": "Now we will use Series.ffill() function to fill out the missing values in the given series object."
},
{
"code": "# fill the missing valuesresult = sr.ffill() # Print the resultprint(result)",
"e": 2019,
"s": 1941,
"text": null
},
{
"code": null,
"e": 2159,
"s": 2019,
"text": "Output :As we can see in the output, the Series.ffill() function has successfully filled out the missing values in the given series object."
},
{
"code": null,
"e": 2180,
"s": 2159,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2209,
"s": 2180,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2223,
"s": 2209,
"text": "Python-pandas"
},
{
"code": null,
"e": 2230,
"s": 2223,
"text": "Python"
},
{
"code": null,
"e": 2328,
"s": 2230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2360,
"s": 2328,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2387,
"s": 2360,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2408,
"s": 2387,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2431,
"s": 2408,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2487,
"s": 2431,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2518,
"s": 2487,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2560,
"s": 2518,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2602,
"s": 2560,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2641,
"s": 2602,
"text": "Python | Get unique values from a list"
}
]
|
Python β Product of two Dictionary Keys | 17 Dec, 2019
Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Letβs discuss product of like key values and ways to solve it in this article.
Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line.
# Python3 code to demonstrate working of# Dictionary Keys Product# Using dictionary comprehension + keys() # Initialize dictionariestest_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2)) # Using dictionary comprehension + keys()# Dictionary Keys Productres = {key: test_dict2[key] * test_dict1.get(key, 0) for key in test_dict2.keys()} # printing result print("The product dictionary is : " + str(res))
The original dictionary 1 : {'best': 7, 'is': 4, 'gfg': 6}
The original dictionary 2 : {'best': 10, 'is': 6, 'gfg': 10}
The product dictionary is : {'best': 70, 'is': 24, 'gfg': 60}
Method #2 : Using Counter() + β*β operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the minus operator can perform the task of multiplication.
# Python3 code to demonstrate working of# Dictionary Keys Product# Using Counter() + "*" operatorfrom collections import Counter # Initialize dictionariestest_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2)) # Using Counter() + "*" operator# Dictionary Keys Producttemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] * temp2[key] for key in temp1}) # printing result print("The product dictionary is : " + str(dict(res)))
The original dictionary 1 : {'best': 7, 'is': 4, 'gfg': 6}
The original dictionary 2 : {'best': 10, 'is': 6, 'gfg': 10}
The product dictionary is : {'best': 70, 'is': 24, 'gfg': 60}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2019"
},
{
"code": null,
"e": 324,
"s": 28,
"text": "Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Letβs discuss product of like key values and ways to solve it in this article."
},
{
"code": null,
"e": 554,
"s": 324,
"text": "Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line."
},
{
"code": "# Python3 code to demonstrate working of# Dictionary Keys Product# Using dictionary comprehension + keys() # Initialize dictionariestest_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionaries print(\"The original dictionary 1 : \" + str(test_dict1))print(\"The original dictionary 2 : \" + str(test_dict2)) # Using dictionary comprehension + keys()# Dictionary Keys Productres = {key: test_dict2[key] * test_dict1.get(key, 0) for key in test_dict2.keys()} # printing result print(\"The product dictionary is : \" + str(res))",
"e": 1168,
"s": 554,
"text": null
},
{
"code": null,
"e": 1351,
"s": 1168,
"text": "The original dictionary 1 : {'best': 7, 'is': 4, 'gfg': 6}\nThe original dictionary 2 : {'best': 10, 'is': 6, 'gfg': 10}\nThe product dictionary is : {'best': 70, 'is': 24, 'gfg': 60}\n"
},
{
"code": null,
"e": 1606,
"s": 1353,
"text": "Method #2 : Using Counter() + β*β operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the minus operator can perform the task of multiplication."
},
{
"code": "# Python3 code to demonstrate working of# Dictionary Keys Product# Using Counter() + \"*\" operatorfrom collections import Counter # Initialize dictionariestest_dict1 = {'gfg' : 6, 'is' : 4, 'best' : 7}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionaries print(\"The original dictionary 1 : \" + str(test_dict1))print(\"The original dictionary 2 : \" + str(test_dict2)) # Using Counter() + \"*\" operator# Dictionary Keys Producttemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] * temp2[key] for key in temp1}) # printing result print(\"The product dictionary is : \" + str(dict(res)))",
"e": 2251,
"s": 1606,
"text": null
},
{
"code": null,
"e": 2434,
"s": 2251,
"text": "The original dictionary 1 : {'best': 7, 'is': 4, 'gfg': 6}\nThe original dictionary 2 : {'best': 10, 'is': 6, 'gfg': 10}\nThe product dictionary is : {'best': 70, 'is': 24, 'gfg': 60}\n"
},
{
"code": null,
"e": 2461,
"s": 2434,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2468,
"s": 2461,
"text": "Python"
},
{
"code": null,
"e": 2484,
"s": 2468,
"text": "Python Programs"
},
{
"code": null,
"e": 2582,
"s": 2484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2600,
"s": 2582,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2642,
"s": 2600,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2664,
"s": 2642,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2699,
"s": 2664,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2725,
"s": 2699,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2768,
"s": 2725,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2807,
"s": 2768,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2845,
"s": 2807,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2894,
"s": 2845,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
std::string::resize() in C++ | 26 Jul, 2019
resize() lets you change the number of characters. Here are we will describe two syntaxes supported by std::string::resize() in C++Return Value : None
Syntax 1: Resize the number of characters of *this to num.
void string ::resize (size_type num)
num: New string length, expressed in number of characters.
Errors:
Throws length_error if num is equal to string ::npos.
Throws length_error if the resulting size exceeds the maximum number of
characters(max_size()).
Note : If num > size() then, the rest of characters are initialized by the β\0β.
// CPP code for resize (size_type num) #include <iostream>#include <string>using namespace std; // Function to demonstrate insertvoid resizeDemo(string str){ // Resizes str to a string with // 5 initial characters only str.resize(5); cout << "Using resize : "; cout << str;} // Driver codeint main(){ string str("GeeksforGeeks "); cout << "Original String : " << str << endl; resizeDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
Using resize : Geeks
Syntax 2: Uses a character to fill the difference between size() and num.
void string ::resize (size_type num, char c )
num: is the new string length, expressed in number of characters.
c: is the character needed to fill the new character space.
If num > size() : character c is used to fill space.
If num < size() : String is simply resized to num number of characters.
Errors:
Throws length_error if num is equal to string ::npos.
Throws length_error if the resulting size exceeds the maximum number of
characters(max_size()).
// CPP code for resize (size_type num, char c ) #include <iostream>#include <string>using namespace std; // Function to demonstrate insertvoid resizeDemo(string str){ cout << "Using resize :" << endl; cout << "If num > size() : "; // Resizes str to character length of // 15 and fill the space with '$' str.resize(15, '$'); cout << str << endl; cout << "If num < size() : "; // Resizes str to a string with // 5 initial characters only str.resize(5, '$'); cout << str;} // Driver codeint main(){ string str("GeeksforGeeks"); cout << "Original String : " << str << endl; resizeDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
Using resize :
If num > size() : GeeksforGeeks$$
If num < size() : Geeks
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManasChhabra2
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 203,
"s": 52,
"text": "resize() lets you change the number of characters. Here are we will describe two syntaxes supported by std::string::resize() in C++Return Value : None"
},
{
"code": null,
"e": 262,
"s": 203,
"text": "Syntax 1: Resize the number of characters of *this to num."
},
{
"code": null,
"e": 518,
"s": 262,
"text": "void string ::resize (size_type num)\nnum: New string length, expressed in number of characters.\nErrors: \nThrows length_error if num is equal to string ::npos.\nThrows length_error if the resulting size exceeds the maximum number of\ncharacters(max_size()).\n"
},
{
"code": null,
"e": 599,
"s": 518,
"text": "Note : If num > size() then, the rest of characters are initialized by the β\\0β."
},
{
"code": "// CPP code for resize (size_type num) #include <iostream>#include <string>using namespace std; // Function to demonstrate insertvoid resizeDemo(string str){ // Resizes str to a string with // 5 initial characters only str.resize(5); cout << \"Using resize : \"; cout << str;} // Driver codeint main(){ string str(\"GeeksforGeeks \"); cout << \"Original String : \" << str << endl; resizeDemo(str); return 0;}",
"e": 1044,
"s": 599,
"text": null
},
{
"code": null,
"e": 1052,
"s": 1044,
"text": "Output:"
},
{
"code": null,
"e": 1107,
"s": 1052,
"text": "Original String : GeeksforGeeks \nUsing resize : Geeks\n"
},
{
"code": null,
"e": 1181,
"s": 1107,
"text": "Syntax 2: Uses a character to fill the difference between size() and num."
},
{
"code": null,
"e": 1638,
"s": 1181,
"text": "void string ::resize (size_type num, char c )\nnum: is the new string length, expressed in number of characters.\nc: is the character needed to fill the new character space.\nIf num > size() : character c is used to fill space.\nIf num < size() : String is simply resized to num number of characters.\nErrors: \nThrows length_error if num is equal to string ::npos.\nThrows length_error if the resulting size exceeds the maximum number of\ncharacters(max_size()).\n"
},
{
"code": "// CPP code for resize (size_type num, char c ) #include <iostream>#include <string>using namespace std; // Function to demonstrate insertvoid resizeDemo(string str){ cout << \"Using resize :\" << endl; cout << \"If num > size() : \"; // Resizes str to character length of // 15 and fill the space with '$' str.resize(15, '$'); cout << str << endl; cout << \"If num < size() : \"; // Resizes str to a string with // 5 initial characters only str.resize(5, '$'); cout << str;} // Driver codeint main(){ string str(\"GeeksforGeeks\"); cout << \"Original String : \" << str << endl; resizeDemo(str); return 0;}",
"e": 2304,
"s": 1638,
"text": null
},
{
"code": null,
"e": 2312,
"s": 2304,
"text": "Output:"
},
{
"code": null,
"e": 2418,
"s": 2312,
"text": "Original String : GeeksforGeeks\nUsing resize :\nIf num > size() : GeeksforGeeks$$\nIf num < size() : Geeks\n"
},
{
"code": null,
"e": 2736,
"s": 2418,
"text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2861,
"s": 2736,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2875,
"s": 2861,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 2895,
"s": 2875,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 2899,
"s": 2895,
"text": "STL"
},
{
"code": null,
"e": 2903,
"s": 2899,
"text": "C++"
},
{
"code": null,
"e": 2907,
"s": 2903,
"text": "STL"
},
{
"code": null,
"e": 2911,
"s": 2907,
"text": "CPP"
},
{
"code": null,
"e": 3009,
"s": 2911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3033,
"s": 3009,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3053,
"s": 3033,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3086,
"s": 3053,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3111,
"s": 3086,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3155,
"s": 3111,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3200,
"s": 3155,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3248,
"s": 3200,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3292,
"s": 3248,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3309,
"s": 3292,
"text": "std::find in C++"
}
]
|
ZonedDateTime plus() method in Java with Examples | 18 Dec, 2018
In ZonedDateTime class, there are two types of plus() method depending upon the parameters passed to it.
plus() method of a ZonedDateTime class used to return a copy of this date-time with the specified amount of unit added.If it is not possible to add the amount, because the unit is not supported or for some other reason, an exception is thrown.
Syntax:
public ZonedDateTime plus(long amountToAdd,
TemporalUnit unit)
Parameters: This method accepts two parameters:
amountToAdd: which is the amount of the unit to add to the result, may be negative
unit: which is the unit of the amount to add.
Return value: This method returns ZonedDateTime based on this date-time with the specified amount added.
Exception: This method throws following Exceptions:
DateTimeException: if the addition cannot be made.
UnsupportedTemporalTypeException: if the unit is not supported.
ArithmeticException: if numeric overflow occurs.
Below programs illustrate the plus() method:
Program 1:
// Java program to demonstrate// ZonedDateTime.plus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a ZonedDateTime object ZonedDateTime zonedlt = ZonedDateTime .parse( "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // add 30 Months to ZonedDateTime ZonedDateTime value = zonedlt.plus(30, ChronoUnit.MONTHS); // print result System.out.println("ZonedDateTime after" + " adding Months: \n" + value); }}
ZonedDateTime after adding Months:
2021-06-06T19:21:12.123+05:30[Asia/Calcutta]
plus() method of a ZonedDateTime class used to return a copy of this date-time with the specified amount added to date-time.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.
Syntax:
public ZonedDateTime plus(TemporalAmount amountToAdd)
Parameters: This method accepts one single parameter amountToAdd which is the amount to add, It should not be null.
Return value: This method returns ZonedDateTime based on this date-time with the addition made.
Exception: This method throws following Exceptions:
DateTimeException: if the addition cannot be made.
ArithmeticException: if numeric overflow occurs.
Below programs illustrate the plus() method:
Program 1:
// Java program to demonstrate// ZonedDateTime.plus() method import java.time.*;public class GFG { public static void main(String[] args) { // create a ZonedDateTime object ZonedDateTime zonedlt = ZonedDateTime .parse( "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // add 100 Days to ZonedDateTime ZonedDateTime value = zonedlt.plus(Period.ofDays(100)); // print result System.out.println("ZonedDateTime after" + " adding Days: \n" + value); }}
ZonedDateTime after adding Days:
2019-03-16T19:21:12.123+05:30[Asia/Calcutta]
Reference:
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#plus(java.time.temporal.TemporalAmount)
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#plus(long, java.time.temporal.TemporalUnit)
Java-Functions
Java-time package
Java-ZonedDateTime
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": "\n18 Dec, 2018"
},
{
"code": null,
"e": 133,
"s": 28,
"text": "In ZonedDateTime class, there are two types of plus() method depending upon the parameters passed to it."
},
{
"code": null,
"e": 377,
"s": 133,
"text": "plus() method of a ZonedDateTime class used to return a copy of this date-time with the specified amount of unit added.If it is not possible to add the amount, because the unit is not supported or for some other reason, an exception is thrown."
},
{
"code": null,
"e": 385,
"s": 377,
"text": "Syntax:"
},
{
"code": null,
"e": 475,
"s": 385,
"text": "public ZonedDateTime plus(long amountToAdd,\n TemporalUnit unit)\n"
},
{
"code": null,
"e": 523,
"s": 475,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 606,
"s": 523,
"text": "amountToAdd: which is the amount of the unit to add to the result, may be negative"
},
{
"code": null,
"e": 652,
"s": 606,
"text": "unit: which is the unit of the amount to add."
},
{
"code": null,
"e": 757,
"s": 652,
"text": "Return value: This method returns ZonedDateTime based on this date-time with the specified amount added."
},
{
"code": null,
"e": 809,
"s": 757,
"text": "Exception: This method throws following Exceptions:"
},
{
"code": null,
"e": 860,
"s": 809,
"text": "DateTimeException: if the addition cannot be made."
},
{
"code": null,
"e": 924,
"s": 860,
"text": "UnsupportedTemporalTypeException: if the unit is not supported."
},
{
"code": null,
"e": 973,
"s": 924,
"text": "ArithmeticException: if numeric overflow occurs."
},
{
"code": null,
"e": 1018,
"s": 973,
"text": "Below programs illustrate the plus() method:"
},
{
"code": null,
"e": 1029,
"s": 1018,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// ZonedDateTime.plus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a ZonedDateTime object ZonedDateTime zonedlt = ZonedDateTime .parse( \"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // add 30 Months to ZonedDateTime ZonedDateTime value = zonedlt.plus(30, ChronoUnit.MONTHS); // print result System.out.println(\"ZonedDateTime after\" + \" adding Months: \\n\" + value); }}",
"e": 1692,
"s": 1029,
"text": null
},
{
"code": null,
"e": 1774,
"s": 1692,
"text": "ZonedDateTime after adding Months: \n2021-06-06T19:21:12.123+05:30[Asia/Calcutta]\n"
},
{
"code": null,
"e": 2010,
"s": 1774,
"text": "plus() method of a ZonedDateTime class used to return a copy of this date-time with the specified amount added to date-time.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface."
},
{
"code": null,
"e": 2018,
"s": 2010,
"text": "Syntax:"
},
{
"code": null,
"e": 2073,
"s": 2018,
"text": "public ZonedDateTime plus(TemporalAmount amountToAdd)\n"
},
{
"code": null,
"e": 2189,
"s": 2073,
"text": "Parameters: This method accepts one single parameter amountToAdd which is the amount to add, It should not be null."
},
{
"code": null,
"e": 2285,
"s": 2189,
"text": "Return value: This method returns ZonedDateTime based on this date-time with the addition made."
},
{
"code": null,
"e": 2337,
"s": 2285,
"text": "Exception: This method throws following Exceptions:"
},
{
"code": null,
"e": 2388,
"s": 2337,
"text": "DateTimeException: if the addition cannot be made."
},
{
"code": null,
"e": 2437,
"s": 2388,
"text": "ArithmeticException: if numeric overflow occurs."
},
{
"code": null,
"e": 2482,
"s": 2437,
"text": "Below programs illustrate the plus() method:"
},
{
"code": null,
"e": 2493,
"s": 2482,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// ZonedDateTime.plus() method import java.time.*;public class GFG { public static void main(String[] args) { // create a ZonedDateTime object ZonedDateTime zonedlt = ZonedDateTime .parse( \"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // add 100 Days to ZonedDateTime ZonedDateTime value = zonedlt.plus(Period.ofDays(100)); // print result System.out.println(\"ZonedDateTime after\" + \" adding Days: \\n\" + value); }}",
"e": 3111,
"s": 2493,
"text": null
},
{
"code": null,
"e": 3191,
"s": 3111,
"text": "ZonedDateTime after adding Days: \n2019-03-16T19:21:12.123+05:30[Asia/Calcutta]\n"
},
{
"code": null,
"e": 3202,
"s": 3191,
"text": "Reference:"
},
{
"code": null,
"e": 3314,
"s": 3202,
"text": "https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#plus(java.time.temporal.TemporalAmount)"
},
{
"code": null,
"e": 3430,
"s": 3314,
"text": "https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#plus(long, java.time.temporal.TemporalUnit)"
},
{
"code": null,
"e": 3445,
"s": 3430,
"text": "Java-Functions"
},
{
"code": null,
"e": 3463,
"s": 3445,
"text": "Java-time package"
},
{
"code": null,
"e": 3482,
"s": 3463,
"text": "Java-ZonedDateTime"
},
{
"code": null,
"e": 3487,
"s": 3482,
"text": "Java"
},
{
"code": null,
"e": 3492,
"s": 3487,
"text": "Java"
}
]
|
Topological Sorting | 03 Jun, 2022
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
For example, a topological sorting of the following graph is β5 4 2 3 1 0β. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is β4 5 2 3 1 0β. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges).
Topological Sorting vs Depth First Traversal (DFS):
In DFS, we print a vertex and then recursively call DFS for its adjacent vertices. In topological sorting, we need to print a vertex before its adjacent vertices. For example, in the given graph, the vertex β5β should be printed before vertex β0β, but unlike DFS, the vertex β4β should also be printed before vertex β0β. So Topological sorting is different from DFS. For example, a DFS of the shown graph is β5 2 3 1 0 4β, but it is not a topological sorting.
Algorithm to find Topological Sorting:
We recommend to first see the implementation of DFS. We can modify DFS to find Topological Sorting of a graph. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. In topological sorting, we use a temporary stack. We donβt print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of the stack. Note that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in the stack.
Below image is an illustration of the above approach:
Following are the implementations of topological sorting. Please see the code for Depth First Traversal for a disconnected Graph and note the differences between the second code given there and the below code.
C++
Java
Python3
C#
Javascript
// A C++ program to print topological// sorting of a DAG#include <iostream>#include <list>#include <stack>using namespace std; // Class to represent a graphclass Graph { // No. of vertices' int V; // Pointer to an array containing adjacency listsList list<int>* adj; // A function used by topologicalSort void topologicalSortUtil(int v, bool visited[], stack<int>& Stack); public: // Constructor Graph(int V); // function to add an edge to graph void addEdge(int v, int w); // prints a Topological Sort of // the complete graph void topologicalSort();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ // Add w to vβs list. adj[v].push_back(w);} // A recursive function used by topologicalSortvoid Graph::topologicalSortUtil(int v, bool visited[], stack<int>& Stack){ // Mark the current node as visited. visited[v] = true; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) topologicalSortUtil(*i, visited, Stack); // Push current vertex to stack // which stores result Stack.push(v);} // The function to do Topological Sort.// It uses recursive topologicalSortUtil()void Graph::topologicalSort(){ stack<int> Stack; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to store Topological // Sort starting from all // vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Print contents of stack while (Stack.empty() == false) { cout << Stack.top() << " "; Stack.pop(); }} // Driver Codeint main(){ // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << "Following is a Topological Sort of the given " "graph \n"; // Function Call g.topologicalSort(); return 0;}
// A Java program to print topological// sorting of a DAGimport java.io.*;import java.util.*; // This class represents a directed graph// using adjacency list representationclass Graph { // No. of vertices private int V; // Adjacency List as ArrayList of ArrayList's private ArrayList<ArrayList<Integer> > adj; // Constructor Graph(int v) { V = v; adj = new ArrayList<ArrayList<Integer> >(v); for (int i = 0; i < v; ++i) adj.add(new ArrayList<Integer>()); } // Function to add an edge into the graph void addEdge(int v, int w) { adj.get(v).add(w); } // A recursive function used by topologicalSort void topologicalSortUtil(int v, boolean visited[], Stack<Integer> stack) { // Mark the current node as visited. visited[v] = true; Integer i; // Recur for all the vertices adjacent // to thisvertex Iterator<Integer> it = adj.get(v).iterator(); while (it.hasNext()) { i = it.next(); if (!visited[i]) topologicalSortUtil(i, visited, stack); } // Push current vertex to stack // which stores result stack.push(new Integer(v)); } // The function to do Topological Sort. // It uses recursive topologicalSortUtil() void topologicalSort() { Stack<Integer> stack = new Stack<Integer>(); // Mark all the vertices as not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper // function to store // Topological Sort starting // from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, stack); // Print contents of stack while (stack.empty() == false) System.out.print(stack.pop() + " "); } // Driver code public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); System.out.println("Following is a Topological " + "sort of the given graph"); // Function Call g.topologicalSort(); }}// This code is contributed by Aakash Hasija
# Python program to print topological sorting of a DAGfrom collections import defaultdict # Class to represent a graph class Graph: def __init__(self, vertices): self.graph = defaultdict(list) # dictionary containing adjacency List self.V = vertices # No. of vertices # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A recursive function used by topologicalSort def topologicalSortUtil(self, v, visited, stack): # Mark the current node as visited. visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.topologicalSortUtil(i, visited, stack) # Push current vertex to stack which stores result stack.append(v) # The function to do Topological Sort. It uses recursive # topologicalSortUtil() def topologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V stack = [] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if visited[i] == False: self.topologicalSortUtil(i, visited, stack) # Print contents of the stack print(stack[::-1]) # return list in reverse order # Driver Codeg = Graph(6)g.addEdge(5, 2)g.addEdge(5, 0)g.addEdge(4, 0)g.addEdge(4, 1)g.addEdge(2, 3)g.addEdge(3, 1) print ("Following is a Topological Sort of the given graph") # Function Callg.topologicalSort() # This code is contributed by Neelam Yadav
// A C# program to print topological// sorting of a DAGusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph { // No. of vertices private int V; // Adjacency List as ArrayList // of ArrayList's private List<List<int> > adj; // Constructor Graph(int v) { V = v; adj = new List<List<int> >(v); for (int i = 0; i < v; i++) adj.Add(new List<int>()); } // Function to add an edge into the graph public void AddEdge(int v, int w) { adj[v].Add(w); } // A recursive function used by topologicalSort void TopologicalSortUtil(int v, bool[] visited, Stack<int> stack) { // Mark the current node as visited. visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach(var vertex in adj[v]) { if (!visited[vertex]) TopologicalSortUtil(vertex, visited, stack); } // Push current vertex to // stack which stores result stack.Push(v); } // The function to do Topological Sort. // It uses recursive topologicalSortUtil() void TopologicalSort() { Stack<int> stack = new Stack<int>(); // Mark all the vertices as not visited var visited = new bool[V]; // Call the recursive helper function // to store Topological Sort starting // from all vertices one by one for (int i = 0; i < V; i++) { if (visited[i] == false) TopologicalSortUtil(i, visited, stack); } // Print contents of stack foreach(var vertex in stack) { Console.Write(vertex + " "); } } // Driver code public static void Main(string[] args) { // Create a graph given // in the above diagram Graph g = new Graph(6); g.AddEdge(5, 2); g.AddEdge(5, 0); g.AddEdge(4, 0); g.AddEdge(4, 1); g.AddEdge(2, 3); g.AddEdge(3, 1); Console.WriteLine("Following is a Topological " + "sort of the given graph"); // Function Call g.TopologicalSort(); }} // This code is contributed by Abhinav Galodha
<script> // Javascript for the above approach // This class represents a directed graph // using adjacency list representation class Graph{ // Constructor constructor(v) { // Number of vertices this.V = v // Adjacency List as ArrayList of ArrayList's this.adj = new Array(this.V) for (let i = 0 ; i < this.V ; i+=1){ this.adj[i] = new Array() } } // Function to add an edge into the graph addEdge(v, w){ this.adj[v].push(w) } // A recursive function used by topologicalSort topologicalSortUtil(v, visited, stack) { // Mark the current node as visited. visited[v] = true; let i = 0; // Recur for all the vertices adjacent // to thisvertex for(i = 0 ; i < this.adj[v].length ; i++){ if(!visited[this.adj[v][i]]){ this.topologicalSortUtil(this.adj[v][i], visited, stack) } } // Push current vertex to stack // which stores result stack.push(v); } // The function to do Topological Sort. // It uses recursive topologicalSortUtil() topologicalSort() { let stack = new Array() // Mark all the vertices as not visited let visited = new Array(this.V); for (let i = 0 ; i < this.V ; i++){ visited[i] = false; } // Call the recursive helper // function to store // Topological Sort starting // from all vertices one by one for (let i = 0 ; i < this.V ; i++){ if (visited[i] == false){ this.topologicalSortUtil(i, visited, stack); } } // Print contents of stack while (stack.length != 0){ console.log(stack.pop() + " ") } } } // Driver Code var g = new Graph(6) g.addEdge(5, 2) g.addEdge(5, 0) g.addEdge(4, 0) g.addEdge(4, 1) g.addEdge(2, 3) g.addEdge(3, 1) console.log("Following is a Topological sort of the given graph") // Function Call g.topologicalSort() // This code is contributed by subhamgoyal2014.</script>
Following is a Topological Sort of the given graph
5 4 2 3 1 0
Complexity Analysis:
Time Complexity: O(V+E). The above algorithm is simply DFS with an extra stack. So time complexity is the same as DFS which is.
Auxiliary space: O(V). The extra space is needed for the stack.
Note: Here, we can also use vector instead of the stack. If the vector is used then print the elements in reverse order to get the topological sorting.
Applications: Topological Sorting is mainly used for scheduling jobs from the given dependencies among jobs. In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets, logic synthesis, determining the order of compilation tasks to perform in make files, data serialization, and resolving symbol dependencies in linkers [2].
Topological Sorting | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersTopological Sorting | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:58β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Q9PIxaNGnig" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Related Articles: Kahnβs algorithm for Topological Sorting : Another O(V + E) algorithm. All Topological Sorts of a Directed Acyclic Graph
References: http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/GraphAlgor/topoSort.htm http://en.wikipedia.org/wiki/Topological_sortingPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ConstantineShulyupin
ShivamBhasin
andrew1234
abhinavgalodha
technicallynoob
highnessatharva
amartyaghoshgfg
subhamgoyal2014
Accolite
Amazon
DFS
Flipkart
Microsoft
Moonfrog Labs
Morgan Stanley
OYO Rooms
Samsung
Topological Sorting
Graph
Moonfrog Labs
Flipkart
Morgan Stanley
Accolite
Amazon
Microsoft
OYO Rooms
Samsung
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG."
},
{
"code": null,
"e": 628,
"s": 295,
"text": "For example, a topological sorting of the following graph is β5 4 2 3 1 0β. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is β4 5 2 3 1 0β. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges). "
},
{
"code": null,
"e": 681,
"s": 628,
"text": "Topological Sorting vs Depth First Traversal (DFS): "
},
{
"code": null,
"e": 1141,
"s": 681,
"text": "In DFS, we print a vertex and then recursively call DFS for its adjacent vertices. In topological sorting, we need to print a vertex before its adjacent vertices. For example, in the given graph, the vertex β5β should be printed before vertex β0β, but unlike DFS, the vertex β4β should also be printed before vertex β0β. So Topological sorting is different from DFS. For example, a DFS of the shown graph is β5 2 3 1 0 4β, but it is not a topological sorting."
},
{
"code": null,
"e": 1181,
"s": 1141,
"text": "Algorithm to find Topological Sorting: "
},
{
"code": null,
"e": 1772,
"s": 1181,
"text": "We recommend to first see the implementation of DFS. We can modify DFS to find Topological Sorting of a graph. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. In topological sorting, we use a temporary stack. We donβt print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of the stack. Note that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in the stack. "
},
{
"code": null,
"e": 1826,
"s": 1772,
"text": "Below image is an illustration of the above approach:"
},
{
"code": null,
"e": 2036,
"s": 1826,
"text": "Following are the implementations of topological sorting. Please see the code for Depth First Traversal for a disconnected Graph and note the differences between the second code given there and the below code."
},
{
"code": null,
"e": 2040,
"s": 2036,
"text": "C++"
},
{
"code": null,
"e": 2045,
"s": 2040,
"text": "Java"
},
{
"code": null,
"e": 2053,
"s": 2045,
"text": "Python3"
},
{
"code": null,
"e": 2056,
"s": 2053,
"text": "C#"
},
{
"code": null,
"e": 2067,
"s": 2056,
"text": "Javascript"
},
{
"code": "// A C++ program to print topological// sorting of a DAG#include <iostream>#include <list>#include <stack>using namespace std; // Class to represent a graphclass Graph { // No. of vertices' int V; // Pointer to an array containing adjacency listsList list<int>* adj; // A function used by topologicalSort void topologicalSortUtil(int v, bool visited[], stack<int>& Stack); public: // Constructor Graph(int V); // function to add an edge to graph void addEdge(int v, int w); // prints a Topological Sort of // the complete graph void topologicalSort();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ // Add w to vβs list. adj[v].push_back(w);} // A recursive function used by topologicalSortvoid Graph::topologicalSortUtil(int v, bool visited[], stack<int>& Stack){ // Mark the current node as visited. visited[v] = true; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) topologicalSortUtil(*i, visited, Stack); // Push current vertex to stack // which stores result Stack.push(v);} // The function to do Topological Sort.// It uses recursive topologicalSortUtil()void Graph::topologicalSort(){ stack<int> Stack; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to store Topological // Sort starting from all // vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Print contents of stack while (Stack.empty() == false) { cout << Stack.top() << \" \"; Stack.pop(); }} // Driver Codeint main(){ // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << \"Following is a Topological Sort of the given \" \"graph \\n\"; // Function Call g.topologicalSort(); return 0;}",
"e": 4342,
"s": 2067,
"text": null
},
{
"code": "// A Java program to print topological// sorting of a DAGimport java.io.*;import java.util.*; // This class represents a directed graph// using adjacency list representationclass Graph { // No. of vertices private int V; // Adjacency List as ArrayList of ArrayList's private ArrayList<ArrayList<Integer> > adj; // Constructor Graph(int v) { V = v; adj = new ArrayList<ArrayList<Integer> >(v); for (int i = 0; i < v; ++i) adj.add(new ArrayList<Integer>()); } // Function to add an edge into the graph void addEdge(int v, int w) { adj.get(v).add(w); } // A recursive function used by topologicalSort void topologicalSortUtil(int v, boolean visited[], Stack<Integer> stack) { // Mark the current node as visited. visited[v] = true; Integer i; // Recur for all the vertices adjacent // to thisvertex Iterator<Integer> it = adj.get(v).iterator(); while (it.hasNext()) { i = it.next(); if (!visited[i]) topologicalSortUtil(i, visited, stack); } // Push current vertex to stack // which stores result stack.push(new Integer(v)); } // The function to do Topological Sort. // It uses recursive topologicalSortUtil() void topologicalSort() { Stack<Integer> stack = new Stack<Integer>(); // Mark all the vertices as not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper // function to store // Topological Sort starting // from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, stack); // Print contents of stack while (stack.empty() == false) System.out.print(stack.pop() + \" \"); } // Driver code public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); System.out.println(\"Following is a Topological \" + \"sort of the given graph\"); // Function Call g.topologicalSort(); }}// This code is contributed by Aakash Hasija",
"e": 6818,
"s": 4342,
"text": null
},
{
"code": "# Python program to print topological sorting of a DAGfrom collections import defaultdict # Class to represent a graph class Graph: def __init__(self, vertices): self.graph = defaultdict(list) # dictionary containing adjacency List self.V = vertices # No. of vertices # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A recursive function used by topologicalSort def topologicalSortUtil(self, v, visited, stack): # Mark the current node as visited. visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.topologicalSortUtil(i, visited, stack) # Push current vertex to stack which stores result stack.append(v) # The function to do Topological Sort. It uses recursive # topologicalSortUtil() def topologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V stack = [] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if visited[i] == False: self.topologicalSortUtil(i, visited, stack) # Print contents of the stack print(stack[::-1]) # return list in reverse order # Driver Codeg = Graph(6)g.addEdge(5, 2)g.addEdge(5, 0)g.addEdge(4, 0)g.addEdge(4, 1)g.addEdge(2, 3)g.addEdge(3, 1) print (\"Following is a Topological Sort of the given graph\") # Function Callg.topologicalSort() # This code is contributed by Neelam Yadav",
"e": 8454,
"s": 6818,
"text": null
},
{
"code": "// A C# program to print topological// sorting of a DAGusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph { // No. of vertices private int V; // Adjacency List as ArrayList // of ArrayList's private List<List<int> > adj; // Constructor Graph(int v) { V = v; adj = new List<List<int> >(v); for (int i = 0; i < v; i++) adj.Add(new List<int>()); } // Function to add an edge into the graph public void AddEdge(int v, int w) { adj[v].Add(w); } // A recursive function used by topologicalSort void TopologicalSortUtil(int v, bool[] visited, Stack<int> stack) { // Mark the current node as visited. visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach(var vertex in adj[v]) { if (!visited[vertex]) TopologicalSortUtil(vertex, visited, stack); } // Push current vertex to // stack which stores result stack.Push(v); } // The function to do Topological Sort. // It uses recursive topologicalSortUtil() void TopologicalSort() { Stack<int> stack = new Stack<int>(); // Mark all the vertices as not visited var visited = new bool[V]; // Call the recursive helper function // to store Topological Sort starting // from all vertices one by one for (int i = 0; i < V; i++) { if (visited[i] == false) TopologicalSortUtil(i, visited, stack); } // Print contents of stack foreach(var vertex in stack) { Console.Write(vertex + \" \"); } } // Driver code public static void Main(string[] args) { // Create a graph given // in the above diagram Graph g = new Graph(6); g.AddEdge(5, 2); g.AddEdge(5, 0); g.AddEdge(4, 0); g.AddEdge(4, 1); g.AddEdge(2, 3); g.AddEdge(3, 1); Console.WriteLine(\"Following is a Topological \" + \"sort of the given graph\"); // Function Call g.TopologicalSort(); }} // This code is contributed by Abhinav Galodha",
"e": 10761,
"s": 8454,
"text": null
},
{
"code": "<script> // Javascript for the above approach // This class represents a directed graph // using adjacency list representation class Graph{ // Constructor constructor(v) { // Number of vertices this.V = v // Adjacency List as ArrayList of ArrayList's this.adj = new Array(this.V) for (let i = 0 ; i < this.V ; i+=1){ this.adj[i] = new Array() } } // Function to add an edge into the graph addEdge(v, w){ this.adj[v].push(w) } // A recursive function used by topologicalSort topologicalSortUtil(v, visited, stack) { // Mark the current node as visited. visited[v] = true; let i = 0; // Recur for all the vertices adjacent // to thisvertex for(i = 0 ; i < this.adj[v].length ; i++){ if(!visited[this.adj[v][i]]){ this.topologicalSortUtil(this.adj[v][i], visited, stack) } } // Push current vertex to stack // which stores result stack.push(v); } // The function to do Topological Sort. // It uses recursive topologicalSortUtil() topologicalSort() { let stack = new Array() // Mark all the vertices as not visited let visited = new Array(this.V); for (let i = 0 ; i < this.V ; i++){ visited[i] = false; } // Call the recursive helper // function to store // Topological Sort starting // from all vertices one by one for (let i = 0 ; i < this.V ; i++){ if (visited[i] == false){ this.topologicalSortUtil(i, visited, stack); } } // Print contents of stack while (stack.length != 0){ console.log(stack.pop() + \" \") } } } // Driver Code var g = new Graph(6) g.addEdge(5, 2) g.addEdge(5, 0) g.addEdge(4, 0) g.addEdge(4, 1) g.addEdge(2, 3) g.addEdge(3, 1) console.log(\"Following is a Topological sort of the given graph\") // Function Call g.topologicalSort() // This code is contributed by subhamgoyal2014.</script>",
"e": 13139,
"s": 10761,
"text": null
},
{
"code": null,
"e": 13204,
"s": 13139,
"text": "Following is a Topological Sort of the given graph \n5 4 2 3 1 0 "
},
{
"code": null,
"e": 13226,
"s": 13204,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 13354,
"s": 13226,
"text": "Time Complexity: O(V+E). The above algorithm is simply DFS with an extra stack. So time complexity is the same as DFS which is."
},
{
"code": null,
"e": 13418,
"s": 13354,
"text": "Auxiliary space: O(V). The extra space is needed for the stack."
},
{
"code": null,
"e": 13570,
"s": 13418,
"text": "Note: Here, we can also use vector instead of the stack. If the vector is used then print the elements in reverse order to get the topological sorting."
},
{
"code": null,
"e": 14001,
"s": 13570,
"text": "Applications: Topological Sorting is mainly used for scheduling jobs from the given dependencies among jobs. In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets, logic synthesis, determining the order of compilation tasks to perform in make files, data serialization, and resolving symbol dependencies in linkers [2]. "
},
{
"code": null,
"e": 14857,
"s": 14001,
"text": "Topological Sorting | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersTopological Sorting | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:58β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Q9PIxaNGnig\" 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": 14996,
"s": 14857,
"text": "Related Articles: Kahnβs algorithm for Topological Sorting : Another O(V + E) algorithm. All Topological Sorts of a Directed Acyclic Graph"
},
{
"code": null,
"e": 15267,
"s": 14996,
"text": "References: http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/GraphAlgor/topoSort.htm http://en.wikipedia.org/wiki/Topological_sortingPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 15288,
"s": 15267,
"text": "ConstantineShulyupin"
},
{
"code": null,
"e": 15301,
"s": 15288,
"text": "ShivamBhasin"
},
{
"code": null,
"e": 15312,
"s": 15301,
"text": "andrew1234"
},
{
"code": null,
"e": 15327,
"s": 15312,
"text": "abhinavgalodha"
},
{
"code": null,
"e": 15343,
"s": 15327,
"text": "technicallynoob"
},
{
"code": null,
"e": 15359,
"s": 15343,
"text": "highnessatharva"
},
{
"code": null,
"e": 15375,
"s": 15359,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 15391,
"s": 15375,
"text": "subhamgoyal2014"
},
{
"code": null,
"e": 15400,
"s": 15391,
"text": "Accolite"
},
{
"code": null,
"e": 15407,
"s": 15400,
"text": "Amazon"
},
{
"code": null,
"e": 15411,
"s": 15407,
"text": "DFS"
},
{
"code": null,
"e": 15420,
"s": 15411,
"text": "Flipkart"
},
{
"code": null,
"e": 15430,
"s": 15420,
"text": "Microsoft"
},
{
"code": null,
"e": 15444,
"s": 15430,
"text": "Moonfrog Labs"
},
{
"code": null,
"e": 15459,
"s": 15444,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 15469,
"s": 15459,
"text": "OYO Rooms"
},
{
"code": null,
"e": 15477,
"s": 15469,
"text": "Samsung"
},
{
"code": null,
"e": 15497,
"s": 15477,
"text": "Topological Sorting"
},
{
"code": null,
"e": 15503,
"s": 15497,
"text": "Graph"
},
{
"code": null,
"e": 15517,
"s": 15503,
"text": "Moonfrog Labs"
},
{
"code": null,
"e": 15526,
"s": 15517,
"text": "Flipkart"
},
{
"code": null,
"e": 15541,
"s": 15526,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 15550,
"s": 15541,
"text": "Accolite"
},
{
"code": null,
"e": 15557,
"s": 15550,
"text": "Amazon"
},
{
"code": null,
"e": 15567,
"s": 15557,
"text": "Microsoft"
},
{
"code": null,
"e": 15577,
"s": 15567,
"text": "OYO Rooms"
},
{
"code": null,
"e": 15585,
"s": 15577,
"text": "Samsung"
},
{
"code": null,
"e": 15589,
"s": 15585,
"text": "DFS"
},
{
"code": null,
"e": 15595,
"s": 15589,
"text": "Graph"
}
]
|
Poverty Alleviation Programmes in India | 30 Nov, 2021
In the mid 19th century and early 20th century, we saw an increase in poverty during the colonial age. The colonial rules moved unwaged artisans into farming and converted the nation into a province gradually rich in land-living, uneducated labor, and low efficiency. Thus, it made the nation scarce in labor, capital, and knowledge.
Poverty Alleviation or Relief, or Reduction, is a set of ways, by which governmentsβ policies can intend to permanently lift people out of the poverty line. As per the Global Multidimensional Poverty Index (MPI) 2020, India ranks at 62nd position out of 107 nations with an MPI score of 0.123. Recently a study also revealed that six multidimensionally poor people, five were from lower tribes or castes and according to the Global Hunger Index 2021, with a score of 27.5, India ranks 101st out of the 116 countries, and according to the data, the level of hunger is serious.
There are some major reasons for poverty in India, due to less financial support to the lower-income group, over-population, fewer job opportunities, discrimination and casteism of society, lack of education, and huge corruption in society.
Indiaβs most persuasive task is the removal of poverty and for that the Indian government has taken various programs, schemes, policies based on two main objectives:
Launching anti-poverty programs to address a specific group of people.Increasing economic growth of the country by providing job opportunities to the lower-income groups.
Launching anti-poverty programs to address a specific group of people.
Increasing economic growth of the country by providing job opportunities to the lower-income groups.
After India got its independence, various initiatives were taken to reduce the poverty in India such as in 1950 by Minhas estimating the poverty rates in India, in 1960 a working group was formed to set up a poverty line for India and various others following that. In the first time after post-Independence history, poverty was considered a national issue under the Chairmanship of Indiaβs third prime minister Indira Gandhi. To achieve two main objectives, removal of poverty βGaribi Hataoβ and attainment of self-reliance, D.D. Dhar prepared and launched the 5th Five Years Plan through the better distribution of income, promotion of high growth rate, and significant growth in the rural area.
It was started in the year 1980-81 to create self-employment for the poor people in rural areas. The main aim of IRDP was to decrease the levels of the families in the below poverty line category permanently by providing them revenue-generating resources and access to other inputs.
It was launched on April 1st, 1989, by an amalgamation of the National Rural Employment Program (NREP) and Rural Landless Employment Guarantee Programme (RLEGP) to create employment options and improve the quality of life for the unemployed and under-employed public in rural parts by generating community and social assets and the rural economic infrastructure. The objective of the program was supplementary profitable employment for the unemployed and underemployed people in the rural parts, to create constant employment by strengthening the rural financial structure and assets supporting the poor people in the rural parts for their continuous benefits. In this Yojana, thirty percent of the employment options are held in reserve for females in rural parts.
The Jawahar Rozgar Yojana was again reformed as Jawahar Gram Samridhi Yojana on 1st April 1999. This scheme on 25th September 2001 was further modified to the Sampoorna Grameen Rozgar Yojana. The objective is to generate demand-driven community village infrastructure that would enable the poor people in the rural parts to increase sustained employment opportunities, durable possessions at the village level. It also includes the creation of additional employment options for the unemployed in the rural parts. The wage employment could be provided to below poverty line (BPL) families.
It was launched on October 2nd, 1993. It covers drought-prone parts, desert parts, tribal parts, and hill region areas. This scheme during the year 1994-95 was implemented across the nationβs 409 blocks and by April 1997 this scheme was extended to cover all the blocks. The primary objective of this scheme was to generate supplementary wage employment options when there is an acute shortage in manual work during lean agricultural seasons to all able adult poor persons of rural areas who are in need of work at that time, and the secondary objective of this scheme is to generate of financial infrastructure and community assets for employment and growth for rural India.
It was launched in the year 1977-78 by providing food grains as a substitute for wages. This was then restructured with changes implemented in 2001 for the most 150 backward districts of the country to create additional employment for the provisions of lives. The objective is to make available supplementary resources apart from the ones available below the Sampoorna Grameen Rozgar Yojana to the 150 most backward districts of the nation. This program can lead to the creation of additional wage employment opportunities and making available food safety through generating need-based societal, financial, and communal assets in these backward districts.
It was launched in the year 2001 via merging the Jawahar Gram Samridhi Yojana and Employment Assurance scheme by the Ministry of Rural Development. The main aim of the scheme was to provide supplementary wage employment options, provide food safety and improved nutritional stages in all parts, generate durable community social and monetary assets, and infrastructural expansion for the poor in rural areas.
Earlier referred to as Indira Awaas Yojana. The Pradhan Mantri Grameen Awaas Yojana was launched in the year 2015 is created to provide construction of free houses for the rural poor in India who are below the poverty line.
The objective is the advancement of affordable housing options through the credit-linked subsidy process, restoration of slum dwellers with the involvement of the private sector using the land-dwelling as a resource, reasonable housing in association with government and private subsidy.
It was launched on 15th August 1995 with the objective of secure social security and welfare program to provide support to widows, aged persons, disabled persons, and bereaved those families on the death of the primary breadwinner, belonging to BPL households for the fulfillment of the Article 41 and Article 42 of Directive Principles of State Policy which is mentioned in Part IV of the Constitution of India. It also had three components namely,
A. National Old Age Pension Scheme (NOAPS): It was launched in the year 1995 to provide pensions to the person who is a βdestituteβ having little or no source of income or monetary support. The main aim is to make available social safety to the eligible beneficiaries. In this, the senior citizens 60 years or above receive a monthly pension and it is a non-contribution person, wherein the beneficiary does not have to contribute any amount to receive the pension.
B. National Family Benefit Scheme (NFBS): It was launched in the year 1995 to support with a lumpsum amount to the household below the poverty line who then becomes the head of the family after the death of the main wage earner. It provides a lumpsum amount of Rs.10,000/- to the household and it is applicable in the age group of 18-64 years.
C. National Maternity Benefit Scheme (NMBS): In the National Maternity Benefit Scheme, a financial grant is provided to women belonging to poor families for pre-natal and post-natal care. It is for women aged above 19 years and above up to the first two live births. It is a cash-based maternity assistance scheme.
The social clusters are most susceptible to poverty, and they are categorized as SC and ST and in the economic clusters, the most susceptible are the agricultural labor in rural parts and the casual labor in the urban parts. The challenges lie ahead such as the rural and the urban parts showing vast differences in poverty.
It is true that poverty has been reduced but not up to the intended level. As a citizen or as a government, still we have to focus on the food chain, clothing, population control, free education at the basic level, empowerment of women and fiscally weaker sections of the society, medical facilities, etc. for better results.
Economics
UPSC
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Role of Micro-Credit in Meeting the Credit Requirements of the Poor
Types of Expenditure in Budget
National Population Policy 2000
Role of Self Help Groups in Poverty Alleviation
Government Policies to Meet the Challenges of the Food Processing Sector
Nehruβs Report - Gulf Between Congress and Muslim League
Types of Receipts of Union Budget
Important Mountains Passes of India
Evolution of Concept of Basic Structure
Diversification Towards Animal Husbandry, Fisheries and Horticulture | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 362,
"s": 28,
"text": "In the mid 19th century and early 20th century, we saw an increase in poverty during the colonial age. The colonial rules moved unwaged artisans into farming and converted the nation into a province gradually rich in land-living, uneducated labor, and low efficiency. Thus, it made the nation scarce in labor, capital, and knowledge."
},
{
"code": null,
"e": 938,
"s": 362,
"text": "Poverty Alleviation or Relief, or Reduction, is a set of ways, by which governmentsβ policies can intend to permanently lift people out of the poverty line. As per the Global Multidimensional Poverty Index (MPI) 2020, India ranks at 62nd position out of 107 nations with an MPI score of 0.123. Recently a study also revealed that six multidimensionally poor people, five were from lower tribes or castes and according to the Global Hunger Index 2021, with a score of 27.5, India ranks 101st out of the 116 countries, and according to the data, the level of hunger is serious."
},
{
"code": null,
"e": 1181,
"s": 938,
"text": "There are some major reasons for poverty in India, due to less financial support to the lower-income group, over-population, fewer job opportunities, discrimination and casteism of society, lack of education, and huge corruption in society. "
},
{
"code": null,
"e": 1348,
"s": 1181,
"text": "Indiaβs most persuasive task is the removal of poverty and for that the Indian government has taken various programs, schemes, policies based on two main objectives: "
},
{
"code": null,
"e": 1521,
"s": 1348,
"text": "Launching anti-poverty programs to address a specific group of people.Increasing economic growth of the country by providing job opportunities to the lower-income groups. "
},
{
"code": null,
"e": 1592,
"s": 1521,
"text": "Launching anti-poverty programs to address a specific group of people."
},
{
"code": null,
"e": 1695,
"s": 1592,
"text": "Increasing economic growth of the country by providing job opportunities to the lower-income groups. "
},
{
"code": null,
"e": 2393,
"s": 1695,
"text": "After India got its independence, various initiatives were taken to reduce the poverty in India such as in 1950 by Minhas estimating the poverty rates in India, in 1960 a working group was formed to set up a poverty line for India and various others following that. In the first time after post-Independence history, poverty was considered a national issue under the Chairmanship of Indiaβs third prime minister Indira Gandhi. To achieve two main objectives, removal of poverty βGaribi Hataoβ and attainment of self-reliance, D.D. Dhar prepared and launched the 5th Five Years Plan through the better distribution of income, promotion of high growth rate, and significant growth in the rural area."
},
{
"code": null,
"e": 2676,
"s": 2393,
"text": "It was started in the year 1980-81 to create self-employment for the poor people in rural areas. The main aim of IRDP was to decrease the levels of the families in the below poverty line category permanently by providing them revenue-generating resources and access to other inputs."
},
{
"code": null,
"e": 3443,
"s": 2676,
"text": "It was launched on April 1st, 1989, by an amalgamation of the National Rural Employment Program (NREP) and Rural Landless Employment Guarantee Programme (RLEGP) to create employment options and improve the quality of life for the unemployed and under-employed public in rural parts by generating community and social assets and the rural economic infrastructure. The objective of the program was supplementary profitable employment for the unemployed and underemployed people in the rural parts, to create constant employment by strengthening the rural financial structure and assets supporting the poor people in the rural parts for their continuous benefits. In this Yojana, thirty percent of the employment options are held in reserve for females in rural parts. "
},
{
"code": null,
"e": 4033,
"s": 3443,
"text": "The Jawahar Rozgar Yojana was again reformed as Jawahar Gram Samridhi Yojana on 1st April 1999. This scheme on 25th September 2001 was further modified to the Sampoorna Grameen Rozgar Yojana. The objective is to generate demand-driven community village infrastructure that would enable the poor people in the rural parts to increase sustained employment opportunities, durable possessions at the village level. It also includes the creation of additional employment options for the unemployed in the rural parts. The wage employment could be provided to below poverty line (BPL) families. "
},
{
"code": null,
"e": 4709,
"s": 4033,
"text": "It was launched on October 2nd, 1993. It covers drought-prone parts, desert parts, tribal parts, and hill region areas. This scheme during the year 1994-95 was implemented across the nationβs 409 blocks and by April 1997 this scheme was extended to cover all the blocks. The primary objective of this scheme was to generate supplementary wage employment options when there is an acute shortage in manual work during lean agricultural seasons to all able adult poor persons of rural areas who are in need of work at that time, and the secondary objective of this scheme is to generate of financial infrastructure and community assets for employment and growth for rural India."
},
{
"code": null,
"e": 5365,
"s": 4709,
"text": "It was launched in the year 1977-78 by providing food grains as a substitute for wages. This was then restructured with changes implemented in 2001 for the most 150 backward districts of the country to create additional employment for the provisions of lives. The objective is to make available supplementary resources apart from the ones available below the Sampoorna Grameen Rozgar Yojana to the 150 most backward districts of the nation. This program can lead to the creation of additional wage employment opportunities and making available food safety through generating need-based societal, financial, and communal assets in these backward districts."
},
{
"code": null,
"e": 5774,
"s": 5365,
"text": "It was launched in the year 2001 via merging the Jawahar Gram Samridhi Yojana and Employment Assurance scheme by the Ministry of Rural Development. The main aim of the scheme was to provide supplementary wage employment options, provide food safety and improved nutritional stages in all parts, generate durable community social and monetary assets, and infrastructural expansion for the poor in rural areas."
},
{
"code": null,
"e": 5999,
"s": 5774,
"text": "Earlier referred to as Indira Awaas Yojana. The Pradhan Mantri Grameen Awaas Yojana was launched in the year 2015 is created to provide construction of free houses for the rural poor in India who are below the poverty line. "
},
{
"code": null,
"e": 6287,
"s": 5999,
"text": "The objective is the advancement of affordable housing options through the credit-linked subsidy process, restoration of slum dwellers with the involvement of the private sector using the land-dwelling as a resource, reasonable housing in association with government and private subsidy."
},
{
"code": null,
"e": 6737,
"s": 6287,
"text": "It was launched on 15th August 1995 with the objective of secure social security and welfare program to provide support to widows, aged persons, disabled persons, and bereaved those families on the death of the primary breadwinner, belonging to BPL households for the fulfillment of the Article 41 and Article 42 of Directive Principles of State Policy which is mentioned in Part IV of the Constitution of India. It also had three components namely,"
},
{
"code": null,
"e": 7203,
"s": 6737,
"text": "A. National Old Age Pension Scheme (NOAPS): It was launched in the year 1995 to provide pensions to the person who is a βdestituteβ having little or no source of income or monetary support. The main aim is to make available social safety to the eligible beneficiaries. In this, the senior citizens 60 years or above receive a monthly pension and it is a non-contribution person, wherein the beneficiary does not have to contribute any amount to receive the pension."
},
{
"code": null,
"e": 7551,
"s": 7203,
"text": "B. National Family Benefit Scheme (NFBS): It was launched in the year 1995 to support with a lumpsum amount to the household below the poverty line who then becomes the head of the family after the death of the main wage earner. It provides a lumpsum amount of Rs.10,000/- to the household and it is applicable in the age group of 18-64 years. "
},
{
"code": null,
"e": 7866,
"s": 7551,
"text": "C. National Maternity Benefit Scheme (NMBS): In the National Maternity Benefit Scheme, a financial grant is provided to women belonging to poor families for pre-natal and post-natal care. It is for women aged above 19 years and above up to the first two live births. It is a cash-based maternity assistance scheme."
},
{
"code": null,
"e": 8192,
"s": 7866,
"text": "The social clusters are most susceptible to poverty, and they are categorized as SC and ST and in the economic clusters, the most susceptible are the agricultural labor in rural parts and the casual labor in the urban parts. The challenges lie ahead such as the rural and the urban parts showing vast differences in poverty. "
},
{
"code": null,
"e": 8519,
"s": 8192,
"text": "It is true that poverty has been reduced but not up to the intended level. As a citizen or as a government, still we have to focus on the food chain, clothing, population control, free education at the basic level, empowerment of women and fiscally weaker sections of the society, medical facilities, etc. for better results. "
},
{
"code": null,
"e": 8529,
"s": 8519,
"text": "Economics"
},
{
"code": null,
"e": 8534,
"s": 8529,
"text": "UPSC"
},
{
"code": null,
"e": 8632,
"s": 8534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8700,
"s": 8632,
"text": "Role of Micro-Credit in Meeting the Credit Requirements of the Poor"
},
{
"code": null,
"e": 8731,
"s": 8700,
"text": "Types of Expenditure in Budget"
},
{
"code": null,
"e": 8763,
"s": 8731,
"text": "National Population Policy 2000"
},
{
"code": null,
"e": 8811,
"s": 8763,
"text": "Role of Self Help Groups in Poverty Alleviation"
},
{
"code": null,
"e": 8884,
"s": 8811,
"text": "Government Policies to Meet the Challenges of the Food Processing Sector"
},
{
"code": null,
"e": 8941,
"s": 8884,
"text": "Nehruβs Report - Gulf Between Congress and Muslim League"
},
{
"code": null,
"e": 8975,
"s": 8941,
"text": "Types of Receipts of Union Budget"
},
{
"code": null,
"e": 9011,
"s": 8975,
"text": "Important Mountains Passes of India"
},
{
"code": null,
"e": 9051,
"s": 9011,
"text": "Evolution of Concept of Basic Structure"
}
]
|
Teradata - Questions & Answers | Dear readers, these Teradata 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 Teradata. 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 β
Teradata Architecture consists of three components.
Parsing Engine β Parsing Engine receives the query from the user, parses it and prepares the execution plan.
Parsing Engine β Parsing Engine receives the query from the user, parses it and prepares the execution plan.
BYNET β BYNET receives the execution plan from the Parsing Engine and dispatches to the appropriate AMP.
BYNET β BYNET receives the execution plan from the Parsing Engine and dispatches to the appropriate AMP.
AMP β AMP is responsible for storing and retrieving rows. It stores the data in the virtual disk associated with it. In addition to this, AMP is responsible for lock management, space management, sorting and aggregation.
AMP β AMP is responsible for storing and retrieving rows. It stores the data in the virtual disk associated with it. In addition to this, AMP is responsible for lock management, space management, sorting and aggregation.
FastLoad provides restart capability through checkpoints. When the script is restarted from the last checkpoint, it is possible that the same rows may be sent again to the AMPs. Thatβs the reason FastLoad doesnβt support duplicates.
SET table does not allow duplicate records whereas MULTISET allows duplicate records.
For each row inserted, System checks if there is any record with the same row hash. If the table has UPI defined, then it will reject the record as duplicate. Otherwise, it will compare the entire record for duplicate. This will severely affect the system performance.
You can define either Unique Primary Index or Unique Secondary Index to avoid duplicate row checking.
Tables are created using CREATE TABLE statement. Tables can be created using
CREATE TABLE statement with column definition.
CREATE TABLE statement with column definition.
CREATE TABLE from an existing table.
CREATE TABLE from an existing table.
CREATE TABLE statement with a SELECT statement.
CREATE TABLE statement with a SELECT statement.
Duplicate records can be identified using DISTINCT statement or GROUP BY statement.
SELECT DISTINCT column 1, column 2...
FROM tablename;
OR
SELECT column 1, column 2,...
FROM tablename
GROUP BY column 1, column 2....;
Primary keys are not mandatory in Teradata whereas Primary Index is mandatory.
Primary keys are not mandatory in Teradata whereas Primary Index is mandatory.
Data distribution is based on Primary Index value.
Data distribution is based on Primary Index value.
Primary keys doesnβt accept NULLs whereas Primary Index accepts NULL values.
Primary keys doesnβt accept NULLs whereas Primary Index accepts NULL values.
Primary keys are unique whereas Primary Index can be either unique (UPI) or non unique(NUPI).
Primary keys are unique whereas Primary Index can be either unique (UPI) or non unique(NUPI).
Primary keys doesnβt change whereas Primary Indexes change.
Primary keys doesnβt change whereas Primary Indexes change.
Data can be accessed in 3 different ways β
Through Primary Index
Through Secondary Index
Full Table Scan
It can be identified using query SELECT HASHAMP() + 1;
The following query can be used for this purpose.
SELECT HASHMAP(HASHBUCKET(HASHROW(primaryindexvalue))), COUNT(*)
FROM tablename GROUP BY 1;
Teradata supports two transaction modes.
Teradata
ANSI
Teradata mode is set using SET SESSION TRANSACTION BTET; ANSI mode is set using SET SESSION TRANSACTION ANSI;
Transactions can be executed using BT and ET statements.
Join Indexes cannot be directly accessed by the user. Only the optimizer can access them.
The duplicate records will be rejected from loading the target tables and will be inserted into the UV table.
FALLBACK is a protection mechanism used by Teradata to handle AMP failures. For each data row, another copy of the row is stored in a different AMP within a cluster. If any AMP fails, then the corresponding rows will be accessed using FALLBACK AMP.
FALLBACK can be mentioned while table creation using CREATE TABLE statement or after the table is created using ALTER TABLE statement.
Spool space error will happen if the intermediate results of the query exceeds per AMP spool space limit set for the user who submitted the query.
SLEEP command specifies the waiting time before Teradata attempts to establish the connection.
TENACITY command specifies the total waiting time for Teradata to establish a new connection.
You can just keep the BEGIN LOADING and END LOADING statement and submit the FASTLOAD script. Other option is to drop the table and create the table again.
Caching in Teradata works with the source and remains in the same order, that is, it does not change frequently. The Cache is usually shared among applications.
It is an added advantage of using Teradata.
RAID is a protection mechanism to handle disk failure. It stands for Redundant Array of Independent Disks. RAID 1 is commonly used in Teradata.
Secondary index provides alternate path to access the data. They are used to avoid Full Table Scan. However, secondary indexes require additional physical structure for maintaining sub tables and also require additional I/O since the sub table needs to be updated for each row.
There are four different locks in Teradata β Exclusive, Write, Read, and Access.
Locks can be applied at three different levels β Database, Table, and Row.
Using Multi Value Compression (MVC) you can compress up to 255 values including NULLs.
FastLoad loads the data in 64K blocks. There are 2 phases in FastLoad.
In Phase 1, it brings the data in 64K blocks and sends them to the target AMPs. Each AMP will then hash redistribute the rows to their target AMPs.
In Phase 1, it brings the data in 64K blocks and sends them to the target AMPs. Each AMP will then hash redistribute the rows to their target AMPs.
In Phase 2, rows are sorted by their row hash order and written into the target table.
In Phase 2, rows are sorted by their row hash order and written into the target table.
MultiLoad import has five phases.
Phase 1 β Preliminary Phase β Performs basic setup activities.
Phase 1 β Preliminary Phase β Performs basic setup activities.
Phase 2 β DML Transaction Phase β Verifies the syntax of DML statements and brings them to Teradata system.
Phase 2 β DML Transaction Phase β Verifies the syntax of DML statements and brings them to Teradata system.
Phase 3 β Acquisition Phase β Brings the input data into work tables and locks the table.
Phase 3 β Acquisition Phase β Brings the input data into work tables and locks the table.
Phase 4 β Application Phase β Applies all DML operations.
Phase 4 β Application Phase β Applies all DML operations.
Phase 5 β Cleanup Phase β Releases the table lock.
Phase 5 β Cleanup Phase β Releases the table lock.
MULTILOAD DELETE is faster since it deletes the records in blocks. DELETE FROM will delete row by row.
Stored procedure returns one or more values whereas Macros can return one or more rows. In addition to SQL, stored procedure may contain SPL statements.
Both FastLoad and MultiLoad load the data in 64K blocks whereas BTEQ will process one row at a time.
FastExport exports the data in 64K blocks whereas BTEQ exports one row at a time.
Teradata Parallel Transporter (TPT) is the utility to load/export data. It combines all the functionalities of FastLoad, MultiLoad, BTEQ, TPUMP and FastExport.
Permanent journals keeps track of data before or after applying the changes. This help to roll back or roll forward the table to a particular state. Permanent journals can be enabled at table level or database level.
In Teradata, each AMP is associated with a virtual disk. Only the AMP that owns the virtual disk can access the data within that virtual disk. This is called as Shared Nothing Architecture.
If the query uses partitioned columns then it will result in partition elimination, which will greatly improve the performance.
If the query uses partitioned columns then it will result in partition elimination, which will greatly improve the performance.
Partition eliminates other partitions and accesses only the partitions that contain the data.
Partition eliminates other partitions and accesses only the partitions that contain the data.
You can easily drop the old partitions and create new partitions.
You can easily drop the old partitions and create new partitions.
Yes. Secondary index requires sub-tables which require permanent space.
Yes. Whenever partitioned primary index is added, then each row occupies additional 2 or 8 bytes for the partition number.
You can use RANK function on the specified column with descending order with Qualify = 2 condition.
You can check the EXPLAIN plan of the query to identify the steps that consume more spool space and try to optimize the query. Filters can be applied to reduce the number of records being processed or you can split the large query into multiple smaller queries.
When the EXPLAIN command is used against the query, it specifies the confidence of the optimizer to retrieve the records.
There are three confidence levels in Teradata: High Confidence, Medium Confidence, and Low Confidence.
Both NUSI and Full Table Scan (FTS) will access all the AMPs but FTS will access all the blocks within the AMP whereas NUSI will access the blocks only if the sub-table contains the qualifying rows.
In BTEQ mode, SKIP command can be used to skip the records.
BYTEINT. It occupies only one byte and can store values up to +127.
Through Unique Primary Index β 1 AMP
Through Non Unique Primary Index β 1 AMP
Through Unique Secondary Index β 2 AMPs
Through Non Unique Secondary Index β All AMPs
Clique is a protection mechanism to handle Node failures. It is a group of nodes. When a node within a clique fails, then the vprocs (Parsing Engine and AMP) will migrate to other nodes and continue to perform read/write operations on their virtual disks.
Teradata provides different levels of protection mechanism.
Transient Journal β To handle Transaction failure.
Transient Journal β To handle Transaction failure.
Fallback β To handle AMP failure.
Fallback β To handle AMP failure.
Cliques β To handle Node failure.
Cliques β To handle Node failure.
RAID β To handle Disk failure.
RAID β To handle Disk failure.
Hot standby Node β To handle Node failure without affecting performance and restart.
Hot standby Node β To handle Node failure without affecting performance and restart.
ACTIVITYCOUNT gives the number of rows affected by the previous SQL query in BTEQ. If the ACTIVITYCOUNT statement follows an insert statement, it returns the number of rows inserted. If the ACTIVITYCOUNT statement follows select statement, it returns the number of rows selected.
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 :-) | [
{
"code": null,
"e": 3205,
"s": 2764,
"text": "Dear readers, these Teradata 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 Teradata. 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": 3257,
"s": 3205,
"text": "Teradata Architecture consists of three components."
},
{
"code": null,
"e": 3366,
"s": 3257,
"text": "Parsing Engine β Parsing Engine receives the query from the user, parses it and prepares the execution plan."
},
{
"code": null,
"e": 3475,
"s": 3366,
"text": "Parsing Engine β Parsing Engine receives the query from the user, parses it and prepares the execution plan."
},
{
"code": null,
"e": 3580,
"s": 3475,
"text": "BYNET β BYNET receives the execution plan from the Parsing Engine and dispatches to the appropriate AMP."
},
{
"code": null,
"e": 3685,
"s": 3580,
"text": "BYNET β BYNET receives the execution plan from the Parsing Engine and dispatches to the appropriate AMP."
},
{
"code": null,
"e": 3906,
"s": 3685,
"text": "AMP β AMP is responsible for storing and retrieving rows. It stores the data in the virtual disk associated with it. In addition to this, AMP is responsible for lock management, space management, sorting and aggregation."
},
{
"code": null,
"e": 4127,
"s": 3906,
"text": "AMP β AMP is responsible for storing and retrieving rows. It stores the data in the virtual disk associated with it. In addition to this, AMP is responsible for lock management, space management, sorting and aggregation."
},
{
"code": null,
"e": 4360,
"s": 4127,
"text": "FastLoad provides restart capability through checkpoints. When the script is restarted from the last checkpoint, it is possible that the same rows may be sent again to the AMPs. Thatβs the reason FastLoad doesnβt support duplicates."
},
{
"code": null,
"e": 4446,
"s": 4360,
"text": "SET table does not allow duplicate records whereas MULTISET allows duplicate records."
},
{
"code": null,
"e": 4715,
"s": 4446,
"text": "For each row inserted, System checks if there is any record with the same row hash. If the table has UPI defined, then it will reject the record as duplicate. Otherwise, it will compare the entire record for duplicate. This will severely affect the system performance."
},
{
"code": null,
"e": 4817,
"s": 4715,
"text": "You can define either Unique Primary Index or Unique Secondary Index to avoid duplicate row checking."
},
{
"code": null,
"e": 4894,
"s": 4817,
"text": "Tables are created using CREATE TABLE statement. Tables can be created using"
},
{
"code": null,
"e": 4941,
"s": 4894,
"text": "CREATE TABLE statement with column definition."
},
{
"code": null,
"e": 4988,
"s": 4941,
"text": "CREATE TABLE statement with column definition."
},
{
"code": null,
"e": 5025,
"s": 4988,
"text": "CREATE TABLE from an existing table."
},
{
"code": null,
"e": 5062,
"s": 5025,
"text": "CREATE TABLE from an existing table."
},
{
"code": null,
"e": 5110,
"s": 5062,
"text": "CREATE TABLE statement with a SELECT statement."
},
{
"code": null,
"e": 5158,
"s": 5110,
"text": "CREATE TABLE statement with a SELECT statement."
},
{
"code": null,
"e": 5242,
"s": 5158,
"text": "Duplicate records can be identified using DISTINCT statement or GROUP BY statement."
},
{
"code": null,
"e": 5387,
"s": 5242,
"text": "SELECT DISTINCT column 1, column 2... \nFROM tablename;\n \nOR\n \nSELECT column 1, column 2,... \nFROM tablename \nGROUP BY column 1, column 2....;\n"
},
{
"code": null,
"e": 5466,
"s": 5387,
"text": "Primary keys are not mandatory in Teradata whereas Primary Index is mandatory."
},
{
"code": null,
"e": 5545,
"s": 5466,
"text": "Primary keys are not mandatory in Teradata whereas Primary Index is mandatory."
},
{
"code": null,
"e": 5596,
"s": 5545,
"text": "Data distribution is based on Primary Index value."
},
{
"code": null,
"e": 5647,
"s": 5596,
"text": "Data distribution is based on Primary Index value."
},
{
"code": null,
"e": 5724,
"s": 5647,
"text": "Primary keys doesnβt accept NULLs whereas Primary Index accepts NULL values."
},
{
"code": null,
"e": 5801,
"s": 5724,
"text": "Primary keys doesnβt accept NULLs whereas Primary Index accepts NULL values."
},
{
"code": null,
"e": 5895,
"s": 5801,
"text": "Primary keys are unique whereas Primary Index can be either unique (UPI) or non unique(NUPI)."
},
{
"code": null,
"e": 5989,
"s": 5895,
"text": "Primary keys are unique whereas Primary Index can be either unique (UPI) or non unique(NUPI)."
},
{
"code": null,
"e": 6049,
"s": 5989,
"text": "Primary keys doesnβt change whereas Primary Indexes change."
},
{
"code": null,
"e": 6109,
"s": 6049,
"text": "Primary keys doesnβt change whereas Primary Indexes change."
},
{
"code": null,
"e": 6152,
"s": 6109,
"text": "Data can be accessed in 3 different ways β"
},
{
"code": null,
"e": 6174,
"s": 6152,
"text": "Through Primary Index"
},
{
"code": null,
"e": 6198,
"s": 6174,
"text": "Through Secondary Index"
},
{
"code": null,
"e": 6214,
"s": 6198,
"text": "Full Table Scan"
},
{
"code": null,
"e": 6269,
"s": 6214,
"text": "It can be identified using query SELECT HASHAMP() + 1;"
},
{
"code": null,
"e": 6319,
"s": 6269,
"text": "The following query can be used for this purpose."
},
{
"code": null,
"e": 6413,
"s": 6319,
"text": "SELECT HASHMAP(HASHBUCKET(HASHROW(primaryindexvalue))), COUNT(*) \nFROM tablename GROUP BY 1; "
},
{
"code": null,
"e": 6454,
"s": 6413,
"text": "Teradata supports two transaction modes."
},
{
"code": null,
"e": 6463,
"s": 6454,
"text": "Teradata"
},
{
"code": null,
"e": 6468,
"s": 6463,
"text": "ANSI"
},
{
"code": null,
"e": 6578,
"s": 6468,
"text": "Teradata mode is set using SET SESSION TRANSACTION BTET; ANSI mode is set using SET SESSION TRANSACTION ANSI;"
},
{
"code": null,
"e": 6635,
"s": 6578,
"text": "Transactions can be executed using BT and ET statements."
},
{
"code": null,
"e": 6725,
"s": 6635,
"text": "Join Indexes cannot be directly accessed by the user. Only the optimizer can access them."
},
{
"code": null,
"e": 6835,
"s": 6725,
"text": "The duplicate records will be rejected from loading the target tables and will be inserted into the UV table."
},
{
"code": null,
"e": 7084,
"s": 6835,
"text": "FALLBACK is a protection mechanism used by Teradata to handle AMP failures. For each data row, another copy of the row is stored in a different AMP within a cluster. If any AMP fails, then the corresponding rows will be accessed using FALLBACK AMP."
},
{
"code": null,
"e": 7219,
"s": 7084,
"text": "FALLBACK can be mentioned while table creation using CREATE TABLE statement or after the table is created using ALTER TABLE statement."
},
{
"code": null,
"e": 7366,
"s": 7219,
"text": "Spool space error will happen if the intermediate results of the query exceeds per AMP spool space limit set for the user who submitted the query."
},
{
"code": null,
"e": 7461,
"s": 7366,
"text": "SLEEP command specifies the waiting time before Teradata attempts to establish the connection."
},
{
"code": null,
"e": 7555,
"s": 7461,
"text": "TENACITY command specifies the total waiting time for Teradata to establish a new connection."
},
{
"code": null,
"e": 7711,
"s": 7555,
"text": "You can just keep the BEGIN LOADING and END LOADING statement and submit the FASTLOAD script. Other option is to drop the table and create the table again."
},
{
"code": null,
"e": 7916,
"s": 7711,
"text": "Caching in Teradata works with the source and remains in the same order, that is, it does not change frequently. The Cache is usually shared among applications.\nIt is an added advantage of using Teradata."
},
{
"code": null,
"e": 8060,
"s": 7916,
"text": "RAID is a protection mechanism to handle disk failure. It stands for Redundant Array of Independent Disks. RAID 1 is commonly used in Teradata."
},
{
"code": null,
"e": 8338,
"s": 8060,
"text": "Secondary index provides alternate path to access the data. They are used to avoid Full Table Scan. However, secondary indexes require additional physical structure for maintaining sub tables and also require additional I/O since the sub table needs to be updated for each row."
},
{
"code": null,
"e": 8419,
"s": 8338,
"text": "There are four different locks in Teradata β Exclusive, Write, Read, and Access."
},
{
"code": null,
"e": 8494,
"s": 8419,
"text": "Locks can be applied at three different levels β Database, Table, and Row."
},
{
"code": null,
"e": 8581,
"s": 8494,
"text": "Using Multi Value Compression (MVC) you can compress up to 255 values including NULLs."
},
{
"code": null,
"e": 8652,
"s": 8581,
"text": "FastLoad loads the data in 64K blocks. There are 2 phases in FastLoad."
},
{
"code": null,
"e": 8800,
"s": 8652,
"text": "In Phase 1, it brings the data in 64K blocks and sends them to the target AMPs. Each AMP will then hash redistribute the rows to their target AMPs."
},
{
"code": null,
"e": 8948,
"s": 8800,
"text": "In Phase 1, it brings the data in 64K blocks and sends them to the target AMPs. Each AMP will then hash redistribute the rows to their target AMPs."
},
{
"code": null,
"e": 9035,
"s": 8948,
"text": "In Phase 2, rows are sorted by their row hash order and written into the target table."
},
{
"code": null,
"e": 9122,
"s": 9035,
"text": "In Phase 2, rows are sorted by their row hash order and written into the target table."
},
{
"code": null,
"e": 9156,
"s": 9122,
"text": "MultiLoad import has five phases."
},
{
"code": null,
"e": 9219,
"s": 9156,
"text": "Phase 1 β Preliminary Phase β Performs basic setup activities."
},
{
"code": null,
"e": 9282,
"s": 9219,
"text": "Phase 1 β Preliminary Phase β Performs basic setup activities."
},
{
"code": null,
"e": 9390,
"s": 9282,
"text": "Phase 2 β DML Transaction Phase β Verifies the syntax of DML statements and brings them to Teradata system."
},
{
"code": null,
"e": 9498,
"s": 9390,
"text": "Phase 2 β DML Transaction Phase β Verifies the syntax of DML statements and brings them to Teradata system."
},
{
"code": null,
"e": 9588,
"s": 9498,
"text": "Phase 3 β Acquisition Phase β Brings the input data into work tables and locks the table."
},
{
"code": null,
"e": 9678,
"s": 9588,
"text": "Phase 3 β Acquisition Phase β Brings the input data into work tables and locks the table."
},
{
"code": null,
"e": 9736,
"s": 9678,
"text": "Phase 4 β Application Phase β Applies all DML operations."
},
{
"code": null,
"e": 9794,
"s": 9736,
"text": "Phase 4 β Application Phase β Applies all DML operations."
},
{
"code": null,
"e": 9845,
"s": 9794,
"text": "Phase 5 β Cleanup Phase β Releases the table lock."
},
{
"code": null,
"e": 9896,
"s": 9845,
"text": "Phase 5 β Cleanup Phase β Releases the table lock."
},
{
"code": null,
"e": 9999,
"s": 9896,
"text": "MULTILOAD DELETE is faster since it deletes the records in blocks. DELETE FROM will delete row by row."
},
{
"code": null,
"e": 10152,
"s": 9999,
"text": "Stored procedure returns one or more values whereas Macros can return one or more rows. In addition to SQL, stored procedure may contain SPL statements."
},
{
"code": null,
"e": 10253,
"s": 10152,
"text": "Both FastLoad and MultiLoad load the data in 64K blocks whereas BTEQ will process one row at a time."
},
{
"code": null,
"e": 10335,
"s": 10253,
"text": "FastExport exports the data in 64K blocks whereas BTEQ exports one row at a time."
},
{
"code": null,
"e": 10495,
"s": 10335,
"text": "Teradata Parallel Transporter (TPT) is the utility to load/export data. It combines all the functionalities of FastLoad, MultiLoad, BTEQ, TPUMP and FastExport."
},
{
"code": null,
"e": 10712,
"s": 10495,
"text": "Permanent journals keeps track of data before or after applying the changes. This help to roll back or roll forward the table to a particular state. Permanent journals can be enabled at table level or database level."
},
{
"code": null,
"e": 10902,
"s": 10712,
"text": "In Teradata, each AMP is associated with a virtual disk. Only the AMP that owns the virtual disk can access the data within that virtual disk. This is called as Shared Nothing Architecture."
},
{
"code": null,
"e": 11030,
"s": 10902,
"text": "If the query uses partitioned columns then it will result in partition elimination, which will greatly improve the performance."
},
{
"code": null,
"e": 11158,
"s": 11030,
"text": "If the query uses partitioned columns then it will result in partition elimination, which will greatly improve the performance."
},
{
"code": null,
"e": 11252,
"s": 11158,
"text": "Partition eliminates other partitions and accesses only the partitions that contain the data."
},
{
"code": null,
"e": 11346,
"s": 11252,
"text": "Partition eliminates other partitions and accesses only the partitions that contain the data."
},
{
"code": null,
"e": 11412,
"s": 11346,
"text": "You can easily drop the old partitions and create new partitions."
},
{
"code": null,
"e": 11478,
"s": 11412,
"text": "You can easily drop the old partitions and create new partitions."
},
{
"code": null,
"e": 11550,
"s": 11478,
"text": "Yes. Secondary index requires sub-tables which require permanent space."
},
{
"code": null,
"e": 11673,
"s": 11550,
"text": "Yes. Whenever partitioned primary index is added, then each row occupies additional 2 or 8 bytes for the partition number."
},
{
"code": null,
"e": 11773,
"s": 11673,
"text": "You can use RANK function on the specified column with descending order with Qualify = 2 condition."
},
{
"code": null,
"e": 12035,
"s": 11773,
"text": "You can check the EXPLAIN plan of the query to identify the steps that consume more spool space and try to optimize the query. Filters can be applied to reduce the number of records being processed or you can split the large query into multiple smaller queries."
},
{
"code": null,
"e": 12157,
"s": 12035,
"text": "When the EXPLAIN command is used against the query, it specifies the confidence of the optimizer to retrieve the records."
},
{
"code": null,
"e": 12260,
"s": 12157,
"text": "There are three confidence levels in Teradata: High Confidence, Medium Confidence, and Low Confidence."
},
{
"code": null,
"e": 12459,
"s": 12260,
"text": "Both NUSI and Full Table Scan (FTS) will access all the AMPs but FTS will access all the blocks within the AMP whereas NUSI will access the blocks only if the sub-table contains the qualifying rows."
},
{
"code": null,
"e": 12519,
"s": 12459,
"text": "In BTEQ mode, SKIP command can be used to skip the records."
},
{
"code": null,
"e": 12587,
"s": 12519,
"text": "BYTEINT. It occupies only one byte and can store values up to +127."
},
{
"code": null,
"e": 12624,
"s": 12587,
"text": "Through Unique Primary Index β 1 AMP"
},
{
"code": null,
"e": 12665,
"s": 12624,
"text": "Through Non Unique Primary Index β 1 AMP"
},
{
"code": null,
"e": 12705,
"s": 12665,
"text": "Through Unique Secondary Index β 2 AMPs"
},
{
"code": null,
"e": 12751,
"s": 12705,
"text": "Through Non Unique Secondary Index β All AMPs"
},
{
"code": null,
"e": 13007,
"s": 12751,
"text": "Clique is a protection mechanism to handle Node failures. It is a group of nodes. When a node within a clique fails, then the vprocs (Parsing Engine and AMP) will migrate to other nodes and continue to perform read/write operations on their virtual disks."
},
{
"code": null,
"e": 13067,
"s": 13007,
"text": "Teradata provides different levels of protection mechanism."
},
{
"code": null,
"e": 13118,
"s": 13067,
"text": "Transient Journal β To handle Transaction failure."
},
{
"code": null,
"e": 13169,
"s": 13118,
"text": "Transient Journal β To handle Transaction failure."
},
{
"code": null,
"e": 13203,
"s": 13169,
"text": "Fallback β To handle AMP failure."
},
{
"code": null,
"e": 13237,
"s": 13203,
"text": "Fallback β To handle AMP failure."
},
{
"code": null,
"e": 13271,
"s": 13237,
"text": "Cliques β To handle Node failure."
},
{
"code": null,
"e": 13305,
"s": 13271,
"text": "Cliques β To handle Node failure."
},
{
"code": null,
"e": 13336,
"s": 13305,
"text": "RAID β To handle Disk failure."
},
{
"code": null,
"e": 13367,
"s": 13336,
"text": "RAID β To handle Disk failure."
},
{
"code": null,
"e": 13452,
"s": 13367,
"text": "Hot standby Node β To handle Node failure without affecting performance and restart."
},
{
"code": null,
"e": 13537,
"s": 13452,
"text": "Hot standby Node β To handle Node failure without affecting performance and restart."
},
{
"code": null,
"e": 13817,
"s": 13537,
"text": "ACTIVITYCOUNT gives the number of rows affected by the previous SQL query in BTEQ. If the ACTIVITYCOUNT statement follows an insert statement, it returns the number of rows inserted. If the ACTIVITYCOUNT statement follows select statement, it returns the number of rows selected."
},
{
"code": null,
"e": 14104,
"s": 13817,
"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."
}
]
|
SQL Query to Create Table With a Primary Key | 13 Sep, 2021
A primary key uniquely identifies each row table. It must contain unique and non-NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called composite keys.
To create a Primary key in the table, we have to use a keyword; βPRIMARY KEY ( )β
Query:
CREATE TABLE `Employee` ( `Emp_ID` VARCHAR(20) NOT NULL ,`Name` VARCHAR(50) NOT NULL ,
`Age` INT NOT NULL ,`Phone_No` VARCHAR(10) NOT NULL ,`Address` VARCHAR(100) NOT NULL ,
PRIMARY KEY (`Emp_ID`));
To view whether βEmp_IDβ is the primary key or not we use Describe command to view the structure of the Table.
DESCRIBE is used to describe something. Since in database we have tables, thatβs why we use DESCRIBE or DESC(both are same) command to describe the structure of a table.
Query:
DESCRIBE Employee;
Or
DESC Employee;
Output:
Now, to create a PRIMARY KEY constraint on any column when the table already exists (NO EARLIER PRIMARY KEY DEFINED), use the following SQL Syntax:
ALTER TABLE [Table_Name] ADD PRIMARY KEY (ID);
Query:
ALTER TABLE Employee ADD PRIMARY KEY (Phone_No);
Output:
If any earlier primary key is defined, then there will be errors like;
Output:
This error is because; Only one primary key can exist. So, we have to first delete the initial PRIMARY KEY to create a new PRIMARY KEY.
1. To create PRIMARY KEY on multiple columns:
Query:
CREATE TABLE `Employee` ( `Emp_ID` VARCHAR(20) NOT NULL ,
`Name` VARCHAR(50) NOT NULL ,
`Age` INT NOT NULL ,
`Phone_No` VARCHAR(10) NOT NULL ,
`Address` VARCHAR(100) NOT NULL ,
PRIMARY KEY (`Emp_ID`,`Name`));
Output:
2. Add Multiple Primary Keys when Table already existing
Query:
ALTER TABLE Employee
ADD CONSTRAINT PK_CUSTID PRIMARY KEY (Emp_ID, NAME);
DESC Employee;
Output:
Blogathon-2021
Picked
SQL-Query
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 289,
"s": 28,
"text": "A primary key uniquely identifies each row table. It must contain unique and non-NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called composite keys."
},
{
"code": null,
"e": 371,
"s": 289,
"text": "To create a Primary key in the table, we have to use a keyword; βPRIMARY KEY ( )β"
},
{
"code": null,
"e": 378,
"s": 371,
"text": "Query:"
},
{
"code": null,
"e": 580,
"s": 378,
"text": "CREATE TABLE `Employee` ( `Emp_ID` VARCHAR(20) NOT NULL ,`Name` VARCHAR(50) NOT NULL , \n`Age` INT NOT NULL ,`Phone_No` VARCHAR(10) NOT NULL ,`Address` VARCHAR(100) NOT NULL ,\n PRIMARY KEY (`Emp_ID`));"
},
{
"code": null,
"e": 691,
"s": 580,
"text": "To view whether βEmp_IDβ is the primary key or not we use Describe command to view the structure of the Table."
},
{
"code": null,
"e": 861,
"s": 691,
"text": "DESCRIBE is used to describe something. Since in database we have tables, thatβs why we use DESCRIBE or DESC(both are same) command to describe the structure of a table."
},
{
"code": null,
"e": 868,
"s": 861,
"text": "Query:"
},
{
"code": null,
"e": 906,
"s": 868,
"text": "DESCRIBE Employee;\nOr \nDESC Employee;"
},
{
"code": null,
"e": 914,
"s": 906,
"text": "Output:"
},
{
"code": null,
"e": 1062,
"s": 914,
"text": "Now, to create a PRIMARY KEY constraint on any column when the table already exists (NO EARLIER PRIMARY KEY DEFINED), use the following SQL Syntax:"
},
{
"code": null,
"e": 1109,
"s": 1062,
"text": "ALTER TABLE [Table_Name] ADD PRIMARY KEY (ID);"
},
{
"code": null,
"e": 1116,
"s": 1109,
"text": "Query:"
},
{
"code": null,
"e": 1165,
"s": 1116,
"text": "ALTER TABLE Employee ADD PRIMARY KEY (Phone_No);"
},
{
"code": null,
"e": 1173,
"s": 1165,
"text": "Output:"
},
{
"code": null,
"e": 1244,
"s": 1173,
"text": "If any earlier primary key is defined, then there will be errors like;"
},
{
"code": null,
"e": 1252,
"s": 1244,
"text": "Output:"
},
{
"code": null,
"e": 1388,
"s": 1252,
"text": "This error is because; Only one primary key can exist. So, we have to first delete the initial PRIMARY KEY to create a new PRIMARY KEY."
},
{
"code": null,
"e": 1436,
"s": 1390,
"text": "1. To create PRIMARY KEY on multiple columns:"
},
{
"code": null,
"e": 1443,
"s": 1436,
"text": "Query:"
},
{
"code": null,
"e": 1766,
"s": 1443,
"text": "CREATE TABLE `Employee` ( `Emp_ID` VARCHAR(20) NOT NULL ,\n `Name` VARCHAR(50) NOT NULL , \n `Age` INT NOT NULL , \n `Phone_No` VARCHAR(10) NOT NULL ,\n `Address` VARCHAR(100) NOT NULL ,\n PRIMARY KEY (`Emp_ID`,`Name`));"
},
{
"code": null,
"e": 1774,
"s": 1766,
"text": "Output:"
},
{
"code": null,
"e": 1831,
"s": 1774,
"text": "2. Add Multiple Primary Keys when Table already existing"
},
{
"code": null,
"e": 1838,
"s": 1831,
"text": "Query:"
},
{
"code": null,
"e": 1929,
"s": 1838,
"text": "ALTER TABLE Employee\n ADD CONSTRAINT PK_CUSTID PRIMARY KEY (Emp_ID, NAME);\n DESC Employee;"
},
{
"code": null,
"e": 1937,
"s": 1929,
"text": "Output:"
},
{
"code": null,
"e": 1952,
"s": 1937,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 1959,
"s": 1952,
"text": "Picked"
},
{
"code": null,
"e": 1969,
"s": 1959,
"text": "SQL-Query"
},
{
"code": null,
"e": 1979,
"s": 1969,
"text": "Blogathon"
},
{
"code": null,
"e": 1983,
"s": 1979,
"text": "SQL"
},
{
"code": null,
"e": 1987,
"s": 1983,
"text": "SQL"
},
{
"code": null,
"e": 2085,
"s": 1987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2126,
"s": 2085,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 2164,
"s": 2126,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 2208,
"s": 2164,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 2268,
"s": 2208,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 2335,
"s": 2268,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 2377,
"s": 2335,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 2424,
"s": 2377,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 2442,
"s": 2424,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 2486,
"s": 2442,
"text": "How to find Nth highest salary from a table"
}
]
|
chown command in Linux with Examples | 24 Feb, 2022
Different users in the operating system have ownership and permission to ensure that the files are secure and put restrictions on who can modify the contents of the files. In Linux there are different users who use the system:
Each user has some properties associated with them, such as a user ID and a home directory. We can add users into a group to make the process of managing users easier.
A group can have zero or more users. A specified user can be associated with a βdefault groupβ. It can also be a member of other groups on the system as well.
Ownership and Permissions: To protect and secure files and directory in Linux we use permissions to control what a user can do with a file or directory. Linux uses three types of permissions:
Read: This permission allows the user to read files and in directories, it lets the user read directories and subdirectories stores in it.
Write: This permission allows a user to modify and delete a file. Also it allows a user to modify its contents (create, delete and rename files in it) for the directories. Unless the execute permission is not given to directories changes does do affect them.
Execute: This permission on a file allows it to get executed. For example, if we have a file named php.sh so unless we donβt give it execute permission it wonβt run.
Types of file Permissions:
User: These type of file permission affect the owner of the file.
Group: These type of file permission affect the group which owns the file. Instead of the group permissions, the user permissions will apply if the owner user is in this group.
Other: These type of file permission affect all other users on the system.
Note: To view the permissions we use:
ls -l
chown command is used to change the file Owner or group. Whenever you want to change ownership you can use chown command.
Syntax:
chown [OPTION]... [OWNER][:[GROUP]] FILE...
chown [OPTION]... βreference=RFILE FILE...
Example: To change owner of the file:
chown owner_name file_name
In our case we have files as follows:
Now if I use file1.txt in my case, to change ownership I will use the following syntax:
chown master file1.txt
where the master is another user in the system. Assume that if you are user named user1 and you want to change ownership to root (where your current directory is user1). use βsudoβ before syntax.
sudo chown root file1.txt
Options:
-c: Reports when a file change is made. Example:
Example:
chown -c master file1.txt
-v: It is used to show the verbose information for every file processed. Example:
Example:
chown -v master file1.txt
-f: It suppresses most of the error messages. When you are not permitted to change group permissions and shows error, this option forcefully/silently changes the ownership.
Examples:
To Change group ownership In our case I am using group1 as a group in the system. To change ownership we will use
chown :group1 file1.txt
You can see that the group permissions changed to group1 from root, if you use -v option it will report that. We just need to add a β:β to change group.
To change the owner as well as group: Again taking master as user and group1 as a group in the system
chown master:group1 greek1
Here, greek1 is a file.
To change the owner from particular ownership only: Suppose we want to change ownership from master to root where current owner must be master only.
chown --from=master root greek1
To change group from a particular group:
chown --from=:group1 root greek1
Here, the group of greek1 is changed to root.
To copy ownership of one file to another:
chown --reference=greek1 greek2
To change ownership of multiple files:
chown master:group greek2 greek3
sooda367
nishuchandravanshi
linux-command
Linux-directory-commands
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 283,
"s": 54,
"text": "Different users in the operating system have ownership and permission to ensure that the files are secure and put restrictions on who can modify the contents of the files. In Linux there are different users who use the system: "
},
{
"code": null,
"e": 451,
"s": 283,
"text": "Each user has some properties associated with them, such as a user ID and a home directory. We can add users into a group to make the process of managing users easier."
},
{
"code": null,
"e": 610,
"s": 451,
"text": "A group can have zero or more users. A specified user can be associated with a βdefault groupβ. It can also be a member of other groups on the system as well."
},
{
"code": null,
"e": 804,
"s": 610,
"text": "Ownership and Permissions: To protect and secure files and directory in Linux we use permissions to control what a user can do with a file or directory. Linux uses three types of permissions: "
},
{
"code": null,
"e": 943,
"s": 804,
"text": "Read: This permission allows the user to read files and in directories, it lets the user read directories and subdirectories stores in it."
},
{
"code": null,
"e": 1202,
"s": 943,
"text": "Write: This permission allows a user to modify and delete a file. Also it allows a user to modify its contents (create, delete and rename files in it) for the directories. Unless the execute permission is not given to directories changes does do affect them."
},
{
"code": null,
"e": 1368,
"s": 1202,
"text": "Execute: This permission on a file allows it to get executed. For example, if we have a file named php.sh so unless we donβt give it execute permission it wonβt run."
},
{
"code": null,
"e": 1397,
"s": 1368,
"text": "Types of file Permissions: "
},
{
"code": null,
"e": 1463,
"s": 1397,
"text": "User: These type of file permission affect the owner of the file."
},
{
"code": null,
"e": 1640,
"s": 1463,
"text": "Group: These type of file permission affect the group which owns the file. Instead of the group permissions, the user permissions will apply if the owner user is in this group."
},
{
"code": null,
"e": 1715,
"s": 1640,
"text": "Other: These type of file permission affect all other users on the system."
},
{
"code": null,
"e": 1755,
"s": 1715,
"text": "Note: To view the permissions we use: "
},
{
"code": null,
"e": 1763,
"s": 1755,
"text": "ls -l "
},
{
"code": null,
"e": 1886,
"s": 1763,
"text": "chown command is used to change the file Owner or group. Whenever you want to change ownership you can use chown command. "
},
{
"code": null,
"e": 1896,
"s": 1886,
"text": "Syntax: "
},
{
"code": null,
"e": 1983,
"s": 1896,
"text": "chown [OPTION]... [OWNER][:[GROUP]] FILE...\nchown [OPTION]... βreference=RFILE FILE..."
},
{
"code": null,
"e": 2022,
"s": 1983,
"text": "Example: To change owner of the file: "
},
{
"code": null,
"e": 2049,
"s": 2022,
"text": "chown owner_name file_name"
},
{
"code": null,
"e": 2088,
"s": 2049,
"text": "In our case we have files as follows: "
},
{
"code": null,
"e": 2177,
"s": 2088,
"text": "Now if I use file1.txt in my case, to change ownership I will use the following syntax: "
},
{
"code": null,
"e": 2200,
"s": 2177,
"text": "chown master file1.txt"
},
{
"code": null,
"e": 2398,
"s": 2200,
"text": "where the master is another user in the system. Assume that if you are user named user1 and you want to change ownership to root (where your current directory is user1). use βsudoβ before syntax. "
},
{
"code": null,
"e": 2424,
"s": 2398,
"text": "sudo chown root file1.txt"
},
{
"code": null,
"e": 2434,
"s": 2424,
"text": "Options: "
},
{
"code": null,
"e": 2484,
"s": 2434,
"text": "-c: Reports when a file change is made. Example: "
},
{
"code": null,
"e": 2494,
"s": 2484,
"text": "Example: "
},
{
"code": null,
"e": 2520,
"s": 2494,
"text": "chown -c master file1.txt"
},
{
"code": null,
"e": 2602,
"s": 2520,
"text": "-v: It is used to show the verbose information for every file processed. Example:"
},
{
"code": null,
"e": 2611,
"s": 2602,
"text": "Example:"
},
{
"code": null,
"e": 2637,
"s": 2611,
"text": "chown -v master file1.txt"
},
{
"code": null,
"e": 2810,
"s": 2637,
"text": "-f: It suppresses most of the error messages. When you are not permitted to change group permissions and shows error, this option forcefully/silently changes the ownership."
},
{
"code": null,
"e": 2822,
"s": 2810,
"text": "Examples: "
},
{
"code": null,
"e": 2936,
"s": 2822,
"text": "To Change group ownership In our case I am using group1 as a group in the system. To change ownership we will use"
},
{
"code": null,
"e": 2960,
"s": 2936,
"text": "chown :group1 file1.txt"
},
{
"code": null,
"e": 3113,
"s": 2960,
"text": "You can see that the group permissions changed to group1 from root, if you use -v option it will report that. We just need to add a β:β to change group."
},
{
"code": null,
"e": 3215,
"s": 3113,
"text": "To change the owner as well as group: Again taking master as user and group1 as a group in the system"
},
{
"code": null,
"e": 3242,
"s": 3215,
"text": "chown master:group1 greek1"
},
{
"code": null,
"e": 3267,
"s": 3242,
"text": "Here, greek1 is a file. "
},
{
"code": null,
"e": 3416,
"s": 3267,
"text": "To change the owner from particular ownership only: Suppose we want to change ownership from master to root where current owner must be master only."
},
{
"code": null,
"e": 3448,
"s": 3416,
"text": "chown --from=master root greek1"
},
{
"code": null,
"e": 3489,
"s": 3448,
"text": "To change group from a particular group:"
},
{
"code": null,
"e": 3522,
"s": 3489,
"text": "chown --from=:group1 root greek1"
},
{
"code": null,
"e": 3568,
"s": 3522,
"text": "Here, the group of greek1 is changed to root."
},
{
"code": null,
"e": 3610,
"s": 3568,
"text": "To copy ownership of one file to another:"
},
{
"code": null,
"e": 3642,
"s": 3610,
"text": "chown --reference=greek1 greek2"
},
{
"code": null,
"e": 3681,
"s": 3642,
"text": "To change ownership of multiple files:"
},
{
"code": null,
"e": 3715,
"s": 3681,
"text": "chown master:group greek2 greek3 "
},
{
"code": null,
"e": 3724,
"s": 3715,
"text": "sooda367"
},
{
"code": null,
"e": 3743,
"s": 3724,
"text": "nishuchandravanshi"
},
{
"code": null,
"e": 3757,
"s": 3743,
"text": "linux-command"
},
{
"code": null,
"e": 3782,
"s": 3757,
"text": "Linux-directory-commands"
},
{
"code": null,
"e": 3802,
"s": 3782,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 3809,
"s": 3802,
"text": "Picked"
},
{
"code": null,
"e": 3820,
"s": 3809,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3918,
"s": 3820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3953,
"s": 3918,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3986,
"s": 3953,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 4024,
"s": 3986,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 4060,
"s": 4024,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 4098,
"s": 4060,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 4124,
"s": 4098,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 4159,
"s": 4124,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 4194,
"s": 4159,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 4230,
"s": 4194,
"text": "echo command in Linux with Examples"
}
]
|
LinkedHashMap and LinkedHashSet in Java | 16 Sep, 2021
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order.
Example:
Java
// Java program to demonstrate// working of LinkedHashMapimport java.util.*; class LinkedHashMapExample { public static void main(String args[]) { // create an instance of LinkedHashMap LinkedHashMap<Integer, String> lhm; lhm = new LinkedHashMap<Integer, String>(); // insert element in LinkedHashMap lhm.put(100, "Amit"); // insert first null key lhm.put(null, "Ajay"); lhm.put(101, "Vijay"); lhm.put(102, "Rahul"); // insert second null key // which replace first null key value lhm.put(null, "Anuj"); // insert duplicate // which replace first 102 key value lhm.put(102, "Saurav"); // iterate and print the key/value pairs lhm.entrySet().stream().forEach((m) -> { System.out.println(m.getKey() + " " + m.getValue()); }); }}
100 Amit
null Anuj
101 Vijay
102 Saurav
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.
Example:
Java
// Java program to demonstrate// working of LinkedHashSetimport java.util.*; class LinkedHashSetExample { public static void main(String args[]) { // create an instance of LinkedHashSet LinkedHashSet<String> lhs = new LinkedHashSet<String>(); // insert element in LinkedHashMap lhs.add("Amit"); // insert first null key lhs.add(null); lhs.add("Vijay"); lhs.add("Rahul"); // insert second null key // which replace first null key value lhs.add(null); // insert duplicate lhs.add("Vijay"); // create an iterator // iterate and print the elements Iterator<String> itr = lhs.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}
Amit
null
Vijay
Rahul
The Hierarchy of LinkedHashMap and LinkedHashSet
Property
LinkedHashMap and LinkedHashSet
Property
LinkedHashMap
LinkedHashSet
The default constructor declaration is :
LinkedHashMap lhm = new LinkedHashMap();
The default constructor declaration is :
LinkedHashSet hs = new LinkedHashSet();
The LinkedHashMap accepts five types of constructors:
LinkedHashMap()
LinkedHashMap(int initialCapacity)
LinkedHashMap(int initialCapacity, float fillRatio)
LinkedHashMap(int initialCapacity, float fillRatio, boolean Order)
LinkedHashMapβ(Map<? extends K,β? extends V> m)
The LinkedHashSet accepts four types of constructors:
LinkedHashSet()
LinkedHashSet(Collection<? extends E> C)
LinkedHashSet(int initialCapacity)
LinkedHashSet(int initialCapacity, float fillRatio)
Ganeshchowdharysadanala
sweetyty
Java-LinkedHashMap
java-LinkedHashSet
Technical Scripter 2018
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 396,
"s": 52,
"text": "The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. "
},
{
"code": null,
"e": 405,
"s": 396,
"text": "Example:"
},
{
"code": null,
"e": 410,
"s": 405,
"text": "Java"
},
{
"code": "// Java program to demonstrate// working of LinkedHashMapimport java.util.*; class LinkedHashMapExample { public static void main(String args[]) { // create an instance of LinkedHashMap LinkedHashMap<Integer, String> lhm; lhm = new LinkedHashMap<Integer, String>(); // insert element in LinkedHashMap lhm.put(100, \"Amit\"); // insert first null key lhm.put(null, \"Ajay\"); lhm.put(101, \"Vijay\"); lhm.put(102, \"Rahul\"); // insert second null key // which replace first null key value lhm.put(null, \"Anuj\"); // insert duplicate // which replace first 102 key value lhm.put(102, \"Saurav\"); // iterate and print the key/value pairs lhm.entrySet().stream().forEach((m) -> { System.out.println(m.getKey() + \" \" + m.getValue()); }); }}",
"e": 1320,
"s": 410,
"text": null
},
{
"code": null,
"e": 1363,
"s": 1323,
"text": "100 Amit\nnull Anuj\n101 Vijay\n102 Saurav"
},
{
"code": null,
"e": 1833,
"s": 1365,
"text": "The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted."
},
{
"code": null,
"e": 1844,
"s": 1835,
"text": "Example:"
},
{
"code": null,
"e": 1851,
"s": 1846,
"text": "Java"
},
{
"code": "// Java program to demonstrate// working of LinkedHashSetimport java.util.*; class LinkedHashSetExample { public static void main(String args[]) { // create an instance of LinkedHashSet LinkedHashSet<String> lhs = new LinkedHashSet<String>(); // insert element in LinkedHashMap lhs.add(\"Amit\"); // insert first null key lhs.add(null); lhs.add(\"Vijay\"); lhs.add(\"Rahul\"); // insert second null key // which replace first null key value lhs.add(null); // insert duplicate lhs.add(\"Vijay\"); // create an iterator // iterate and print the elements Iterator<String> itr = lhs.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}",
"e": 2657,
"s": 1851,
"text": null
},
{
"code": null,
"e": 2682,
"s": 2660,
"text": "Amit\nnull\nVijay\nRahul"
},
{
"code": null,
"e": 2734,
"s": 2684,
"text": "The Hierarchy of LinkedHashMap and LinkedHashSet "
},
{
"code": null,
"e": 2745,
"s": 2736,
"text": "Property"
},
{
"code": null,
"e": 2777,
"s": 2745,
"text": "LinkedHashMap and LinkedHashSet"
},
{
"code": null,
"e": 2786,
"s": 2777,
"text": "Property"
},
{
"code": null,
"e": 2800,
"s": 2786,
"text": "LinkedHashMap"
},
{
"code": null,
"e": 2814,
"s": 2800,
"text": "LinkedHashSet"
},
{
"code": null,
"e": 2855,
"s": 2814,
"text": "The default constructor declaration is :"
},
{
"code": null,
"e": 2896,
"s": 2855,
"text": "LinkedHashMap lhm = new LinkedHashMap();"
},
{
"code": null,
"e": 2937,
"s": 2896,
"text": "The default constructor declaration is :"
},
{
"code": null,
"e": 2977,
"s": 2937,
"text": "LinkedHashSet hs = new LinkedHashSet();"
},
{
"code": null,
"e": 3031,
"s": 2977,
"text": "The LinkedHashMap accepts five types of constructors:"
},
{
"code": null,
"e": 3047,
"s": 3031,
"text": "LinkedHashMap()"
},
{
"code": null,
"e": 3082,
"s": 3047,
"text": "LinkedHashMap(int initialCapacity)"
},
{
"code": null,
"e": 3134,
"s": 3082,
"text": "LinkedHashMap(int initialCapacity, float fillRatio)"
},
{
"code": null,
"e": 3201,
"s": 3134,
"text": "LinkedHashMap(int initialCapacity, float fillRatio, boolean Order)"
},
{
"code": null,
"e": 3249,
"s": 3201,
"text": "LinkedHashMapβ(Map<? extends K,β? extends V> m)"
},
{
"code": null,
"e": 3303,
"s": 3249,
"text": "The LinkedHashSet accepts four types of constructors:"
},
{
"code": null,
"e": 3319,
"s": 3303,
"text": "LinkedHashSet()"
},
{
"code": null,
"e": 3360,
"s": 3319,
"text": "LinkedHashSet(Collection<? extends E> C)"
},
{
"code": null,
"e": 3395,
"s": 3360,
"text": "LinkedHashSet(int initialCapacity)"
},
{
"code": null,
"e": 3447,
"s": 3395,
"text": "LinkedHashSet(int initialCapacity, float fillRatio)"
},
{
"code": null,
"e": 3473,
"s": 3449,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 3482,
"s": 3473,
"text": "sweetyty"
},
{
"code": null,
"e": 3501,
"s": 3482,
"text": "Java-LinkedHashMap"
},
{
"code": null,
"e": 3520,
"s": 3501,
"text": "java-LinkedHashSet"
},
{
"code": null,
"e": 3544,
"s": 3520,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3563,
"s": 3544,
"text": "Difference Between"
},
{
"code": null,
"e": 3568,
"s": 3563,
"text": "Java"
},
{
"code": null,
"e": 3587,
"s": 3568,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3592,
"s": 3587,
"text": "Java"
}
]
|
Java.io.Reader class in Java | 30 Jan, 2017
It is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.Constructors:
protected Reader() : Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
protected Reader(Object lock) : Creates a new character-stream reader whose critical sections will synchronize on the given object.
Methods:
abstract void close() : Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.Syntax :public abstract void close()
throws IOException
Throws:
IOException
Syntax :public abstract void close()
throws IOException
Throws:
IOException
void mark(int readAheadLimit) : Marks the present position in the stream.Subsequent calls to reset() will attempt to reposition the stream to this point. Not all character-input streams support the mark() operation.Syntax :public void mark(int readAheadLimit)
throws IOException
Parameters:
readAheadLimit - Limit on the number of characters that may be read
while still preserving the mark. After reading this many characters,
attempting to reset the stream may fail.
Throws:
IOException
Syntax :public void mark(int readAheadLimit)
throws IOException
Parameters:
readAheadLimit - Limit on the number of characters that may be read
while still preserving the mark. After reading this many characters,
attempting to reset the stream may fail.
Throws:
IOException
boolean markSupported() : Tells whether this stream supports the mark() operation.The default implementation always returns false. Subclasses should override this method.Syntax :public boolean markSupported()
Returns:
true if and only if this stream supports the mark operation.
Syntax :public boolean markSupported()
Returns:
true if and only if this stream supports the mark operation.
int read() : Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.Subclasses that intend to support efficient single-character input should override this method.Syntax :public int read()
throws IOException
Returns:
The character read, as an integer in the range 0 to 65535 (0x00-0xffff),
or -1 if the end of the stream has been reached
Throws:
IOException
Syntax :public int read()
throws IOException
Returns:
The character read, as an integer in the range 0 to 65535 (0x00-0xffff),
or -1 if the end of the stream has been reached
Throws:
IOException
int read(char[] cbuf) : Reads characters into an array.This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.Syntax :public int read(char[] cbuf)
throws IOException
Parameters:
cbuf - Destination buffer
Returns:
The number of characters read, or -1 if the end of the stream has been reached
Throws:
IOException
Syntax :public int read(char[] cbuf)
throws IOException
Parameters:
cbuf - Destination buffer
Returns:
The number of characters read, or -1 if the end of the stream has been reached
Throws:
IOException
abstract int read(char[] cbuf, int off, int len) : Reads characters into a portion of an array.This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.Syntax :public abstract int read(char[] cbuf,
int off,
int len)
throws IOException
Parameters:
cbuf - Destination buffer
off - Offset at which to start storing characters
len - Maximum number of characters to read
Returns:
The number of characters read, or -1 if the end of the stream has been reached
Throws:
IOException
Syntax :public abstract int read(char[] cbuf,
int off,
int len)
throws IOException
Parameters:
cbuf - Destination buffer
off - Offset at which to start storing characters
len - Maximum number of characters to read
Returns:
The number of characters read, or -1 if the end of the stream has been reached
Throws:
IOException
int read(CharBuffer target) : Attempts to read characters into the specified character buffer.The buffer is used as a repository of characters as-is: the only changes made are the results of a put operation. No flipping or rewinding of the buffer is performed.Syntax :public int read(CharBuffer target)
throws IOException
Parameters:
target - the buffer to read characters into
Returns:
The number of characters added to the buffer,
or -1 if this source of characters is at its end
Throws:
IOException
NullPointerException
ReadOnlyBufferException
Syntax :public int read(CharBuffer target)
throws IOException
Parameters:
target - the buffer to read characters into
Returns:
The number of characters added to the buffer,
or -1 if this source of characters is at its end
Throws:
IOException
NullPointerException
ReadOnlyBufferException
boolean ready() : Tells whether this stream is ready to be read.Syntax :public boolean ready()
throws IOException
Returns:
True if the next read() is guaranteed not to block for input, false otherwise.
Note that returning false does not guarantee that the next read will block.
Throws:
IOException
Syntax :public boolean ready()
throws IOException
Returns:
True if the next read() is guaranteed not to block for input, false otherwise.
Note that returning false does not guarantee that the next read will block.
Throws:
IOException
void reset() : Resets the stream. If the stream has been marked, then attempt to reposition it at the mark. If the stream has not been marked, then attempt to reset it in some way appropriate to the particular stream, for example by repositioning it to its starting point. Not all character-input streams support the reset() operation, and some support reset() without supporting mark().Syntax :public void reset()
throws IOException
Throws:
IOException
Syntax :public void reset()
throws IOException
Throws:
IOException
long skip(long n) : Skips characters.This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached.Syntax :public long skip(long n)
throws IOException
Parameters:
n - The number of characters to skip
Returns:
The number of characters actually skipped
Throws:
IllegalArgumentException - If n is negative.
IOException
Syntax :public long skip(long n)
throws IOException
Parameters:
n - The number of characters to skip
Returns:
The number of characters actually skipped
Throws:
IllegalArgumentException - If n is negative.
IOException
//Java program demonstrating Reader methodsimport java.io.*;import java.nio.CharBuffer;import java.util.Arrays;class ReaderDemo{ public static void main(String[] args) throws IOException { Reader r = new FileReader("file.txt"); PrintStream out = System.out; char c[] = new char[10]; CharBuffer cf = CharBuffer.wrap(c); //illustrating markSupported() if(r.markSupported()) { //illustrating mark() r.mark(100); out.println("mark method is supported"); } //skipping 5 characters r.skip(5); //checking whether this stream is ready to be read. if(r.ready()) { //illustrating read(char[] cbuf,int off,int len) r.read(c,0,10); out.println(Arrays.toString(c)); //illustrating read(CharBuffer target ) r.read(cf); out.println(Arrays.toString(cf.array())); //illustrating read() out.println((char)r.read()); } //closing the stream r.close(); }}
Output :
[f, g, h, i, g, k, l, m, n, o]
[p, q, r, s, t, u, v, w, x, y]
z
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jan, 2017"
},
{
"code": null,
"e": 355,
"s": 52,
"text": "It is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.Constructors:"
},
{
"code": null,
"e": 477,
"s": 355,
"text": "protected Reader() : Creates a new character-stream reader whose critical sections will synchronize on the reader itself."
},
{
"code": null,
"e": 609,
"s": 477,
"text": "protected Reader(Object lock) : Creates a new character-stream reader whose critical sections will synchronize on the given object."
},
{
"code": null,
"e": 618,
"s": 609,
"text": "Methods:"
},
{
"code": null,
"e": 984,
"s": 618,
"text": "abstract void close() : Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.Syntax :public abstract void close()\n throws IOException\nThrows:\nIOException "
},
{
"code": null,
"e": 1081,
"s": 984,
"text": "Syntax :public abstract void close()\n throws IOException\nThrows:\nIOException "
},
{
"code": null,
"e": 1582,
"s": 1081,
"text": "void mark(int readAheadLimit) : Marks the present position in the stream.Subsequent calls to reset() will attempt to reposition the stream to this point. Not all character-input streams support the mark() operation.Syntax :public void mark(int readAheadLimit)\n throws IOException\nParameters:\nreadAheadLimit - Limit on the number of characters that may be read\nwhile still preserving the mark. After reading this many characters, \nattempting to reset the stream may fail.\nThrows:\nIOException "
},
{
"code": null,
"e": 1868,
"s": 1582,
"text": "Syntax :public void mark(int readAheadLimit)\n throws IOException\nParameters:\nreadAheadLimit - Limit on the number of characters that may be read\nwhile still preserving the mark. After reading this many characters, \nattempting to reset the stream may fail.\nThrows:\nIOException "
},
{
"code": null,
"e": 2147,
"s": 1868,
"text": "boolean markSupported() : Tells whether this stream supports the mark() operation.The default implementation always returns false. Subclasses should override this method.Syntax :public boolean markSupported()\nReturns:\ntrue if and only if this stream supports the mark operation."
},
{
"code": null,
"e": 2256,
"s": 2147,
"text": "Syntax :public boolean markSupported()\nReturns:\ntrue if and only if this stream supports the mark operation."
},
{
"code": null,
"e": 2708,
"s": 2256,
"text": "int read() : Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.Subclasses that intend to support efficient single-character input should override this method.Syntax :public int read()\n throws IOException\nReturns:\nThe character read, as an integer in the range 0 to 65535 (0x00-0xffff), \nor -1 if the end of the stream has been reached\nThrows:\nIOException "
},
{
"code": null,
"e": 2914,
"s": 2708,
"text": "Syntax :public int read()\n throws IOException\nReturns:\nThe character read, as an integer in the range 0 to 65535 (0x00-0xffff), \nor -1 if the end of the stream has been reached\nThrows:\nIOException "
},
{
"code": null,
"e": 3292,
"s": 2914,
"text": "int read(char[] cbuf) : Reads characters into an array.This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.Syntax :public int read(char[] cbuf)\n throws IOException\nParameters:\ncbuf - Destination buffer\nReturns:\nThe number of characters read, or -1 if the end of the stream has been reached\nThrows:\nIOException "
},
{
"code": null,
"e": 3504,
"s": 3292,
"text": "Syntax :public int read(char[] cbuf)\n throws IOException\nParameters:\ncbuf - Destination buffer\nReturns:\nThe number of characters read, or -1 if the end of the stream has been reached\nThrows:\nIOException "
},
{
"code": null,
"e": 4065,
"s": 3504,
"text": "abstract int read(char[] cbuf, int off, int len) : Reads characters into a portion of an array.This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.Syntax :public abstract int read(char[] cbuf,\n int off,\n int len)\n throws IOException\nParameters:\ncbuf - Destination buffer\noff - Offset at which to start storing characters\nlen - Maximum number of characters to read\nReturns:\nThe number of characters read, or -1 if the end of the stream has been reached\nThrows:\nIOException "
},
{
"code": null,
"e": 4420,
"s": 4065,
"text": "Syntax :public abstract int read(char[] cbuf,\n int off,\n int len)\n throws IOException\nParameters:\ncbuf - Destination buffer\noff - Offset at which to start storing characters\nlen - Maximum number of characters to read\nReturns:\nThe number of characters read, or -1 if the end of the stream has been reached\nThrows:\nIOException "
},
{
"code": null,
"e": 4978,
"s": 4420,
"text": "int read(CharBuffer target) : Attempts to read characters into the specified character buffer.The buffer is used as a repository of characters as-is: the only changes made are the results of a put operation. No flipping or rewinding of the buffer is performed.Syntax :public int read(CharBuffer target)\n throws IOException\nParameters:\ntarget - the buffer to read characters into\nReturns:\nThe number of characters added to the buffer, \nor -1 if this source of characters is at its end\nThrows:\nIOException \nNullPointerException\nReadOnlyBufferException"
},
{
"code": null,
"e": 5276,
"s": 4978,
"text": "Syntax :public int read(CharBuffer target)\n throws IOException\nParameters:\ntarget - the buffer to read characters into\nReturns:\nThe number of characters added to the buffer, \nor -1 if this source of characters is at its end\nThrows:\nIOException \nNullPointerException\nReadOnlyBufferException"
},
{
"code": null,
"e": 5590,
"s": 5276,
"text": "boolean ready() : Tells whether this stream is ready to be read.Syntax :public boolean ready()\n throws IOException\nReturns:\nTrue if the next read() is guaranteed not to block for input, false otherwise. \nNote that returning false does not guarantee that the next read will block.\nThrows:\nIOException "
},
{
"code": null,
"e": 5840,
"s": 5590,
"text": "Syntax :public boolean ready()\n throws IOException\nReturns:\nTrue if the next read() is guaranteed not to block for input, false otherwise. \nNote that returning false does not guarantee that the next read will block.\nThrows:\nIOException "
},
{
"code": null,
"e": 6305,
"s": 5840,
"text": "void reset() : Resets the stream. If the stream has been marked, then attempt to reposition it at the mark. If the stream has not been marked, then attempt to reset it in some way appropriate to the particular stream, for example by repositioning it to its starting point. Not all character-input streams support the reset() operation, and some support reset() without supporting mark().Syntax :public void reset()\n throws IOException\nThrows:\nIOException"
},
{
"code": null,
"e": 6383,
"s": 6305,
"text": "Syntax :public void reset()\n throws IOException\nThrows:\nIOException"
},
{
"code": null,
"e": 6764,
"s": 6383,
"text": "long skip(long n) : Skips characters.This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached.Syntax :public long skip(long n)\n throws IOException\nParameters:\nn - The number of characters to skip\nReturns:\nThe number of characters actually skipped\nThrows:\nIllegalArgumentException - If n is negative.\nIOException"
},
{
"code": null,
"e": 6991,
"s": 6764,
"text": "Syntax :public long skip(long n)\n throws IOException\nParameters:\nn - The number of characters to skip\nReturns:\nThe number of characters actually skipped\nThrows:\nIllegalArgumentException - If n is negative.\nIOException"
},
{
"code": "//Java program demonstrating Reader methodsimport java.io.*;import java.nio.CharBuffer;import java.util.Arrays;class ReaderDemo{ public static void main(String[] args) throws IOException { Reader r = new FileReader(\"file.txt\"); PrintStream out = System.out; char c[] = new char[10]; CharBuffer cf = CharBuffer.wrap(c); //illustrating markSupported() if(r.markSupported()) { //illustrating mark() r.mark(100); out.println(\"mark method is supported\"); } //skipping 5 characters r.skip(5); //checking whether this stream is ready to be read. if(r.ready()) { //illustrating read(char[] cbuf,int off,int len) r.read(c,0,10); out.println(Arrays.toString(c)); //illustrating read(CharBuffer target ) r.read(cf); out.println(Arrays.toString(cf.array())); //illustrating read() out.println((char)r.read()); } //closing the stream r.close(); }}",
"e": 8082,
"s": 6991,
"text": null
},
{
"code": null,
"e": 8091,
"s": 8082,
"text": "Output :"
},
{
"code": null,
"e": 8156,
"s": 8091,
"text": "[f, g, h, i, g, k, l, m, n, o]\n[p, q, r, s, t, u, v, w, x, y]\nz\n"
},
{
"code": null,
"e": 8458,
"s": 8156,
"text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 8583,
"s": 8458,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8592,
"s": 8583,
"text": "Java-I/O"
},
{
"code": null,
"e": 8597,
"s": 8592,
"text": "Java"
},
{
"code": null,
"e": 8602,
"s": 8597,
"text": "Java"
}
]
|
Take Matrix input from user in Python | 30 Dec, 2020
Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as βrowsβ while the vertical entries are called as βcolumnsβ. If a matrix has r number of rows and c number of columns then the order of matrix is given by r x c. Each entries in a matrix can be integer values, or floating values, or even it can be complex numbers.
Examples:
// 3 x 4 matrix
1 2 3 4
M = 4 5 6 7
6 7 8 9
// 2 x 3 matrix in Python
A = ( [ 2, 5, 7 ],
[ 4, 7, 9 ] )
// 3 x 4 matrix in Python where entries are floating numbers
B = ( [ 1.0, 3.5, 5.4, 7.9 ],
[ 9.0, 2.5, 4.2, 3.6 ],
[ 1.5, 3.2, 1.6, 6.5 ] )
In Python, we can take a user input matrix in different ways. Some of the methods for user input matrix in Python are shown below:
Code #1:
# A basic code for matrix input from user R = int(input("Enter the number of rows:"))C = int(input("Enter the number of columns:")) # Initialize matrixmatrix = []print("Enter the entries rowwise:") # For user inputfor i in range(R): # A for loop for row entries a =[] for j in range(C): # A for loop for column entries a.append(int(input())) matrix.append(a) # For printing the matrixfor i in range(R): for j in range(C): print(matrix[i][j], end = " ") print()
Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
1
2
3
4
5
6
1 2 3
4 5 6
One liner:
# one-liner logic to take input for rows and columnsmat = [[int(input()) for x in range (C)] for y in range(R)]
Code #2: Using map() function and Numpy.
In Python, there exists a popular library called NumPy. This library is a fundamental library for any scientific computation. It is also used for multidimensional arrays and as we know matrix is a rectangular array, we will use this library for user input matrix.
import numpy as np R = int(input("Enter the number of rows:"))C = int(input("Enter the number of columns:")) print("Enter the entries in a single line (separated by space): ") # User input of entries in a # single line separated by spaceentries = list(map(int, input().split())) # For printing the matrixmatrix = np.array(entries).reshape(R, C)print(matrix)
Output:
Enter the number of rows:2
Enter the number of columns:2
Enter the entries in a single line separated by space: 1 2 3 1
[[1 2]
[3 1]]
mkumarchaudhary06
Picked
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 496,
"s": 54,
"text": "Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as βrowsβ while the vertical entries are called as βcolumnsβ. If a matrix has r number of rows and c number of columns then the order of matrix is given by r x c. Each entries in a matrix can be integer values, or floating values, or even it can be complex numbers."
},
{
"code": null,
"e": 506,
"s": 496,
"text": "Examples:"
},
{
"code": null,
"e": 780,
"s": 506,
"text": "// 3 x 4 matrix\n 1 2 3 4\nM = 4 5 6 7\n 6 7 8 9\n\n// 2 x 3 matrix in Python\nA = ( [ 2, 5, 7 ],\n [ 4, 7, 9 ] )\n\n// 3 x 4 matrix in Python where entries are floating numbers\nB = ( [ 1.0, 3.5, 5.4, 7.9 ],\n [ 9.0, 2.5, 4.2, 3.6 ],\n [ 1.5, 3.2, 1.6, 6.5 ] )"
},
{
"code": null,
"e": 911,
"s": 780,
"text": "In Python, we can take a user input matrix in different ways. Some of the methods for user input matrix in Python are shown below:"
},
{
"code": null,
"e": 920,
"s": 911,
"text": "Code #1:"
},
{
"code": "# A basic code for matrix input from user R = int(input(\"Enter the number of rows:\"))C = int(input(\"Enter the number of columns:\")) # Initialize matrixmatrix = []print(\"Enter the entries rowwise:\") # For user inputfor i in range(R): # A for loop for row entries a =[] for j in range(C): # A for loop for column entries a.append(int(input())) matrix.append(a) # For printing the matrixfor i in range(R): for j in range(C): print(matrix[i][j], end = \" \") print()",
"e": 1429,
"s": 920,
"text": null
},
{
"code": null,
"e": 1437,
"s": 1429,
"text": "Output:"
},
{
"code": null,
"e": 1549,
"s": 1437,
"text": "Enter the number of rows:2\nEnter the number of columns:3\nEnter the entries rowwise:\n1\n2\n3\n4\n5\n6\n\n1 2 3 \n4 5 6 \n"
},
{
"code": null,
"e": 1560,
"s": 1549,
"text": "One liner:"
},
{
"code": "# one-liner logic to take input for rows and columnsmat = [[int(input()) for x in range (C)] for y in range(R)]",
"e": 1672,
"s": 1560,
"text": null
},
{
"code": null,
"e": 1714,
"s": 1672,
"text": " Code #2: Using map() function and Numpy."
},
{
"code": null,
"e": 1978,
"s": 1714,
"text": "In Python, there exists a popular library called NumPy. This library is a fundamental library for any scientific computation. It is also used for multidimensional arrays and as we know matrix is a rectangular array, we will use this library for user input matrix."
},
{
"code": "import numpy as np R = int(input(\"Enter the number of rows:\"))C = int(input(\"Enter the number of columns:\")) print(\"Enter the entries in a single line (separated by space): \") # User input of entries in a # single line separated by spaceentries = list(map(int, input().split())) # For printing the matrixmatrix = np.array(entries).reshape(R, C)print(matrix)",
"e": 2342,
"s": 1978,
"text": null
},
{
"code": null,
"e": 2350,
"s": 2342,
"text": "Output:"
},
{
"code": null,
"e": 2486,
"s": 2350,
"text": "Enter the number of rows:2\nEnter the number of columns:2\nEnter the entries in a single line separated by space: 1 2 3 1 \n[[1 2]\n [3 1]]"
},
{
"code": null,
"e": 2504,
"s": 2486,
"text": "mkumarchaudhary06"
},
{
"code": null,
"e": 2511,
"s": 2504,
"text": "Picked"
},
{
"code": null,
"e": 2533,
"s": 2511,
"text": "Python matrix-program"
},
{
"code": null,
"e": 2540,
"s": 2533,
"text": "Python"
},
{
"code": null,
"e": 2556,
"s": 2540,
"text": "Python Programs"
},
{
"code": null,
"e": 2654,
"s": 2556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2672,
"s": 2654,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2714,
"s": 2672,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2736,
"s": 2714,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2771,
"s": 2736,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2797,
"s": 2771,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2840,
"s": 2797,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2862,
"s": 2840,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2901,
"s": 2862,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2939,
"s": 2901,
"text": "Python | Convert a list to dictionary"
}
]
|
Enumeration in Scala | 21 Oct, 2021
An enumerations serve the purpose of representing a group of named constants in a programming language. Refer Enumeration (or enum) in C and enum in Java for information on enumerations. Scala provides an Enumeration class which we can extend in order to create our enumerations. Declaration of enumerations in Scala
Scala
// A simple scala program of enumeration // Creating enumerationobject Main extends Enumeration{ type Main = Value // Assigning values val first = Value("Thriller") val second = Value("Horror") val third = Value("Comedy") val fourth = Value("Romance") // Main method def main(args: Array[String]) { println(s"Main Movie Genres = ${Main.values}") }}
Main Movie Genres = Movies.ValueSet(Thriller, Horror, Comedy, Romance)
Important points of enum :
In Scala, there is no enum keyword unlike Java or C.
Scala provides an Enumeration class which we can extend in order to create our enumerations.
Every Enumeration constant represents an object of type Enumeration.
Enumeration values are defined as val members of the evaluation.
When we extended the Enumeration class, a lot of functions get inherited. ID is one among the them.
We can iterate the members.
Printing particular element of the enumeration
Scala
// Scala program Printing particular// element of the enumeration // Creating enumerationobject Main extends Enumeration{ type Main = Value // Assigning values val first = Value("Thriller") val second = Value("Horror") val third = Value("Comedy") val fourth = Value("Romance") // Main method def main(args: Array[String]) { println(s"The third value = ${Main.third}") }}
The third value = Comedy
In above example, Main.third is printing particular element of the enumeration. Printing default ID of any element in the enumeration
Scala
// Scala program Printing default ID of// any element in the enumeration // Creating Enumerationobject Main extends Enumeration{ type Main = Value // Assigning Values val first = Value("Thriller") // ID = 0 val second = Value("Horror") // ID = 1 val third = Value("Comedy") // ID = 2 val fourth = Value("Romance") // ID = 3 // Main Method def main(args: Array[String]) { println(s"ID of third = ${Main.third.id}") }}
ID of third = 2
In above example, Main.third.id is printing default ID of any element in the enumeration. Matching values in enumeration
Scala
// Scala program of Matching values in enumeration // Creating Enumerationobject Main extends Enumeration{ type Main = Value // Assigning Values val first = Value("Thriller") val second = Value("Horror") val third = Value("Comedy") val fourth = Value("Romance") // Main Method def main(args: Array[String]) { Main.values.foreach { // Matching values in Enumeration case d if ( d == Main.third ) => println(s"Favourite type of Movie = $d") case _ => None } }}
Favourite type of Movie = Comedy
Changing default IDs of values The values are printed in the order of the ID set by us.These values of IDs can be any integer .These IDs need not be in any particular order.
Scala
// Scala program of Changing// default IDs of values // Creating Enumerationobject Main extends Enumeration{ type Main = Value // Assigning Values val first = Value(0, "Thriller") val second = Value(-1, "Horror") val third = Value(-3, "Comedy") val fourth = Value(4, "Romance") // Main Method def main(args: Array[String]) { println(s" Movie Genres = ${Main.values}") }}
Movie Genres = Movies.ValueSet(Comedy, Horror, Thriller, Romance)
Reference: https://www.scala-lang.org/api/current/scala/Enumeration.html
kashishsoda
Picked
Scala
Scala-Basics
Articles
Programming Language
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 346,
"s": 28,
"text": "An enumerations serve the purpose of representing a group of named constants in a programming language. Refer Enumeration (or enum) in C and enum in Java for information on enumerations. Scala provides an Enumeration class which we can extend in order to create our enumerations. Declaration of enumerations in Scala "
},
{
"code": null,
"e": 352,
"s": 346,
"text": "Scala"
},
{
"code": "// A simple scala program of enumeration // Creating enumerationobject Main extends Enumeration{ type Main = Value // Assigning values val first = Value(\"Thriller\") val second = Value(\"Horror\") val third = Value(\"Comedy\") val fourth = Value(\"Romance\") // Main method def main(args: Array[String]) { println(s\"Main Movie Genres = ${Main.values}\") }}",
"e": 748,
"s": 352,
"text": null
},
{
"code": null,
"e": 819,
"s": 748,
"text": "Main Movie Genres = Movies.ValueSet(Thriller, Horror, Comedy, Romance)"
},
{
"code": null,
"e": 852,
"s": 821,
"text": " Important points of enum : "
},
{
"code": null,
"e": 905,
"s": 852,
"text": "In Scala, there is no enum keyword unlike Java or C."
},
{
"code": null,
"e": 998,
"s": 905,
"text": "Scala provides an Enumeration class which we can extend in order to create our enumerations."
},
{
"code": null,
"e": 1067,
"s": 998,
"text": "Every Enumeration constant represents an object of type Enumeration."
},
{
"code": null,
"e": 1132,
"s": 1067,
"text": "Enumeration values are defined as val members of the evaluation."
},
{
"code": null,
"e": 1232,
"s": 1132,
"text": "When we extended the Enumeration class, a lot of functions get inherited. ID is one among the them."
},
{
"code": null,
"e": 1260,
"s": 1232,
"text": "We can iterate the members."
},
{
"code": null,
"e": 1309,
"s": 1260,
"text": "Printing particular element of the enumeration "
},
{
"code": null,
"e": 1315,
"s": 1309,
"text": "Scala"
},
{
"code": "// Scala program Printing particular// element of the enumeration // Creating enumerationobject Main extends Enumeration{ type Main = Value // Assigning values val first = Value(\"Thriller\") val second = Value(\"Horror\") val third = Value(\"Comedy\") val fourth = Value(\"Romance\") // Main method def main(args: Array[String]) { println(s\"The third value = ${Main.third}\") }}",
"e": 1734,
"s": 1315,
"text": null
},
{
"code": null,
"e": 1759,
"s": 1734,
"text": "The third value = Comedy"
},
{
"code": null,
"e": 1899,
"s": 1761,
"text": "In above example, Main.third is printing particular element of the enumeration. Printing default ID of any element in the enumeration "
},
{
"code": null,
"e": 1905,
"s": 1899,
"text": "Scala"
},
{
"code": "// Scala program Printing default ID of// any element in the enumeration // Creating Enumerationobject Main extends Enumeration{ type Main = Value // Assigning Values val first = Value(\"Thriller\") // ID = 0 val second = Value(\"Horror\") // ID = 1 val third = Value(\"Comedy\") // ID = 2 val fourth = Value(\"Romance\") // ID = 3 // Main Method def main(args: Array[String]) { println(s\"ID of third = ${Main.third.id}\") }}",
"e": 2367,
"s": 1905,
"text": null
},
{
"code": null,
"e": 2383,
"s": 2367,
"text": "ID of third = 2"
},
{
"code": null,
"e": 2509,
"s": 2385,
"text": "In above example, Main.third.id is printing default ID of any element in the enumeration. Matching values in enumeration "
},
{
"code": null,
"e": 2515,
"s": 2509,
"text": "Scala"
},
{
"code": "// Scala program of Matching values in enumeration // Creating Enumerationobject Main extends Enumeration{ type Main = Value // Assigning Values val first = Value(\"Thriller\") val second = Value(\"Horror\") val third = Value(\"Comedy\") val fourth = Value(\"Romance\") // Main Method def main(args: Array[String]) { Main.values.foreach { // Matching values in Enumeration case d if ( d == Main.third ) => println(s\"Favourite type of Movie = $d\") case _ => None } }}",
"e": 3079,
"s": 2515,
"text": null
},
{
"code": null,
"e": 3112,
"s": 3079,
"text": "Favourite type of Movie = Comedy"
},
{
"code": null,
"e": 3291,
"s": 3114,
"text": " Changing default IDs of values The values are printed in the order of the ID set by us.These values of IDs can be any integer .These IDs need not be in any particular order. "
},
{
"code": null,
"e": 3297,
"s": 3291,
"text": "Scala"
},
{
"code": "// Scala program of Changing// default IDs of values // Creating Enumerationobject Main extends Enumeration{ type Main = Value // Assigning Values val first = Value(0, \"Thriller\") val second = Value(-1, \"Horror\") val third = Value(-3, \"Comedy\") val fourth = Value(4, \"Romance\") // Main Method def main(args: Array[String]) { println(s\" Movie Genres = ${Main.values}\") }}",
"e": 3711,
"s": 3297,
"text": null
},
{
"code": null,
"e": 3777,
"s": 3711,
"text": "Movie Genres = Movies.ValueSet(Comedy, Horror, Thriller, Romance)"
},
{
"code": null,
"e": 3855,
"s": 3779,
"text": " Reference: https://www.scala-lang.org/api/current/scala/Enumeration.html "
},
{
"code": null,
"e": 3867,
"s": 3855,
"text": "kashishsoda"
},
{
"code": null,
"e": 3874,
"s": 3867,
"text": "Picked"
},
{
"code": null,
"e": 3880,
"s": 3874,
"text": "Scala"
},
{
"code": null,
"e": 3893,
"s": 3880,
"text": "Scala-Basics"
},
{
"code": null,
"e": 3902,
"s": 3893,
"text": "Articles"
},
{
"code": null,
"e": 3923,
"s": 3902,
"text": "Programming Language"
},
{
"code": null,
"e": 3929,
"s": 3923,
"text": "Scala"
}
]
|
How to Maintain Insertion Order of the Elements in Java HashMap? | 04 Jan, 2021
When elements get from the HashMap due to hashing the order they inserted is not maintained while retrieval. We can achieve the given task using LinkedHashMap. The LinkedHashMap class implements a doubly-linked list so that it can traverse through all the elements.
Example:
Input : HashMapInput = {c=6, a=1, b=2}
Output: HashMapPrint = {c=6, a=1, b=2}
Input : HashMapInput = {"first"=1, "second"=3}
Output: HashMapPrint = {"first"=1, "second"=3}
Syntax:
public LinkedHashMap(Map m)
It creates an object of the LinkedHashMap class with the same mappings specified in the original Map object.
Order Not Maintain Here: HashMap Implementation:
Java
// Java Program to maintain insertion order// of the elements in HashMap // Using HashMap (Order not maintain)import java.io.*;import java.util.*;class GFG { public static void main(String args[]) { // creating a hashmap HashMap<String, String> hm = new HashMap<>(); // putting elements hm.put("01", "aaaaaaa"); hm.put("03", "bbbbbbb"); hm.put("04", "zzzzzzz"); hm.put("02", "kkkkkkk"); System.out.println("Iterate over original HashMap"); // printing hashmap for (Map.Entry<String, String> entry : hm.entrySet()) { System.out.println(entry.getKey() + " => " + ": " + entry.getValue()); } }}
Iterate over original HashMap
01 => : aaaaaaa
02 => : kkkkkkk
03 => : bbbbbbb
04 => : zzzzzzz
Here, the original insertion order of HashMap is [01, 03, 04, 02], but the output is different [01, 02, 03, 04]. It did not maintain the original insertion order of the elements.
Order Maintain Here: LinkedHashMap implementation
Java
// Java Program to maintain insertion order// of the elements in HashMap // LinkedHashMapimport java.io.*;import java.util.*;class GFG { public static void main(String args[]) { // creating a hashmap HashMap<String, String> hm = new LinkedHashMap<>(); // putting elements hm.put("01", "aaaaaaa"); hm.put("03", "bbbbbbb"); hm.put("04", "zzzzzzz"); hm.put("02", "kkkkkkk"); // printing LinkedHashMap System.out.println("Iterate over LinkedHashMap"); for (Map.Entry<String, String> entry : hm.entrySet()) { System.out.println(entry.getKey() + " => " + ": " + entry.getValue()); } }}
Iterate over LinkedHashMap
01 => : aaaaaaa
03 => : bbbbbbb
04 => : zzzzzzz
02 => : kkkkkkk
Java-LinkedHashMap
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "When elements get from the HashMap due to hashing the order they inserted is not maintained while retrieval. We can achieve the given task using LinkedHashMap. The LinkedHashMap class implements a doubly-linked list so that it can traverse through all the elements."
},
{
"code": null,
"e": 303,
"s": 294,
"text": "Example:"
},
{
"code": null,
"e": 476,
"s": 303,
"text": "Input : HashMapInput = {c=6, a=1, b=2}\nOutput: HashMapPrint = {c=6, a=1, b=2}\n\nInput : HashMapInput = {\"first\"=1, \"second\"=3}\nOutput: HashMapPrint = {\"first\"=1, \"second\"=3}"
},
{
"code": null,
"e": 484,
"s": 476,
"text": "Syntax:"
},
{
"code": null,
"e": 512,
"s": 484,
"text": "public LinkedHashMap(Map m)"
},
{
"code": null,
"e": 621,
"s": 512,
"text": "It creates an object of the LinkedHashMap class with the same mappings specified in the original Map object."
},
{
"code": null,
"e": 670,
"s": 621,
"text": "Order Not Maintain Here: HashMap Implementation:"
},
{
"code": null,
"e": 675,
"s": 670,
"text": "Java"
},
{
"code": "// Java Program to maintain insertion order// of the elements in HashMap // Using HashMap (Order not maintain)import java.io.*;import java.util.*;class GFG { public static void main(String args[]) { // creating a hashmap HashMap<String, String> hm = new HashMap<>(); // putting elements hm.put(\"01\", \"aaaaaaa\"); hm.put(\"03\", \"bbbbbbb\"); hm.put(\"04\", \"zzzzzzz\"); hm.put(\"02\", \"kkkkkkk\"); System.out.println(\"Iterate over original HashMap\"); // printing hashmap for (Map.Entry<String, String> entry : hm.entrySet()) { System.out.println(entry.getKey() + \" => \" + \": \" + entry.getValue()); } }}",
"e": 1423,
"s": 675,
"text": null
},
{
"code": null,
"e": 1517,
"s": 1423,
"text": "Iterate over original HashMap\n01 => : aaaaaaa\n02 => : kkkkkkk\n03 => : bbbbbbb\n04 => : zzzzzzz"
},
{
"code": null,
"e": 1696,
"s": 1517,
"text": "Here, the original insertion order of HashMap is [01, 03, 04, 02], but the output is different [01, 02, 03, 04]. It did not maintain the original insertion order of the elements."
},
{
"code": null,
"e": 1746,
"s": 1696,
"text": "Order Maintain Here: LinkedHashMap implementation"
},
{
"code": null,
"e": 1751,
"s": 1746,
"text": "Java"
},
{
"code": "// Java Program to maintain insertion order// of the elements in HashMap // LinkedHashMapimport java.io.*;import java.util.*;class GFG { public static void main(String args[]) { // creating a hashmap HashMap<String, String> hm = new LinkedHashMap<>(); // putting elements hm.put(\"01\", \"aaaaaaa\"); hm.put(\"03\", \"bbbbbbb\"); hm.put(\"04\", \"zzzzzzz\"); hm.put(\"02\", \"kkkkkkk\"); // printing LinkedHashMap System.out.println(\"Iterate over LinkedHashMap\"); for (Map.Entry<String, String> entry : hm.entrySet()) { System.out.println(entry.getKey() + \" => \" + \": \" + entry.getValue()); } }}",
"e": 2479,
"s": 1751,
"text": null
},
{
"code": null,
"e": 2570,
"s": 2479,
"text": "Iterate over LinkedHashMap\n01 => : aaaaaaa\n03 => : bbbbbbb\n04 => : zzzzzzz\n02 => : kkkkkkk"
},
{
"code": null,
"e": 2589,
"s": 2570,
"text": "Java-LinkedHashMap"
},
{
"code": null,
"e": 2596,
"s": 2589,
"text": "Picked"
},
{
"code": null,
"e": 2601,
"s": 2596,
"text": "Java"
},
{
"code": null,
"e": 2615,
"s": 2601,
"text": "Java Programs"
},
{
"code": null,
"e": 2620,
"s": 2615,
"text": "Java"
},
{
"code": null,
"e": 2718,
"s": 2620,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2733,
"s": 2718,
"text": "Stream In Java"
},
{
"code": null,
"e": 2754,
"s": 2733,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2775,
"s": 2754,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2794,
"s": 2775,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2811,
"s": 2794,
"text": "Generics in Java"
},
{
"code": null,
"e": 2837,
"s": 2811,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2871,
"s": 2837,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 2918,
"s": 2871,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 2956,
"s": 2918,
"text": "Factory method design pattern in Java"
}
]
|
Python β Sort Dictionary key and values List | 02 Jun, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Letβs discuss certain way in which this task can be performed.
Input : test_dict = {βcβ: [3], βbβ: [12, 10], βaβ: [19, 4]}Output : {βaβ: [4, 19], βbβ: [10, 12], βcβ: [3]}
Input : test_dict = {βcβ: [10, 34, 3]}Output : {βcβ: [3, 10, 34]}
Method #1 : Using sorted() + loopThe combination of above functions can be used to solve this problem. In this, we initially sort all the values of keys, and then perform the keys sorting after that, in brute manner.
# Python3 code to demonstrate working of # Sort Dictionary key and values List# Using loop + dictionary comprehension # initializing dictionarytest_dict = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Sort Dictionary key and values List# Using loop + dictionary comprehensionres = dict()for key in sorted(test_dict): res[key] = sorted(test_dict[key]) # printing result print("The sorted dictionary : " + str(res))
The original dictionary is : {βgfgβ: [7, 6, 3], βisβ: [2, 10, 3], βbestβ: [19, 4]}The sorted dictionary : {βbestβ: [4, 19], βgfgβ: [3, 6, 7], βisβ: [2, 3, 10]}
Method #2: Using dictionary comprehension + sorted()The combination of above functions can be used to solve this problem. In this, we perform the task of dual sorting inside dictionary comprehension construct.
# Python3 code to demonstrate working of # Sort Dictionary key and values List# Using dictionary comprehension + sorted() # initializing dictionarytest_dict = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Sort Dictionary key and values List# Using dictionary comprehension + sorted()res = {key : sorted(test_dict[key]) for key in sorted(test_dict)} # printing result print("The sorted dictionary : " + str(res))
The original dictionary is : {βgfgβ: [7, 6, 3], βisβ: [2, 10, 3], βbestβ: [19, 4]}The sorted dictionary : {βbestβ: [4, 19], βgfgβ: [3, 6, 7], βisβ: [2, 3, 10]}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 314,
"s": 28,
"text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Letβs discuss certain way in which this task can be performed."
},
{
"code": null,
"e": 422,
"s": 314,
"text": "Input : test_dict = {βcβ: [3], βbβ: [12, 10], βaβ: [19, 4]}Output : {βaβ: [4, 19], βbβ: [10, 12], βcβ: [3]}"
},
{
"code": null,
"e": 488,
"s": 422,
"text": "Input : test_dict = {βcβ: [10, 34, 3]}Output : {βcβ: [3, 10, 34]}"
},
{
"code": null,
"e": 705,
"s": 488,
"text": "Method #1 : Using sorted() + loopThe combination of above functions can be used to solve this problem. In this, we initially sort all the values of keys, and then perform the keys sorting after that, in brute manner."
},
{
"code": "# Python3 code to demonstrate working of # Sort Dictionary key and values List# Using loop + dictionary comprehension # initializing dictionarytest_dict = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Sort Dictionary key and values List# Using loop + dictionary comprehensionres = dict()for key in sorted(test_dict): res[key] = sorted(test_dict[key]) # printing result print(\"The sorted dictionary : \" + str(res)) ",
"e": 1249,
"s": 705,
"text": null
},
{
"code": null,
"e": 1409,
"s": 1249,
"text": "The original dictionary is : {βgfgβ: [7, 6, 3], βisβ: [2, 10, 3], βbestβ: [19, 4]}The sorted dictionary : {βbestβ: [4, 19], βgfgβ: [3, 6, 7], βisβ: [2, 3, 10]}"
},
{
"code": null,
"e": 1621,
"s": 1411,
"text": "Method #2: Using dictionary comprehension + sorted()The combination of above functions can be used to solve this problem. In this, we perform the task of dual sorting inside dictionary comprehension construct."
},
{
"code": "# Python3 code to demonstrate working of # Sort Dictionary key and values List# Using dictionary comprehension + sorted() # initializing dictionarytest_dict = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Sort Dictionary key and values List# Using dictionary comprehension + sorted()res = {key : sorted(test_dict[key]) for key in sorted(test_dict)} # printing result print(\"The sorted dictionary : \" + str(res)) ",
"e": 2160,
"s": 1621,
"text": null
},
{
"code": null,
"e": 2320,
"s": 2160,
"text": "The original dictionary is : {βgfgβ: [7, 6, 3], βisβ: [2, 10, 3], βbestβ: [19, 4]}The sorted dictionary : {βbestβ: [4, 19], βgfgβ: [3, 6, 7], βisβ: [2, 3, 10]}"
},
{
"code": null,
"e": 2347,
"s": 2320,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2354,
"s": 2347,
"text": "Python"
},
{
"code": null,
"e": 2370,
"s": 2354,
"text": "Python Programs"
},
{
"code": null,
"e": 2468,
"s": 2370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2500,
"s": 2468,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2527,
"s": 2500,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2558,
"s": 2527,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2581,
"s": 2558,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2602,
"s": 2581,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2624,
"s": 2602,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2663,
"s": 2624,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2701,
"s": 2663,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2750,
"s": 2701,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
PHP Returning values | A function can have return as last statement in its body although it is not mandatory. When a function is called, control of program come back to calling environment after executing statements in its body block - irrespective of whether last statement in function block is return or not. In absence of retun statement, control returns NULL value to caller. If return statement consistes of an expression clause, value of expression is returned. Function can return only one value which may be of scalar type, array, or an object. Returned value may be assigned to some variable for subsequent processing
In following example, a function returns sum of two integers passed as argument
Live Demo
<?php
function add($var1, $var2){
$var3= $var1+$var2 ;
return $var3;
}
$x=10;
$y=20;
$z=add($x,$y);
echo "addition=$z";
?>
This will produce following result. β
addition=30
Function can return only one value. However, array of multiple values can be returned. Following example passes two numbers to a function that returns array of addition, subtraction, multiplication and division
Live Demo
<?php
function result($var1, $var2){
$r1=$var1+$var2;
$r2=$var1-$var2;
$r3=$var1*$var2;
$r4=$var1/$var2;
return array("add"=>$r1,"sub"=>$r2,"multiply"=>$r3,"division"=>$r4);
}
$x=10;
$y=20;
$arr=result($x,$y);
foreach ($arr as $k=>$v){
echo $k . "->" . $v . "\n";
}
?>
This will produce following result. β
add->30
sub->-10
multiply->200
division->0.5
Just as arguments can be passed by reference, a function can return by reference also. For that purpose, function's name must be prefixed by $ symbol. Further, & symbol must also be given in function call
In following example, myfunction() has a static array. One of its elements is returned by reference and is accepted in a variable. Value of variable is then modified and same function is called again. Array in the function should now show its value changed.
Live Demo
<?php
function &myfunction(){
static $arr=[1,2,3,4,5];
echo "array elements: ";
foreach ($arr as $i){
echo "$i ";
}
echo "\n";
return $arr[2];
}
$var=&myfunction();
echo "returned by reference : $var\n";
$var=100;
$var=&myfunction();
?>
This will produce following result. β
array elements: 1 2 3 4 5
returned by reference : 3
array elements: 1 2 100 4 5
Values of variables xandy are interchanged in swap() function. Since, variables are passed by reference, the variables show modified values outside the function too
From PHP 7 onwards, you can specify type hints for returned variable/object, just as it is possible to declare type for arguments. For return type also all scalar types, class and array can be used
//define a function with type hints for return value
function myfunction($arg1, $arg2): type{
..
..
return $var;
}
All standard PHP data types including scalar types, array, class/interface, iterable and object are valid types for providing type hints for return variable in a function declaration
Live Demo
<?php
function add($x, $y): float{
return $x+$y;
}
$var=add(5,8);
var_dump($var);
?>
This will produce following result. β
float(13)
Use of declare statement with strict_types=1 will prevent coercion of data types
Live Demo
<?php
declare (strict_types=1);
function add($x, $y): int{
return $x+$y;
}
$var=add(5.5,8.8);
var_dump($var);
?>
This will now throw exception as follows β
PHP Fatal error: Uncaught TypeError: Return value of add() must be of the type integer, float returned | [
{
"code": null,
"e": 1791,
"s": 1187,
"text": "A function can have return as last statement in its body although it is not mandatory. When a function is called, control of program come back to calling environment after executing statements in its body block - irrespective of whether last statement in function block is return or not. In absence of retun statement, control returns NULL value to caller. If return statement consistes of an expression clause, value of expression is returned. Function can return only one value which may be of scalar type, array, or an object. Returned value may be assigned to some variable for subsequent processing"
},
{
"code": null,
"e": 1871,
"s": 1791,
"text": "In following example, a function returns sum of two integers passed as argument"
},
{
"code": null,
"e": 1882,
"s": 1871,
"text": " Live Demo"
},
{
"code": null,
"e": 2011,
"s": 1882,
"text": "<?php\nfunction add($var1, $var2){\n $var3= $var1+$var2 ;\n return $var3;\n}\n$x=10;\n$y=20;\n$z=add($x,$y);\necho \"addition=$z\";\n?>"
},
{
"code": null,
"e": 2049,
"s": 2011,
"text": "This will produce following result. β"
},
{
"code": null,
"e": 2061,
"s": 2049,
"text": "addition=30"
},
{
"code": null,
"e": 2272,
"s": 2061,
"text": "Function can return only one value. However, array of multiple values can be returned. Following example passes two numbers to a function that returns array of addition, subtraction, multiplication and division"
},
{
"code": null,
"e": 2283,
"s": 2272,
"text": " Live Demo"
},
{
"code": null,
"e": 2570,
"s": 2283,
"text": "<?php\nfunction result($var1, $var2){\n $r1=$var1+$var2;\n $r2=$var1-$var2;\n $r3=$var1*$var2;\n $r4=$var1/$var2;\n return array(\"add\"=>$r1,\"sub\"=>$r2,\"multiply\"=>$r3,\"division\"=>$r4);\n}\n$x=10;\n$y=20;\n$arr=result($x,$y);\nforeach ($arr as $k=>$v){\n echo $k . \"->\" . $v . \"\\n\";\n}\n?>"
},
{
"code": null,
"e": 2608,
"s": 2570,
"text": "This will produce following result. β"
},
{
"code": null,
"e": 2653,
"s": 2608,
"text": "add->30\nsub->-10\nmultiply->200\ndivision->0.5"
},
{
"code": null,
"e": 2858,
"s": 2653,
"text": "Just as arguments can be passed by reference, a function can return by reference also. For that purpose, function's name must be prefixed by $ symbol. Further, & symbol must also be given in function call"
},
{
"code": null,
"e": 3116,
"s": 2858,
"text": "In following example, myfunction() has a static array. One of its elements is returned by reference and is accepted in a variable. Value of variable is then modified and same function is called again. Array in the function should now show its value changed."
},
{
"code": null,
"e": 3127,
"s": 3116,
"text": " Live Demo"
},
{
"code": null,
"e": 3388,
"s": 3127,
"text": "<?php\nfunction &myfunction(){\n static $arr=[1,2,3,4,5];\n echo \"array elements: \";\n foreach ($arr as $i){\n echo \"$i \";\n }\n echo \"\\n\";\n return $arr[2];\n}\n$var=&myfunction();\necho \"returned by reference : $var\\n\";\n$var=100;\n$var=&myfunction();\n?>"
},
{
"code": null,
"e": 3426,
"s": 3388,
"text": "This will produce following result. β"
},
{
"code": null,
"e": 3506,
"s": 3426,
"text": "array elements: 1 2 3 4 5\nreturned by reference : 3\narray elements: 1 2 100 4 5"
},
{
"code": null,
"e": 3671,
"s": 3506,
"text": "Values of variables xandy are interchanged in swap() function. Since, variables are passed by reference, the variables show modified values outside the function too"
},
{
"code": null,
"e": 3869,
"s": 3671,
"text": "From PHP 7 onwards, you can specify type hints for returned variable/object, just as it is possible to declare type for arguments. For return type also all scalar types, class and array can be used"
},
{
"code": null,
"e": 3993,
"s": 3869,
"text": "//define a function with type hints for return value\nfunction myfunction($arg1, $arg2): type{\n ..\n ..\n return $var;\n}"
},
{
"code": null,
"e": 4176,
"s": 3993,
"text": "All standard PHP data types including scalar types, array, class/interface, iterable and object are valid types for providing type hints for return variable in a function declaration"
},
{
"code": null,
"e": 4187,
"s": 4176,
"text": " Live Demo"
},
{
"code": null,
"e": 4275,
"s": 4187,
"text": "<?php\nfunction add($x, $y): float{\n return $x+$y;\n}\n$var=add(5,8);\nvar_dump($var);\n?>"
},
{
"code": null,
"e": 4313,
"s": 4275,
"text": "This will produce following result. β"
},
{
"code": null,
"e": 4323,
"s": 4313,
"text": "float(13)"
},
{
"code": null,
"e": 4404,
"s": 4323,
"text": "Use of declare statement with strict_types=1 will prevent coercion of data types"
},
{
"code": null,
"e": 4415,
"s": 4404,
"text": " Live Demo"
},
{
"code": null,
"e": 4531,
"s": 4415,
"text": "<?php\ndeclare (strict_types=1);\nfunction add($x, $y): int{\n return $x+$y;\n}\n$var=add(5.5,8.8);\nvar_dump($var);\n?>"
},
{
"code": null,
"e": 4574,
"s": 4531,
"text": "This will now throw exception as follows β"
},
{
"code": null,
"e": 4677,
"s": 4574,
"text": "PHP Fatal error: Uncaught TypeError: Return value of add() must be of the type integer, float returned"
}
]
|
Flask aΜΒΒ Message Flashing | A good GUI based application provides feedback to a user about the interaction. For example, the desktop applications use dialog or message box and JavaScript uses alerts for similar purpose.
Generating such informative messages is easy in Flask web application. Flashing system of Flask framework makes it possible to create a message in one view and render it in a view function called next.
A Flask module contains flash() method. It passes a message to the next request, which generally is a template.
flash(message, category)
Here,
message parameter is the actual message to be flashed.
message parameter is the actual message to be flashed.
category parameter is optional. It can be either βerrorβ, βinfoβ or βwarningβ.
category parameter is optional. It can be either βerrorβ, βinfoβ or βwarningβ.
In order to remove message from session, template calls get_flashed_messages().
get_flashed_messages(with_categories, category_filter)
Both parameters are optional. The first parameter is a tuple if received messages are having category. The second parameter is useful to display only specific messages.
The following flashes received messages in a template.
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
{% endwith %}
Let us now see a simple example, demonstrating the flashing mechanism in Flask. In the following code, a β/β URL displays link to the login page, with no message to flash.
@app.route('/')
def index():
return render_template('index.html')
The link leads a user to β/loginβ URL which displays a login form. When submitted, the login() view function verifies a username and password and accordingly flashes a βsuccessβ message or creates βerrorβ variable.
@app.route('/login', methods = ['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'admin':
error = 'Invalid username or password. Please try again!'
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('login.html', error = error)
In case of error, the login template is redisplayed with error message.
<!doctype html>
<html>
<body>
<h1>Login</h1>
{% if error %}
<p><strong>Error:</strong> {{ error }}
{% endif %}
<form action = "" method = post>
<dl>
<dt>Username:</dt>
<dd>
<input type = text name = username
value = "{{request.form.username }}">
</dd>
<dt>Password:</dt>
<dd><input type = password name = password></dd>
</dl>
<p><input type = submit value = Login></p>
</form>
</body>
</html>
On the other hand, if login is successful, a success message is flashed on the index template.
<!doctype html>
<html>
<head>
<title>Flask Message flashing</title>
</head>
<body>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li<{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<h1>Flask Message Flashing Example</h1>
<p>Do you want to <a href = "{{ url_for('login') }}">
<b>log in?</b></a></p>
</body>
</html>
A complete code for Flask message flashing example is given below β
from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods = ['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'admin':
error = 'Invalid username or password. Please try again!'
else:
flash('You were successfully logged in')
return redirect(url_for('index'))
return render_template('login.html', error = error)
if __name__ == "__main__":
app.run(debug = True)
After executing the above codes, you will see the screen as shown below.
When you click on the link, you will be directed to the Login page.
Enter the Username and password.
Click Login. A message will be displayed βYou were successfully logged inβ . | [
{
"code": null,
"e": 2359,
"s": 2167,
"text": "A good GUI based application provides feedback to a user about the interaction. For example, the desktop applications use dialog or message box and JavaScript uses alerts for similar purpose."
},
{
"code": null,
"e": 2561,
"s": 2359,
"text": "Generating such informative messages is easy in Flask web application. Flashing system of Flask framework makes it possible to create a message in one view and render it in a view function called next."
},
{
"code": null,
"e": 2673,
"s": 2561,
"text": "A Flask module contains flash() method. It passes a message to the next request, which generally is a template."
},
{
"code": null,
"e": 2699,
"s": 2673,
"text": "flash(message, category)\n"
},
{
"code": null,
"e": 2705,
"s": 2699,
"text": "Here,"
},
{
"code": null,
"e": 2760,
"s": 2705,
"text": "message parameter is the actual message to be flashed."
},
{
"code": null,
"e": 2815,
"s": 2760,
"text": "message parameter is the actual message to be flashed."
},
{
"code": null,
"e": 2894,
"s": 2815,
"text": "category parameter is optional. It can be either βerrorβ, βinfoβ or βwarningβ."
},
{
"code": null,
"e": 2973,
"s": 2894,
"text": "category parameter is optional. It can be either βerrorβ, βinfoβ or βwarningβ."
},
{
"code": null,
"e": 3053,
"s": 2973,
"text": "In order to remove message from session, template calls get_flashed_messages()."
},
{
"code": null,
"e": 3109,
"s": 3053,
"text": "get_flashed_messages(with_categories, category_filter)\n"
},
{
"code": null,
"e": 3278,
"s": 3109,
"text": "Both parameters are optional. The first parameter is a tuple if received messages are having category. The second parameter is useful to display only specific messages."
},
{
"code": null,
"e": 3333,
"s": 3278,
"text": "The following flashes received messages in a template."
},
{
"code": null,
"e": 3506,
"s": 3333,
"text": "{% with messages = get_flashed_messages() %}\n {% if messages %}\n {% for message in messages %}\n {{ message }}\n {% endfor %}\n {% endif %}\n{% endwith %}"
},
{
"code": null,
"e": 3678,
"s": 3506,
"text": "Let us now see a simple example, demonstrating the flashing mechanism in Flask. In the following code, a β/β URL displays link to the login page, with no message to flash."
},
{
"code": null,
"e": 3747,
"s": 3678,
"text": "@app.route('/')\ndef index():\n return render_template('index.html')"
},
{
"code": null,
"e": 3962,
"s": 3747,
"text": "The link leads a user to β/loginβ URL which displays a login form. When submitted, the login() view function verifies a username and password and accordingly flashes a βsuccessβ message or creates βerrorβ variable."
},
{
"code": null,
"e": 4398,
"s": 3962,
"text": "@app.route('/login', methods = ['GET', 'POST'])\ndef login():\n error = None\n \n if request.method == 'POST':\n if request.form['username'] != 'admin' or \\\n request.form['password'] != 'admin':\n error = 'Invalid username or password. Please try again!'\n else:\n flash('You were successfully logged in')\n return redirect(url_for('index'))\n return render_template('login.html', error = error)"
},
{
"code": null,
"e": 4470,
"s": 4398,
"text": "In case of error, the login template is redisplayed with error message."
},
{
"code": null,
"e": 5037,
"s": 4470,
"text": "<!doctype html>\n<html>\n <body>\n <h1>Login</h1>\n\n {% if error %}\n <p><strong>Error:</strong> {{ error }}\n {% endif %}\n \n <form action = \"\" method = post>\n <dl>\n <dt>Username:</dt>\n <dd>\n <input type = text name = username \n value = \"{{request.form.username }}\">\n </dd>\n <dt>Password:</dt>\n <dd><input type = password name = password></dd>\n </dl>\n <p><input type = submit value = Login></p>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 5132,
"s": 5037,
"text": "On the other hand, if login is successful, a success message is flashed on the index template."
},
{
"code": null,
"e": 5655,
"s": 5132,
"text": "<!doctype html>\n<html>\n <head>\n <title>Flask Message flashing</title>\n </head>\n <body>\n {% with messages = get_flashed_messages() %}\n {% if messages %}\n <ul>\n {% for message in messages %}\n <li<{{ message }}</li>\n {% endfor %}\n </ul>\n {% endif %}\n {% endwith %}\n\t\t\n <h1>Flask Message Flashing Example</h1>\n <p>Do you want to <a href = \"{{ url_for('login') }}\">\n <b>log in?</b></a></p>\n </body>\n</html>"
},
{
"code": null,
"e": 5723,
"s": 5655,
"text": "A complete code for Flask message flashing example is given below β"
},
{
"code": null,
"e": 6418,
"s": 5723,
"text": "from flask import Flask, flash, redirect, render_template, request, url_for\napp = Flask(__name__)\napp.secret_key = 'random string'\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/login', methods = ['GET', 'POST'])\ndef login():\n error = None\n \n if request.method == 'POST':\n if request.form['username'] != 'admin' or \\\n request.form['password'] != 'admin':\n error = 'Invalid username or password. Please try again!'\n else:\n flash('You were successfully logged in')\n return redirect(url_for('index'))\n\t\t\t\n return render_template('login.html', error = error)\n\nif __name__ == \"__main__\":\n app.run(debug = True)"
},
{
"code": null,
"e": 6491,
"s": 6418,
"text": "After executing the above codes, you will see the screen as shown below."
},
{
"code": null,
"e": 6559,
"s": 6491,
"text": "When you click on the link, you will be directed to the Login page."
},
{
"code": null,
"e": 6592,
"s": 6559,
"text": "Enter the Username and password."
}
]
|
Macro Processor | 06 Oct, 2020
A Macro instruction is the notational convenience for the programmer. For every occurrence of macro the whole macro body or macro block of statements gets expanded in the main source code. Thus Macro instructions make writing code more convenient.
Salient features of Macro Processor:
Macro represents a group of commonly used statements in the source programming language.
Macro Processor replaces each macro instruction with the corresponding group of source language statements. This is known as the expansion of macros.
Using Macro instructions programmer can leave the mechanical details to be handled by the macro processor.
Macro Processor designs are not directly related to the computer architecture on which it runs.
Macro Processor involves definition, invocation, and expansion.
Macro Definition and Expansion:
Line Label Opcode Operand
5 COPY START 0
10 RDBUFF MACRO &INDEV, &BUFADR
15
.
.
90
95 MEND
Line 10: RDBUFF (Read Buffer) in the Label part is the name of the Macro or definition of the Macro. &INDEV and &BUFADR are the parameters present in the Operand part. Each parameter begins with the character &.
Line 15 β Line 90: From Line 15 to Line 90 Macro Body is present. Macro directives are the statements that make up the body of the macro definition.
Line 95: MEND is the assembler directive that means the end of the macro definition.
Macro Invocation:
Line Label Opcode Operand
180 FIRST STL RETADR
190 CLOOP RDBUFF F1, BUFFER
15
.
.
255 END FIRST
Line 190: RDBUFF is the Macro invocation or Macro Call that gives the name of the macro instruction being invoked and F1, BUFFER are the arguments to be used in expanding the macro. The statement that form the expansion of a macro are generated each time the macro is invoked.
PanchajanyaSarkar
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Architecture of 8085 microprocessor
Control Characters
Pin diagram of 8086 microprocessor
I2C Communication Protocol
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Difference between SRAM and DRAM
Difference between Hardwired and Micro-programmed Control Unit | Set 2
Cache Coherence
Difference between RISC and CISC processor | Set 2 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Oct, 2020"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "A Macro instruction is the notational convenience for the programmer. For every occurrence of macro the whole macro body or macro block of statements gets expanded in the main source code. Thus Macro instructions make writing code more convenient. "
},
{
"code": null,
"e": 315,
"s": 277,
"text": "Salient features of Macro Processor: "
},
{
"code": null,
"e": 404,
"s": 315,
"text": "Macro represents a group of commonly used statements in the source programming language."
},
{
"code": null,
"e": 554,
"s": 404,
"text": "Macro Processor replaces each macro instruction with the corresponding group of source language statements. This is known as the expansion of macros."
},
{
"code": null,
"e": 661,
"s": 554,
"text": "Using Macro instructions programmer can leave the mechanical details to be handled by the macro processor."
},
{
"code": null,
"e": 757,
"s": 661,
"text": "Macro Processor designs are not directly related to the computer architecture on which it runs."
},
{
"code": null,
"e": 821,
"s": 757,
"text": "Macro Processor involves definition, invocation, and expansion."
},
{
"code": null,
"e": 854,
"s": 821,
"text": "Macro Definition and Expansion: "
},
{
"code": null,
"e": 1160,
"s": 854,
"text": "\nLine Label Opcode Operand\n \n5 COPY START 0\n10 RDBUFF MACRO &INDEV, &BUFADR\n15 \n.\n.\n90\n95 MEND\n"
},
{
"code": null,
"e": 1373,
"s": 1160,
"text": "Line 10: RDBUFF (Read Buffer) in the Label part is the name of the Macro or definition of the Macro. &INDEV and &BUFADR are the parameters present in the Operand part. Each parameter begins with the character &. "
},
{
"code": null,
"e": 1523,
"s": 1373,
"text": "Line 15 β Line 90: From Line 15 to Line 90 Macro Body is present. Macro directives are the statements that make up the body of the macro definition. "
},
{
"code": null,
"e": 1610,
"s": 1523,
"text": "Line 95: MEND is the assembler directive that means the end of the macro definition. "
},
{
"code": null,
"e": 1629,
"s": 1610,
"text": "Macro Invocation: "
},
{
"code": null,
"e": 1957,
"s": 1629,
"text": "\nLine Label Opcode Operand\n \n180 FIRST STL RETADR\n190 CLOOP RDBUFF F1, BUFFER\n15 \n.\n.\n255 END FIRST\n"
},
{
"code": null,
"e": 2235,
"s": 1957,
"text": "Line 190: RDBUFF is the Macro invocation or Macro Call that gives the name of the macro instruction being invoked and F1, BUFFER are the arguments to be used in expanding the macro. The statement that form the expansion of a macro are generated each time the macro is invoked. "
},
{
"code": null,
"e": 2253,
"s": 2235,
"text": "PanchajanyaSarkar"
},
{
"code": null,
"e": 2290,
"s": 2253,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 2388,
"s": 2290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2450,
"s": 2388,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 2486,
"s": 2450,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 2505,
"s": 2486,
"text": "Control Characters"
},
{
"code": null,
"e": 2540,
"s": 2505,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 2567,
"s": 2540,
"text": "I2C Communication Protocol"
},
{
"code": null,
"e": 2658,
"s": 2567,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 2691,
"s": 2658,
"text": "Difference between SRAM and DRAM"
},
{
"code": null,
"e": 2762,
"s": 2691,
"text": "Difference between Hardwired and Micro-programmed Control Unit | Set 2"
},
{
"code": null,
"e": 2778,
"s": 2762,
"text": "Cache Coherence"
}
]
|
Python β Pearsonβs Chi-Square Test | 23 Jun, 2020
The Pearsonβs Chi-Square statistical hypothesis is a test for independence between categorical variables. In this article, we will perform the test using a mathematical approach and then using Pythonβs SciPy module.First, let us see the mathematical approach :
The Contingency Table :A Contingency table (also called crosstab) is used in statistics to summarise the relationship between several categorical variables. Here, we take a table that shows the number of men and women buying different types of pets.
The aim of the test is to conclude whether the two variables( gender and choice of pet ) are related to each other.
Null hypothesis:We start by defining the null hypothesis (H0) which states that there is no relation between the variables. An alternate hypothesis would state that there is a significant relation between the two.
We can verify the hypothesis by these methods:
Using p-value:
We define a significance factor to determine whether the relation between the variables is of considerable significance. Generally a significance factor or alpha value of 0.05 is chosen. This alpha value denotes the probability of erroneously rejecting H0 when it is true. A lower alpha value is chosen in cases where we expect more precision. If the p-value for the test comes out to be strictly greater than the alpha value, then H0 holds true.
Using chi-square value:
If our calculated value of chi-square is less or equal to the tabular(also called critical) value of chi-square, then H0 holds true.
Expected Values Table :
Next, we prepare a similar table of calculated(or expected) values. To do this we need to calculate each item in the new table as :
Chi-Square Table :
We prepare this table by calculating for each item the following:
From this table, we obtain the total of the last column, which gives us the calculated value of chi-square. Hence the calculated value of chi-square is 4.542228269825232
Now, we need to find the critical value of chi-square. We can obtain this from a table. To use this table, we need to know the degrees of freedom for the dataset. The degrees of freedom is defined as : (no. of rows β 1) * (no. of columns β 1).Hence, the degrees of freedom is (2-1) * (3-1) = 2
Now, let us look at the table and find the value corresponding to 2 degrees of freedom and 0.05 significance factor :
Hence,
Next, let us see how to perform the test in Python.
Performing the test using Python (scipy.stats) :
SciPy is an Open Source Python library, which is used in mathematics, engineering, scientific and technical computing.
Installation:
pip install scipy
The chi2_contingency() function of scipy.stats module takes as input, the contingency table in 2d array format. It returns a tuple containing test statistics, the p-value, degrees of freedom and expected table(the one we created from the calculated values) in that order.
Hence, we need to compare the obtained p-value with alpha value of 0.05.
from scipy.stats import chi2_contingency # defining the tabledata = [[207, 282, 241], [234, 242, 232]]stat, p, dof, expected = chi2_contingency(data) # interpret p-valuealpha = 0.05print("p value is " + str(p))if p <= alpha: print('Dependent (reject H0)')else: print('Independent (H0 holds true)')
Output :
p value is 0.1031971404730939
Independent (H0 holds true)
Since,
p-value > alpha
Therefore, we accept H0, that is, the variables do not have a significant relation.
data-science
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Search Algorithms in AI
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Introduction to Recurrent Neural Network
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": 53,
"s": 25,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 314,
"s": 53,
"text": "The Pearsonβs Chi-Square statistical hypothesis is a test for independence between categorical variables. In this article, we will perform the test using a mathematical approach and then using Pythonβs SciPy module.First, let us see the mathematical approach :"
},
{
"code": null,
"e": 564,
"s": 314,
"text": "The Contingency Table :A Contingency table (also called crosstab) is used in statistics to summarise the relationship between several categorical variables. Here, we take a table that shows the number of men and women buying different types of pets."
},
{
"code": null,
"e": 680,
"s": 564,
"text": "The aim of the test is to conclude whether the two variables( gender and choice of pet ) are related to each other."
},
{
"code": null,
"e": 894,
"s": 680,
"text": "Null hypothesis:We start by defining the null hypothesis (H0) which states that there is no relation between the variables. An alternate hypothesis would state that there is a significant relation between the two."
},
{
"code": null,
"e": 941,
"s": 894,
"text": "We can verify the hypothesis by these methods:"
},
{
"code": null,
"e": 956,
"s": 941,
"text": "Using p-value:"
},
{
"code": null,
"e": 1403,
"s": 956,
"text": "We define a significance factor to determine whether the relation between the variables is of considerable significance. Generally a significance factor or alpha value of 0.05 is chosen. This alpha value denotes the probability of erroneously rejecting H0 when it is true. A lower alpha value is chosen in cases where we expect more precision. If the p-value for the test comes out to be strictly greater than the alpha value, then H0 holds true."
},
{
"code": null,
"e": 1427,
"s": 1403,
"text": "Using chi-square value:"
},
{
"code": null,
"e": 1560,
"s": 1427,
"text": "If our calculated value of chi-square is less or equal to the tabular(also called critical) value of chi-square, then H0 holds true."
},
{
"code": null,
"e": 1584,
"s": 1560,
"text": "Expected Values Table :"
},
{
"code": null,
"e": 1716,
"s": 1584,
"text": "Next, we prepare a similar table of calculated(or expected) values. To do this we need to calculate each item in the new table as :"
},
{
"code": null,
"e": 1735,
"s": 1716,
"text": "Chi-Square Table :"
},
{
"code": null,
"e": 1801,
"s": 1735,
"text": "We prepare this table by calculating for each item the following:"
},
{
"code": null,
"e": 1972,
"s": 1801,
"text": "From this table, we obtain the total of the last column, which gives us the calculated value of chi-square. Hence the calculated value of chi-square is 4.542228269825232"
},
{
"code": null,
"e": 2267,
"s": 1972,
"text": "Now, we need to find the critical value of chi-square. We can obtain this from a table. To use this table, we need to know the degrees of freedom for the dataset. The degrees of freedom is defined as : (no. of rows β 1) * (no. of columns β 1).Hence, the degrees of freedom is (2-1) * (3-1) = 2"
},
{
"code": null,
"e": 2385,
"s": 2267,
"text": "Now, let us look at the table and find the value corresponding to 2 degrees of freedom and 0.05 significance factor :"
},
{
"code": null,
"e": 2392,
"s": 2385,
"text": "Hence,"
},
{
"code": null,
"e": 2444,
"s": 2392,
"text": "Next, let us see how to perform the test in Python."
},
{
"code": null,
"e": 2493,
"s": 2444,
"text": "Performing the test using Python (scipy.stats) :"
},
{
"code": null,
"e": 2613,
"s": 2493,
"text": "SciPy is an Open Source Python library, which is used in mathematics, engineering, scientific and technical computing. "
},
{
"code": null,
"e": 2627,
"s": 2613,
"text": "Installation:"
},
{
"code": null,
"e": 2646,
"s": 2627,
"text": "pip install scipy\n"
},
{
"code": null,
"e": 2919,
"s": 2646,
"text": "The chi2_contingency() function of scipy.stats module takes as input, the contingency table in 2d array format. It returns a tuple containing test statistics, the p-value, degrees of freedom and expected table(the one we created from the calculated values) in that order. "
},
{
"code": null,
"e": 2992,
"s": 2919,
"text": "Hence, we need to compare the obtained p-value with alpha value of 0.05."
},
{
"code": "from scipy.stats import chi2_contingency # defining the tabledata = [[207, 282, 241], [234, 242, 232]]stat, p, dof, expected = chi2_contingency(data) # interpret p-valuealpha = 0.05print(\"p value is \" + str(p))if p <= alpha: print('Dependent (reject H0)')else: print('Independent (H0 holds true)')",
"e": 3298,
"s": 2992,
"text": null
},
{
"code": null,
"e": 3308,
"s": 3298,
"text": "Output : "
},
{
"code": null,
"e": 3367,
"s": 3308,
"text": "p value is 0.1031971404730939\nIndependent (H0 holds true)\n"
},
{
"code": null,
"e": 3374,
"s": 3367,
"text": "Since,"
},
{
"code": null,
"e": 3391,
"s": 3374,
"text": "p-value > alpha "
},
{
"code": null,
"e": 3475,
"s": 3391,
"text": "Therefore, we accept H0, that is, the variables do not have a significant relation."
},
{
"code": null,
"e": 3488,
"s": 3475,
"text": "data-science"
},
{
"code": null,
"e": 3505,
"s": 3488,
"text": "Machine Learning"
},
{
"code": null,
"e": 3512,
"s": 3505,
"text": "Python"
},
{
"code": null,
"e": 3529,
"s": 3512,
"text": "Machine Learning"
},
{
"code": null,
"e": 3627,
"s": 3529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3650,
"s": 3627,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 3674,
"s": 3650,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 3710,
"s": 3674,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 3734,
"s": 3710,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 3775,
"s": 3734,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 3803,
"s": 3775,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3853,
"s": 3803,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3875,
"s": 3853,
"text": "Python map() function"
}
]
|
Check for NaN in Pandas DataFrame | 02 Jul, 2020
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results.
The ways to check for NaN in Pandas DataFrame are as follows:
Check for NaN under a single DataFrame column:
Count the NaN under a single DataFrame column:
Check for NaN under the whole DataFrame:
Count the NaN under the whole DataFrame:
Method 1: Using isnull().values.any() methodExample:
Python3
# importing librariesimport pandas as pdimport numpy as np num = {'Integers': [10, 15, 30, 40, 55, np.nan, 75, np.nan, 90, 150, np.nan]} # Create the dataframedf = pd.DataFrame(num, columns=['Integers']) # Applying the methodcheck_nan = df['Integers'].isnull().values.any() # printing the resultprint(check_nan)
Output:
It is also possible to to get the exact positions where NaN values are present. We can do so by removing .values.any() from isnull().values.any() .
Python3
check_nan = df['Integers'].isnull()
Output:
Method 2: Using isnull().sum() MethodExample:
Python3
# importing librariesimport pandas as pdimport numpy as np num = {'Integers': [10, 15, 30, 40, 55, np.nan, 75, np.nan, 90, 150, np.nan]} # Create the dataframedf = pd.DataFrame(num, columns=['Integers']) # applying the methodcount_nan = df['Integers'].isnull().sum() # printing the number of values present# in the columnprint('Number of NaN values present: ' + str(count_nan))
Output:
Method 3: Using isnull().values.any() Method
Example:
Python3
# importing librariesimport pandas as pdimport numpy as np nums = {'Integers_1': [10, 15, 30, 40, 55, np.nan, 75, np.nan, 90, 150, np.nan], 'Integers_2': [np.nan, 21, 22, 23, np.nan, 24, 25, np.nan, 26, np.nan, np.nan]} # Create the dataframedf = pd.DataFrame(nums, columns=['Integers_1', 'Integers_2']) # applying the methodnan_in_df = df.isnull().values.any() # Print the dataframeprint(nan_in_df)
Output:
To get the exact positions where NaN values are present, we can do so by removing .values.any() from isnull().values.any() .
Method 4: Using isnull().sum().sum() MethodExample:
Python3
# importing librariesimport pandas as pdimport numpy as np nums = {'Integers_1': [10, 15, 30, 40, 55, np.nan, 75, np.nan, 90, 150, np.nan], 'Integers_2': [np.nan, 21, 22, 23, np.nan, 24, 25, np.nan, 26, np.nan, np.nan]} # Create the dataframedf = pd.DataFrame(nums, columns=['Integers_1', 'Integers_2']) # applying the methodnan_in_df = df.isnull().sum().sum() # printing the number of values present in# the whole dataframeprint('Number of NaN values present: ' + str(nan_in_df))
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Read a file line by line in Python
Defaultdict in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 354,
"s": 28,
"text": "NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results. "
},
{
"code": null,
"e": 417,
"s": 354,
"text": "The ways to check for NaN in Pandas DataFrame are as follows: "
},
{
"code": null,
"e": 464,
"s": 417,
"text": "Check for NaN under a single DataFrame column:"
},
{
"code": null,
"e": 511,
"s": 464,
"text": "Count the NaN under a single DataFrame column:"
},
{
"code": null,
"e": 552,
"s": 511,
"text": "Check for NaN under the whole DataFrame:"
},
{
"code": null,
"e": 593,
"s": 552,
"text": "Count the NaN under the whole DataFrame:"
},
{
"code": null,
"e": 647,
"s": 593,
"text": "Method 1: Using isnull().values.any() methodExample: "
},
{
"code": null,
"e": 655,
"s": 647,
"text": "Python3"
},
{
"code": "# importing librariesimport pandas as pdimport numpy as np num = {'Integers': [10, 15, 30, 40, 55, np.nan, 75, np.nan, 90, 150, np.nan]} # Create the dataframedf = pd.DataFrame(num, columns=['Integers']) # Applying the methodcheck_nan = df['Integers'].isnull().values.any() # printing the resultprint(check_nan)",
"e": 992,
"s": 655,
"text": null
},
{
"code": null,
"e": 1001,
"s": 992,
"text": "Output: "
},
{
"code": null,
"e": 1150,
"s": 1001,
"text": "It is also possible to to get the exact positions where NaN values are present. We can do so by removing .values.any() from isnull().values.any() . "
},
{
"code": null,
"e": 1158,
"s": 1150,
"text": "Python3"
},
{
"code": "check_nan = df['Integers'].isnull()",
"e": 1194,
"s": 1158,
"text": null
},
{
"code": null,
"e": 1203,
"s": 1194,
"text": "Output: "
},
{
"code": null,
"e": 1250,
"s": 1203,
"text": "Method 2: Using isnull().sum() MethodExample: "
},
{
"code": null,
"e": 1258,
"s": 1250,
"text": "Python3"
},
{
"code": "# importing librariesimport pandas as pdimport numpy as np num = {'Integers': [10, 15, 30, 40, 55, np.nan, 75, np.nan, 90, 150, np.nan]} # Create the dataframedf = pd.DataFrame(num, columns=['Integers']) # applying the methodcount_nan = df['Integers'].isnull().sum() # printing the number of values present# in the columnprint('Number of NaN values present: ' + str(count_nan))",
"e": 1661,
"s": 1258,
"text": null
},
{
"code": null,
"e": 1669,
"s": 1661,
"text": "Output:"
},
{
"code": null,
"e": 1714,
"s": 1669,
"text": "Method 3: Using isnull().values.any() Method"
},
{
"code": null,
"e": 1724,
"s": 1714,
"text": "Example: "
},
{
"code": null,
"e": 1732,
"s": 1724,
"text": "Python3"
},
{
"code": "# importing librariesimport pandas as pdimport numpy as np nums = {'Integers_1': [10, 15, 30, 40, 55, np.nan, 75, np.nan, 90, 150, np.nan], 'Integers_2': [np.nan, 21, 22, 23, np.nan, 24, 25, np.nan, 26, np.nan, np.nan]} # Create the dataframedf = pd.DataFrame(nums, columns=['Integers_1', 'Integers_2']) # applying the methodnan_in_df = df.isnull().values.any() # Print the dataframeprint(nan_in_df)",
"e": 2187,
"s": 1732,
"text": null
},
{
"code": null,
"e": 2196,
"s": 2187,
"text": "Output: "
},
{
"code": null,
"e": 2322,
"s": 2196,
"text": "To get the exact positions where NaN values are present, we can do so by removing .values.any() from isnull().values.any() . "
},
{
"code": null,
"e": 2375,
"s": 2322,
"text": "Method 4: Using isnull().sum().sum() MethodExample: "
},
{
"code": null,
"e": 2383,
"s": 2375,
"text": "Python3"
},
{
"code": "# importing librariesimport pandas as pdimport numpy as np nums = {'Integers_1': [10, 15, 30, 40, 55, np.nan, 75, np.nan, 90, 150, np.nan], 'Integers_2': [np.nan, 21, 22, 23, np.nan, 24, 25, np.nan, 26, np.nan, np.nan]} # Create the dataframedf = pd.DataFrame(nums, columns=['Integers_1', 'Integers_2']) # applying the methodnan_in_df = df.isnull().sum().sum() # printing the number of values present in# the whole dataframeprint('Number of NaN values present: ' + str(nan_in_df))",
"e": 2919,
"s": 2383,
"text": null
},
{
"code": null,
"e": 2927,
"s": 2919,
"text": "Output:"
},
{
"code": null,
"e": 2951,
"s": 2927,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2965,
"s": 2951,
"text": "Python-pandas"
},
{
"code": null,
"e": 2972,
"s": 2965,
"text": "Python"
},
{
"code": null,
"e": 3070,
"s": 2972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3100,
"s": 3070,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3145,
"s": 3100,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3167,
"s": 3145,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3217,
"s": 3167,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 3235,
"s": 3217,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3251,
"s": 3235,
"text": "Deque in Python"
},
{
"code": null,
"e": 3267,
"s": 3251,
"text": "Stack in Python"
},
{
"code": null,
"e": 3283,
"s": 3267,
"text": "Queue in Python"
},
{
"code": null,
"e": 3318,
"s": 3283,
"text": "Read a file line by line in Python"
}
]
|
Selenium Webdriver - Double Click | Selenium can perform mouse movements, key press, hovering on an element, double click, drag and drop actions, and so on with the help of the ActionsChains class. The method double_click performs double-click on an element.
The syntax for using the double click is as follows:
double_click(e=None)
Here, e is the element to be double-clicked. If None is mentioned, the click is performed on the present mouse position. We have to add the statement from selenium.webdriver import ActionChains to work with the ActionChains class.
Let us perform the double click on the below element β
In the above image, it is seen that on double clicking the Double Click me! button, an alert box gets generated.
The code implementation for using the double click is as follows β
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.alert import Alert
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(5)
#url launch
driver.get("http://www.uitestpractice.com/Students/Actions")
#identify element
s = driver.find_element_by_name("dblClick")
#object of ActionChains
a = ActionChains(driver)
#right click then perform
a.double_click(s).perform()
#switch to alert
alrt = Alert(driver)
# get alert text
print(alrt.text)
#accept alert
alrt.accept()
#driver quit
driver.quit()
The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the Alert text - Double Clicked! gets printed in the console. The Alert got generated by double clicking the Double Click me! button.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2426,
"s": 2203,
"text": "Selenium can perform mouse movements, key press, hovering on an element, double click, drag and drop actions, and so on with the help of the ActionsChains class. The method double_click performs double-click on an element."
},
{
"code": null,
"e": 2479,
"s": 2426,
"text": "The syntax for using the double click is as follows:"
},
{
"code": null,
"e": 2501,
"s": 2479,
"text": "double_click(e=None)\n"
},
{
"code": null,
"e": 2732,
"s": 2501,
"text": "Here, e is the element to be double-clicked. If None is mentioned, the click is performed on the present mouse position. We have to add the statement from selenium.webdriver import ActionChains to work with the ActionChains class."
},
{
"code": null,
"e": 2787,
"s": 2732,
"text": "Let us perform the double click on the below element β"
},
{
"code": null,
"e": 2900,
"s": 2787,
"text": "In the above image, it is seen that on double clicking the Double Click me! button, an alert box gets generated."
},
{
"code": null,
"e": 2967,
"s": 2900,
"text": "The code implementation for using the double click is as follows β"
},
{
"code": null,
"e": 3572,
"s": 2967,
"text": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.alert import Alert\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"http://www.uitestpractice.com/Students/Actions\")\n#identify element\ns = driver.find_element_by_name(\"dblClick\")\n#object of ActionChains\na = ActionChains(driver)\n#right click then perform\na.double_click(s).perform()\n#switch to alert\nalrt = Alert(driver)\n# get alert text\nprint(alrt.text)\n#accept alert\nalrt.accept()\n#driver quit\ndriver.quit()"
},
{
"code": null,
"e": 3826,
"s": 3572,
"text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the Alert text - Double Clicked! gets printed in the console. The Alert got generated by double clicking the Double Click me! button."
},
{
"code": null,
"e": 3861,
"s": 3826,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3873,
"s": 3861,
"text": " Aditya Dua"
},
{
"code": null,
"e": 3909,
"s": 3873,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 3923,
"s": 3909,
"text": " Arun Motoori"
},
{
"code": null,
"e": 3960,
"s": 3923,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 3982,
"s": 3960,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4015,
"s": 3982,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4029,
"s": 4015,
"text": " Arun Motoori"
},
{
"code": null,
"e": 4064,
"s": 4029,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 4078,
"s": 4064,
"text": " Arun Motoori"
},
{
"code": null,
"e": 4115,
"s": 4078,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 4129,
"s": 4115,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4136,
"s": 4129,
"text": " Print"
},
{
"code": null,
"e": 4147,
"s": 4136,
"text": " Add Notes"
}
]
|
How To Build a Basic Chatbot from Scratch | by Pratheesh Shivaprasad | Towards Data Science | Be it a Whatsapp chat, Telegram group, Slack channel, or any product website, Iβm sure you have encountered one of these bots popping out of nowhere. You ask some questions and it will try itβs best to resolve your queries. Today weβll try to build a chatbot that could respond to some basic queries and respond in real-time.
Let us just assume that weβll be building a chatbot for a restaurant. Our client has certain requirements for the chatbot.
The bot should be able to:
Greet the visitors on the website.Book seats.Show available seats.Show whatβs on the menu.Show the working hours.Show contact information.Show the location of the restaurant.
Greet the visitors on the website.
Book seats.
Show available seats.
Show whatβs on the menu.
Show the working hours.
Show contact information.
Show the location of the restaurant.
In the end, our chatbot will look like this:
If you have a basic understanding of Natural Language Processing (NLP), Fully Connected layers in Deep Learning, and Flask framework, this project will be a breeze for you. Even if you arenβt familiar with these terms Iβll try my best to explain everything in simple language and link helpful resources wherever possible.
With that being said, let's start building our chatbot.
Now itβs time to see what kind of data weβre dealing with here. The data required for building a chatbot is a little different than the conventional datasets we tend to see. Every intelligent machine needs data that it can see and interpret. We wonβt be downloading any particular dataset for this project. We already have a small set of data. Letβs have a look at it.
This is an example of how our data looks like. It is a JSON format file that is normally used to store and transmit data. The three important terms to be noted here are βtagβ, βpatternsβ and βresponsesβ.
Whatever queries a user enters for the chatbot to interpret must be included in βpatternsβ.
After interpreting the userβs query, the chatbot will have to reply to the query and this reply will be randomly selected from the set of predefined replies in βresponsesβ.
The βtagβ groups a set of similar patterns and responses to a specific category so that itβll be easier for the model to predict which category a particular pattern represents.
You can now copy the data given below into a file. I have named my file βintents.jsonβ.
As you can see the data provided here meets all of the requirements given by our client. I have intentionally set the responses of the tags βmenuβ, βbook_tableβ and βavailable_tablesβ as an empty list. Iβll explain the reason later in our project.
With this data, we can now train our own neural network and it will predict and try to classify it into one of the tags from the file. Once the tag is known, a random response will be selected from that tag and shown to the user. You can add any other tags you wish to this data. Just make sure that the syntax isnβt wrong. The more tags, patterns, and responses you provide, the more robust the chatbot will be.
Now that you're familiar with the data letβs load it onto the kernel using Python. The version that Iβm using is Python 3.6.
Before starting with any code, itβs recommended to set up a virtual environment so that any libraries weβll be installing won't clash with existing ones or cause any redundancy issues.
Iβll be creating a virtual environment using conda. (See here on how to install Anaconda.)
Open your command prompt and enter the command.
conda create -n simple_chatbot python=3.6
Here βsimple_chatbotβ is the name of the virtual environment. You can give it any name you like.
To activate this virtual environment, just enter:
conda activate simple_chatbot
Once activated, the name of your environment should show up on the left something like this:
Weβll be using pip to install the following libraries:
numpy==1.16.5
nltk==3.4.5
tensorflow==1.13.2
tflearn==0.3.2
flask==1.1.1
I have also added the version of the libraries just to be safe.
pip install packagename==version //Enter packages mentioned above
Now that weβre prepped up, let's dive into the code.
Now weβll be importing some libraries needed to load, process, and transform our data and then feed it into a deep learning network. Just remember to keep your JSON file in the same directory as your python file. Iβll be naming my file βmain.pyβ.
Now, we have to take the βtagβ and βpatternsβ out of the file and store it in a list. Weβll also make a collection of unique words in the patterns to create a Bag of Words (BoW) vector.
In the code above, we have created four empty lists.
words: Holds a list of unique words.labels: Holds a list of all the unique tags in the file.docs_x: Holds a list of patterns.docs_y: Holds a list of tags corresponding to the pattern in docs_x.
words: Holds a list of unique words.
labels: Holds a list of all the unique tags in the file.
docs_x: Holds a list of patterns.
docs_y: Holds a list of tags corresponding to the pattern in docs_x.
As we loop through the data, we convert all patterns into lower case, tokenize each pattern and then add them to the respective lists. We also add the patternβs tag into docs_y simultaneously.
Now that weβve got the words in a list, itβs time to perform stemming on them. Stemming is basically trying to find the root origin of a word. It removes all the prefixes and suffixes of a word so that the model that weβre building will get a general idea of that word instead of getting trapped in all the intricacies of the same word with different forms. There are different types of stemmers like Porter Stemmer, Snowball Stemmer, Lancaster Stemmer, etc. Weβll be using Lancaster Stemmer in our code. (Learn more about Stemmers here.)
Itβs known that Machine Learning and Deep Learning models only accept numerical inputs. So we have to convert this stemmed list of words into some kind of numerical input so that we can feed it to the neural network. This is where vectorization methods like Bag of Words, TF-IDF, Word2vec, and others come into the picture.
Weβll be using Bag of Words (BoW) in our code. It basically describes the occurrence of a word within a document. In our case, weβll be representing each sentence with a list of the length of all unique words collected in the list βwordsβ. Each position in that list will be a unique word from βwordsβ. If a sentence consists of a specific word, their position will be marked as 1 and if a word is not present in that position, itβll be marked as 0.
With this method though, the model can only understand the occurrence of a word in the sentence. The sequence of the words within the sentence will be lost, hence the name βBag of Wordsβ. Other methods like TF-IDF, Word2Vec tries to capture some of these lost semantics in their own way. Iβd recommend you to try out other vectorization methods as well.
Similarly, for the output, weβll create a list which will be the length of the labels/tags we have in our JSON file. A β1β in any of those positions indicates the belonging of a pattern in that particular label/tag.
We will be also saving all the processed data in a pickle file so that it can be used later for processing inputs from the user as well.
Now that weβre done with data preprocessing, itβs time to build a model and feed our preprocessed data to it. The network architecture is not too complicated. We will be using Fully Connected Layers (FC layers) with two of them being hidden layers and one giving out the target probabilities. Hence, the last layer will be having a softmax activation.
Feel free to mess around with the architecture and the numbers to get the model that suits your requirements. You could also choose to add a bit more steps into text preprocessing to get more out of the data. The more trial and error cycles you perform better will be your understanding of the architecture.
All we have to do now is feed the data to this model and begin training. We will set our epochs to 200 and batch size to 8. Again, you can experiment with these numbers and find the right one for your data. After training, we will be saving it on the disk so that we can use the trained model in our Flask application.
If everything goes right, you should have files named βmodel.tflearn.dataβ, βmodel.tflearn.indexβ, and βmodel.tflearn.metaβ in the working directory.
Your βmain.pyβ file should look something like this:
Now that weβve trained our deep learning model, itβs time to integrate it into a web application. The framework we will be using here is Flask. Now explaining how to build a Flask application requires a series of articles on its own so I wonβt be doing that here. However, Iβll make sure to include all the resources I referred to while building this application in the βReferencesβ section down below.
Hereβs a link to my GitHub repository where you can access all the files to build the Flask application. Iβd recommend you to copy all the files into your working directory so that it can access the trained model and pickle files.
We will be using AJAX for asynchronous transfer of data i.e you wonβt have to reload your webpage every time you send an input to the model. The web application will respond to your inputs seamlessly. Letβs take a look at the HTML file.
Have a look at the JavaScript section where we get the input from the user, sends it to the βapp.pyβ file where itβs fed to the trained model and then receives the output back to display it on the app.
The βapp.pyβ file is where all the routes are mentioned, input data is processed (Stemming and Bag of Words), and fed to the model for output. Letβs have a look at it.
We first import all the required libraries and then load the pickle file in which we saved the preprocessed data. This will be required to create a BoW vector for the input data. Then we define a function βbag_of_wordsβ where we provide user input and get a BoW vector as an output.
Remember the tags βmenuβ, βbook_tableβ and βavailable_tablesβ with empty responses? We did that so we could provide custom responses to questions in those tags.
For the questions related to whatβs on the menu, we would first check what day of the week it is and according to that, the chatbot will recommend special dishes for the day.
When the user asks to book a table, we decrement the counter βseat_countβ by one. Now, of course, this isnβt how bookings work but the whole point of demonstrating this was to show the possibilities we can have with this chatbot. You could connect this bot to a database and conduct bookings accordingly. Or you could add any other additional tasks according to your requirements. Asking for available tables just shows the current value of βseat_countβ. Whenever you reset the Flask server, the counter goes back to 50. This was done to show that you donβt have to always depend on the JSON file for a response.
Once the setup is complete, just run the βapp.pyβ file and the Flask server will be live. It should look something like this:
The project is finally done and working like itβs supposed to. However, there are tons of stuff you can tweak and fine-tune in here. Iβd love to hear what additional features you were able to add to this chatbot or any other modifications you have made to this project. You can go ahead and connect this chatbot to a database or integrate it with any website. Instead of using Bag of Words, you could also use other vectorization methods like TF-IDF, Word2Vec, etc. There is a high chance that these methods will improve the modelβs accuracy in predicting the tags.
As promised I have also listed all the blogs and videos I referred to while building this application. Itβll definitely help you get a deeper understanding of the project and its working.
Contextual Chatbots with TensorflowFlask Tutorials by Corey SchaferBuilding a Chatbot in Python Using FlaskSubmit AJAX Forms with jQuery and Flask
Contextual Chatbots with Tensorflow
Flask Tutorials by Corey Schafer
Building a Chatbot in Python Using Flask
Submit AJAX Forms with jQuery and Flask | [
{
"code": null,
"e": 498,
"s": 172,
"text": "Be it a Whatsapp chat, Telegram group, Slack channel, or any product website, Iβm sure you have encountered one of these bots popping out of nowhere. You ask some questions and it will try itβs best to resolve your queries. Today weβll try to build a chatbot that could respond to some basic queries and respond in real-time."
},
{
"code": null,
"e": 621,
"s": 498,
"text": "Let us just assume that weβll be building a chatbot for a restaurant. Our client has certain requirements for the chatbot."
},
{
"code": null,
"e": 648,
"s": 621,
"text": "The bot should be able to:"
},
{
"code": null,
"e": 823,
"s": 648,
"text": "Greet the visitors on the website.Book seats.Show available seats.Show whatβs on the menu.Show the working hours.Show contact information.Show the location of the restaurant."
},
{
"code": null,
"e": 858,
"s": 823,
"text": "Greet the visitors on the website."
},
{
"code": null,
"e": 870,
"s": 858,
"text": "Book seats."
},
{
"code": null,
"e": 892,
"s": 870,
"text": "Show available seats."
},
{
"code": null,
"e": 917,
"s": 892,
"text": "Show whatβs on the menu."
},
{
"code": null,
"e": 941,
"s": 917,
"text": "Show the working hours."
},
{
"code": null,
"e": 967,
"s": 941,
"text": "Show contact information."
},
{
"code": null,
"e": 1004,
"s": 967,
"text": "Show the location of the restaurant."
},
{
"code": null,
"e": 1049,
"s": 1004,
"text": "In the end, our chatbot will look like this:"
},
{
"code": null,
"e": 1371,
"s": 1049,
"text": "If you have a basic understanding of Natural Language Processing (NLP), Fully Connected layers in Deep Learning, and Flask framework, this project will be a breeze for you. Even if you arenβt familiar with these terms Iβll try my best to explain everything in simple language and link helpful resources wherever possible."
},
{
"code": null,
"e": 1427,
"s": 1371,
"text": "With that being said, let's start building our chatbot."
},
{
"code": null,
"e": 1796,
"s": 1427,
"text": "Now itβs time to see what kind of data weβre dealing with here. The data required for building a chatbot is a little different than the conventional datasets we tend to see. Every intelligent machine needs data that it can see and interpret. We wonβt be downloading any particular dataset for this project. We already have a small set of data. Letβs have a look at it."
},
{
"code": null,
"e": 2000,
"s": 1796,
"text": "This is an example of how our data looks like. It is a JSON format file that is normally used to store and transmit data. The three important terms to be noted here are βtagβ, βpatternsβ and βresponsesβ."
},
{
"code": null,
"e": 2092,
"s": 2000,
"text": "Whatever queries a user enters for the chatbot to interpret must be included in βpatternsβ."
},
{
"code": null,
"e": 2265,
"s": 2092,
"text": "After interpreting the userβs query, the chatbot will have to reply to the query and this reply will be randomly selected from the set of predefined replies in βresponsesβ."
},
{
"code": null,
"e": 2442,
"s": 2265,
"text": "The βtagβ groups a set of similar patterns and responses to a specific category so that itβll be easier for the model to predict which category a particular pattern represents."
},
{
"code": null,
"e": 2530,
"s": 2442,
"text": "You can now copy the data given below into a file. I have named my file βintents.jsonβ."
},
{
"code": null,
"e": 2778,
"s": 2530,
"text": "As you can see the data provided here meets all of the requirements given by our client. I have intentionally set the responses of the tags βmenuβ, βbook_tableβ and βavailable_tablesβ as an empty list. Iβll explain the reason later in our project."
},
{
"code": null,
"e": 3191,
"s": 2778,
"text": "With this data, we can now train our own neural network and it will predict and try to classify it into one of the tags from the file. Once the tag is known, a random response will be selected from that tag and shown to the user. You can add any other tags you wish to this data. Just make sure that the syntax isnβt wrong. The more tags, patterns, and responses you provide, the more robust the chatbot will be."
},
{
"code": null,
"e": 3316,
"s": 3191,
"text": "Now that you're familiar with the data letβs load it onto the kernel using Python. The version that Iβm using is Python 3.6."
},
{
"code": null,
"e": 3501,
"s": 3316,
"text": "Before starting with any code, itβs recommended to set up a virtual environment so that any libraries weβll be installing won't clash with existing ones or cause any redundancy issues."
},
{
"code": null,
"e": 3592,
"s": 3501,
"text": "Iβll be creating a virtual environment using conda. (See here on how to install Anaconda.)"
},
{
"code": null,
"e": 3640,
"s": 3592,
"text": "Open your command prompt and enter the command."
},
{
"code": null,
"e": 3682,
"s": 3640,
"text": "conda create -n simple_chatbot python=3.6"
},
{
"code": null,
"e": 3779,
"s": 3682,
"text": "Here βsimple_chatbotβ is the name of the virtual environment. You can give it any name you like."
},
{
"code": null,
"e": 3829,
"s": 3779,
"text": "To activate this virtual environment, just enter:"
},
{
"code": null,
"e": 3859,
"s": 3829,
"text": "conda activate simple_chatbot"
},
{
"code": null,
"e": 3952,
"s": 3859,
"text": "Once activated, the name of your environment should show up on the left something like this:"
},
{
"code": null,
"e": 4007,
"s": 3952,
"text": "Weβll be using pip to install the following libraries:"
},
{
"code": null,
"e": 4021,
"s": 4007,
"text": "numpy==1.16.5"
},
{
"code": null,
"e": 4033,
"s": 4021,
"text": "nltk==3.4.5"
},
{
"code": null,
"e": 4052,
"s": 4033,
"text": "tensorflow==1.13.2"
},
{
"code": null,
"e": 4067,
"s": 4052,
"text": "tflearn==0.3.2"
},
{
"code": null,
"e": 4080,
"s": 4067,
"text": "flask==1.1.1"
},
{
"code": null,
"e": 4144,
"s": 4080,
"text": "I have also added the version of the libraries just to be safe."
},
{
"code": null,
"e": 4210,
"s": 4144,
"text": "pip install packagename==version //Enter packages mentioned above"
},
{
"code": null,
"e": 4263,
"s": 4210,
"text": "Now that weβre prepped up, let's dive into the code."
},
{
"code": null,
"e": 4510,
"s": 4263,
"text": "Now weβll be importing some libraries needed to load, process, and transform our data and then feed it into a deep learning network. Just remember to keep your JSON file in the same directory as your python file. Iβll be naming my file βmain.pyβ."
},
{
"code": null,
"e": 4696,
"s": 4510,
"text": "Now, we have to take the βtagβ and βpatternsβ out of the file and store it in a list. Weβll also make a collection of unique words in the patterns to create a Bag of Words (BoW) vector."
},
{
"code": null,
"e": 4749,
"s": 4696,
"text": "In the code above, we have created four empty lists."
},
{
"code": null,
"e": 4943,
"s": 4749,
"text": "words: Holds a list of unique words.labels: Holds a list of all the unique tags in the file.docs_x: Holds a list of patterns.docs_y: Holds a list of tags corresponding to the pattern in docs_x."
},
{
"code": null,
"e": 4980,
"s": 4943,
"text": "words: Holds a list of unique words."
},
{
"code": null,
"e": 5037,
"s": 4980,
"text": "labels: Holds a list of all the unique tags in the file."
},
{
"code": null,
"e": 5071,
"s": 5037,
"text": "docs_x: Holds a list of patterns."
},
{
"code": null,
"e": 5140,
"s": 5071,
"text": "docs_y: Holds a list of tags corresponding to the pattern in docs_x."
},
{
"code": null,
"e": 5333,
"s": 5140,
"text": "As we loop through the data, we convert all patterns into lower case, tokenize each pattern and then add them to the respective lists. We also add the patternβs tag into docs_y simultaneously."
},
{
"code": null,
"e": 5872,
"s": 5333,
"text": "Now that weβve got the words in a list, itβs time to perform stemming on them. Stemming is basically trying to find the root origin of a word. It removes all the prefixes and suffixes of a word so that the model that weβre building will get a general idea of that word instead of getting trapped in all the intricacies of the same word with different forms. There are different types of stemmers like Porter Stemmer, Snowball Stemmer, Lancaster Stemmer, etc. Weβll be using Lancaster Stemmer in our code. (Learn more about Stemmers here.)"
},
{
"code": null,
"e": 6196,
"s": 5872,
"text": "Itβs known that Machine Learning and Deep Learning models only accept numerical inputs. So we have to convert this stemmed list of words into some kind of numerical input so that we can feed it to the neural network. This is where vectorization methods like Bag of Words, TF-IDF, Word2vec, and others come into the picture."
},
{
"code": null,
"e": 6646,
"s": 6196,
"text": "Weβll be using Bag of Words (BoW) in our code. It basically describes the occurrence of a word within a document. In our case, weβll be representing each sentence with a list of the length of all unique words collected in the list βwordsβ. Each position in that list will be a unique word from βwordsβ. If a sentence consists of a specific word, their position will be marked as 1 and if a word is not present in that position, itβll be marked as 0."
},
{
"code": null,
"e": 7000,
"s": 6646,
"text": "With this method though, the model can only understand the occurrence of a word in the sentence. The sequence of the words within the sentence will be lost, hence the name βBag of Wordsβ. Other methods like TF-IDF, Word2Vec tries to capture some of these lost semantics in their own way. Iβd recommend you to try out other vectorization methods as well."
},
{
"code": null,
"e": 7216,
"s": 7000,
"text": "Similarly, for the output, weβll create a list which will be the length of the labels/tags we have in our JSON file. A β1β in any of those positions indicates the belonging of a pattern in that particular label/tag."
},
{
"code": null,
"e": 7353,
"s": 7216,
"text": "We will be also saving all the processed data in a pickle file so that it can be used later for processing inputs from the user as well."
},
{
"code": null,
"e": 7705,
"s": 7353,
"text": "Now that weβre done with data preprocessing, itβs time to build a model and feed our preprocessed data to it. The network architecture is not too complicated. We will be using Fully Connected Layers (FC layers) with two of them being hidden layers and one giving out the target probabilities. Hence, the last layer will be having a softmax activation."
},
{
"code": null,
"e": 8013,
"s": 7705,
"text": "Feel free to mess around with the architecture and the numbers to get the model that suits your requirements. You could also choose to add a bit more steps into text preprocessing to get more out of the data. The more trial and error cycles you perform better will be your understanding of the architecture."
},
{
"code": null,
"e": 8332,
"s": 8013,
"text": "All we have to do now is feed the data to this model and begin training. We will set our epochs to 200 and batch size to 8. Again, you can experiment with these numbers and find the right one for your data. After training, we will be saving it on the disk so that we can use the trained model in our Flask application."
},
{
"code": null,
"e": 8482,
"s": 8332,
"text": "If everything goes right, you should have files named βmodel.tflearn.dataβ, βmodel.tflearn.indexβ, and βmodel.tflearn.metaβ in the working directory."
},
{
"code": null,
"e": 8535,
"s": 8482,
"text": "Your βmain.pyβ file should look something like this:"
},
{
"code": null,
"e": 8938,
"s": 8535,
"text": "Now that weβve trained our deep learning model, itβs time to integrate it into a web application. The framework we will be using here is Flask. Now explaining how to build a Flask application requires a series of articles on its own so I wonβt be doing that here. However, Iβll make sure to include all the resources I referred to while building this application in the βReferencesβ section down below."
},
{
"code": null,
"e": 9169,
"s": 8938,
"text": "Hereβs a link to my GitHub repository where you can access all the files to build the Flask application. Iβd recommend you to copy all the files into your working directory so that it can access the trained model and pickle files."
},
{
"code": null,
"e": 9406,
"s": 9169,
"text": "We will be using AJAX for asynchronous transfer of data i.e you wonβt have to reload your webpage every time you send an input to the model. The web application will respond to your inputs seamlessly. Letβs take a look at the HTML file."
},
{
"code": null,
"e": 9608,
"s": 9406,
"text": "Have a look at the JavaScript section where we get the input from the user, sends it to the βapp.pyβ file where itβs fed to the trained model and then receives the output back to display it on the app."
},
{
"code": null,
"e": 9776,
"s": 9608,
"text": "The βapp.pyβ file is where all the routes are mentioned, input data is processed (Stemming and Bag of Words), and fed to the model for output. Letβs have a look at it."
},
{
"code": null,
"e": 10059,
"s": 9776,
"text": "We first import all the required libraries and then load the pickle file in which we saved the preprocessed data. This will be required to create a BoW vector for the input data. Then we define a function βbag_of_wordsβ where we provide user input and get a BoW vector as an output."
},
{
"code": null,
"e": 10220,
"s": 10059,
"text": "Remember the tags βmenuβ, βbook_tableβ and βavailable_tablesβ with empty responses? We did that so we could provide custom responses to questions in those tags."
},
{
"code": null,
"e": 10395,
"s": 10220,
"text": "For the questions related to whatβs on the menu, we would first check what day of the week it is and according to that, the chatbot will recommend special dishes for the day."
},
{
"code": null,
"e": 11008,
"s": 10395,
"text": "When the user asks to book a table, we decrement the counter βseat_countβ by one. Now, of course, this isnβt how bookings work but the whole point of demonstrating this was to show the possibilities we can have with this chatbot. You could connect this bot to a database and conduct bookings accordingly. Or you could add any other additional tasks according to your requirements. Asking for available tables just shows the current value of βseat_countβ. Whenever you reset the Flask server, the counter goes back to 50. This was done to show that you donβt have to always depend on the JSON file for a response."
},
{
"code": null,
"e": 11134,
"s": 11008,
"text": "Once the setup is complete, just run the βapp.pyβ file and the Flask server will be live. It should look something like this:"
},
{
"code": null,
"e": 11700,
"s": 11134,
"text": "The project is finally done and working like itβs supposed to. However, there are tons of stuff you can tweak and fine-tune in here. Iβd love to hear what additional features you were able to add to this chatbot or any other modifications you have made to this project. You can go ahead and connect this chatbot to a database or integrate it with any website. Instead of using Bag of Words, you could also use other vectorization methods like TF-IDF, Word2Vec, etc. There is a high chance that these methods will improve the modelβs accuracy in predicting the tags."
},
{
"code": null,
"e": 11888,
"s": 11700,
"text": "As promised I have also listed all the blogs and videos I referred to while building this application. Itβll definitely help you get a deeper understanding of the project and its working."
},
{
"code": null,
"e": 12035,
"s": 11888,
"text": "Contextual Chatbots with TensorflowFlask Tutorials by Corey SchaferBuilding a Chatbot in Python Using FlaskSubmit AJAX Forms with jQuery and Flask"
},
{
"code": null,
"e": 12071,
"s": 12035,
"text": "Contextual Chatbots with Tensorflow"
},
{
"code": null,
"e": 12104,
"s": 12071,
"text": "Flask Tutorials by Corey Schafer"
},
{
"code": null,
"e": 12145,
"s": 12104,
"text": "Building a Chatbot in Python Using Flask"
}
]
|
How to get the complete screenshot of a page in Selenium with python? | We can get the complete screenshot of a page in Selenium. While
executing any test cases, we might encounter failures. To keep track of the failures
we capture a screenshot of the web page where the error exists.
In a test case, there may be failure for reasons listed below β
If the assertion does not pass.
If there are sync issues between our application and Selenium.
If there are timeout issues.
If an alert appears in between.
If the element cannot be identified with the locators.
If the actual and final results are not matching.
For capturing the screenshot, save_screenshot() method is available. This method
takes the full page screenshot.
driver.save_screenshot("screenshot_t.png")
In the arguments, we have to provide the screenshot file name along with the
extension of .png. If anything else is used as extension, a warning message will be
thrown and the image cannot be viewed.
The screenshot gets saved in the same path of the program.
Code Implementation for full page screenshot.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to get the screenshot of complete page
driver.save_screenshot("screenshot_tutorialspoint.png")
#to close the browser
driver.close() | [
{
"code": null,
"e": 1275,
"s": 1062,
"text": "We can get the complete screenshot of a page in Selenium. While\nexecuting any test cases, we might encounter failures. To keep track of the failures\nwe capture a screenshot of the web page where the error exists."
},
{
"code": null,
"e": 1339,
"s": 1275,
"text": "In a test case, there may be failure for reasons listed below β"
},
{
"code": null,
"e": 1371,
"s": 1339,
"text": "If the assertion does not pass."
},
{
"code": null,
"e": 1434,
"s": 1371,
"text": "If there are sync issues between our application and Selenium."
},
{
"code": null,
"e": 1463,
"s": 1434,
"text": "If there are timeout issues."
},
{
"code": null,
"e": 1495,
"s": 1463,
"text": "If an alert appears in between."
},
{
"code": null,
"e": 1550,
"s": 1495,
"text": "If the element cannot be identified with the locators."
},
{
"code": null,
"e": 1600,
"s": 1550,
"text": "If the actual and final results are not matching."
},
{
"code": null,
"e": 1713,
"s": 1600,
"text": "For capturing the screenshot, save_screenshot() method is available. This method\ntakes the full page screenshot."
},
{
"code": null,
"e": 1756,
"s": 1713,
"text": "driver.save_screenshot(\"screenshot_t.png\")"
},
{
"code": null,
"e": 1956,
"s": 1756,
"text": "In the arguments, we have to provide the screenshot file name along with the\nextension of .png. If anything else is used as extension, a warning message will be\nthrown and the image cannot be viewed."
},
{
"code": null,
"e": 2015,
"s": 1956,
"text": "The screenshot gets saved in the same path of the program."
},
{
"code": null,
"e": 2061,
"s": 2015,
"text": "Code Implementation for full page screenshot."
},
{
"code": null,
"e": 2608,
"s": 2061,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n#to get the screenshot of complete page\ndriver.save_screenshot(\"screenshot_tutorialspoint.png\")\n#to close the browser\ndriver.close()"
}
]
|
Groupby without aggregation in Pandas - GeeksforGeeks | 29 Aug, 2021
Pandas is a great python package for manipulating data and some of the tools which we learn as a beginner are an aggregation and group by functions of pandas.
Groupby() is a function used to split the data in dataframe into groups based on a given condition. Aggregation on other hand operates on series, data and returns a numerical summary of the data. There are a lot of aggregation functions as count(),max(),min(),mean(),std(),describe(). We can combine both functions to find multiple aggregations on a particular column. For further details about this refer to this article How to combine Groupby and Multiple aggregation function in Pandas.
Instead of using groupby aggregation together, we can perform groupby without aggregation which is applicable to aggregate data separately. We will see this with an example where we will take a breast cancer dataset with different numerical features like mean area, worst texture, and many more. The target column has 0 which means the cancer is benign and 1 means the cancer is malignant.
Example 1:
Python3
# importing python libraries and breast_cancer dataset from sklearnimport numpy as npimport pandas as pdfrom sklearn import datasetsfrom sklearn.datasets import load_breast_cancer # data is loaded in a DataFramecancer_data = load_breast_cancer()df = pd.DataFrame(cancer_data.data, columns=cancer_data.feature_names)df['target'] = pd.Series(cancer_data.target)df.head()
Output:
Thus, we can visualize the data which have all the columns, but all the columns are in numerical form and there are no categorical data instead of only the target column, so letβs have a look in target and another column named βworst textureβ.
Python3
print(df['target'].describe(), df['worst texture'].describe())
Output:
count 569.000000
mean 0.627417
std 0.483918
min 0.000000
25% 0.000000
50% 1.000000
75% 1.000000
max 1.000000
Name: target, dtype: float64
count 569.000000
mean 25.677223
std 6.146258
min 12.020000
25% 21.080000
50% 25.410000
75% 29.720000
max 49.540000
Name: worst texture, dtype: float64
Here we can see the summary of target and worst texture column, we take only these columns to understand the groupby aggregate functions better.
Python3
df1 = df[['worst texture', 'worst area', 'target']]gr1 = df1.groupby(df1['target']).mean()gr1
Output:
So here we see the mean of worst texture and worst area grouped around benign and malignant cancer, now the normal data has been interfered by this method, and we have to add them separately thereβs why groupby without aggregation becomes handy.
Python3
# function to take the data as group and perform aggregationdef meanofTargets(group1): wt = group1['worst texture'].agg('mean') wa = group1['worst area'].agg('mean') group1['Mean worst texture'] = wt group1['Mean worst area'] = wa return group1 df2 = df1.groupby('target').apply(meanofTargets)df2
Output:
Thus, in the above dataset, we are able to join the mean of the worst area and worst texture in a separate column, and we do it with groupby method of the target column where it grouped β1βs and 0βs separately.
Example 2:
Similarly, letβs see another example of using groupby without aggregation. But as there is no categorical column we will have to make a categorical column myself. For this, letβs choose mean area which have a max value of 2500 and min value of 150, so we will classify them into 6 groups of range 400 using the pandas cut method to convert continuous to categorical. As this doesnβt concern subject of the article refer to the GitHub repo here for more info.
Thus, we make a categorical column βCat_mean_areaβ and we can perform the groupby aggregation method here too. But instead of grouping the whole dataset we can use some specific columns like mean area and target only.
Python3
# dataframe df_3 to contain only mean_area,Cat_mean_area and targetdf_3 = df_2[['mean area', 'Cat_mean_area', 'target']] # applying groupby sumgr2 = df_3.groupby(df_2['Cat_mean_area']).sum()gr2
Output:
Thus, by the steps mentioned above, we perform groupby without aggregation.
Python3
# function to take the data as group and perform aggregationdef totalTargets(group): g = group['target'].agg('sum') group['Total_targets'] = g return group df_4 = df_3.groupby(df_3['Cat_mean_area']).apply(totalTargets)df_4
Output:
simmytarika5
surindertarika1234
Picked
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24072,
"s": 24044,
"text": "\n29 Aug, 2021"
},
{
"code": null,
"e": 24232,
"s": 24072,
"text": "Pandas is a great python package for manipulating data and some of the tools which we learn as a beginner are an aggregation and group by functions of pandas. "
},
{
"code": null,
"e": 24723,
"s": 24232,
"text": "Groupby() is a function used to split the data in dataframe into groups based on a given condition. Aggregation on other hand operates on series, data and returns a numerical summary of the data. There are a lot of aggregation functions as count(),max(),min(),mean(),std(),describe(). We can combine both functions to find multiple aggregations on a particular column. For further details about this refer to this article How to combine Groupby and Multiple aggregation function in Pandas."
},
{
"code": null,
"e": 25113,
"s": 24723,
"text": "Instead of using groupby aggregation together, we can perform groupby without aggregation which is applicable to aggregate data separately. We will see this with an example where we will take a breast cancer dataset with different numerical features like mean area, worst texture, and many more. The target column has 0 which means the cancer is benign and 1 means the cancer is malignant."
},
{
"code": null,
"e": 25124,
"s": 25113,
"text": "Example 1:"
},
{
"code": null,
"e": 25132,
"s": 25124,
"text": "Python3"
},
{
"code": "# importing python libraries and breast_cancer dataset from sklearnimport numpy as npimport pandas as pdfrom sklearn import datasetsfrom sklearn.datasets import load_breast_cancer # data is loaded in a DataFramecancer_data = load_breast_cancer()df = pd.DataFrame(cancer_data.data, columns=cancer_data.feature_names)df['target'] = pd.Series(cancer_data.target)df.head()",
"e": 25501,
"s": 25132,
"text": null
},
{
"code": null,
"e": 25509,
"s": 25501,
"text": "Output:"
},
{
"code": null,
"e": 25753,
"s": 25509,
"text": "Thus, we can visualize the data which have all the columns, but all the columns are in numerical form and there are no categorical data instead of only the target column, so letβs have a look in target and another column named βworst textureβ."
},
{
"code": null,
"e": 25761,
"s": 25753,
"text": "Python3"
},
{
"code": "print(df['target'].describe(), df['worst texture'].describe())",
"e": 25824,
"s": 25761,
"text": null
},
{
"code": null,
"e": 25832,
"s": 25824,
"text": "Output:"
},
{
"code": null,
"e": 26217,
"s": 25832,
"text": "count 569.000000\nmean 0.627417\nstd 0.483918\nmin 0.000000\n25% 0.000000\n50% 1.000000\n75% 1.000000\nmax 1.000000\nName: target, dtype: float64\ncount 569.000000\nmean 25.677223\nstd 6.146258\nmin 12.020000\n25% 21.080000\n50% 25.410000\n75% 29.720000\nmax 49.540000\nName: worst texture, dtype: float64"
},
{
"code": null,
"e": 26362,
"s": 26217,
"text": "Here we can see the summary of target and worst texture column, we take only these columns to understand the groupby aggregate functions better."
},
{
"code": null,
"e": 26370,
"s": 26362,
"text": "Python3"
},
{
"code": "df1 = df[['worst texture', 'worst area', 'target']]gr1 = df1.groupby(df1['target']).mean()gr1",
"e": 26464,
"s": 26370,
"text": null
},
{
"code": null,
"e": 26472,
"s": 26464,
"text": "Output:"
},
{
"code": null,
"e": 26719,
"s": 26472,
"text": "So here we see the mean of worst texture and worst area grouped around benign and malignant cancer, now the normal data has been interfered by this method, and we have to add them separately thereβs why groupby without aggregation becomes handy. "
},
{
"code": null,
"e": 26727,
"s": 26719,
"text": "Python3"
},
{
"code": "# function to take the data as group and perform aggregationdef meanofTargets(group1): wt = group1['worst texture'].agg('mean') wa = group1['worst area'].agg('mean') group1['Mean worst texture'] = wt group1['Mean worst area'] = wa return group1 df2 = df1.groupby('target').apply(meanofTargets)df2",
"e": 27042,
"s": 26727,
"text": null
},
{
"code": null,
"e": 27050,
"s": 27042,
"text": "Output:"
},
{
"code": null,
"e": 27261,
"s": 27050,
"text": "Thus, in the above dataset, we are able to join the mean of the worst area and worst texture in a separate column, and we do it with groupby method of the target column where it grouped β1βs and 0βs separately."
},
{
"code": null,
"e": 27272,
"s": 27261,
"text": "Example 2:"
},
{
"code": null,
"e": 27731,
"s": 27272,
"text": "Similarly, letβs see another example of using groupby without aggregation. But as there is no categorical column we will have to make a categorical column myself. For this, letβs choose mean area which have a max value of 2500 and min value of 150, so we will classify them into 6 groups of range 400 using the pandas cut method to convert continuous to categorical. As this doesnβt concern subject of the article refer to the GitHub repo here for more info."
},
{
"code": null,
"e": 27949,
"s": 27731,
"text": "Thus, we make a categorical column βCat_mean_areaβ and we can perform the groupby aggregation method here too. But instead of grouping the whole dataset we can use some specific columns like mean area and target only."
},
{
"code": null,
"e": 27957,
"s": 27949,
"text": "Python3"
},
{
"code": "# dataframe df_3 to contain only mean_area,Cat_mean_area and targetdf_3 = df_2[['mean area', 'Cat_mean_area', 'target']] # applying groupby sumgr2 = df_3.groupby(df_2['Cat_mean_area']).sum()gr2",
"e": 28151,
"s": 27957,
"text": null
},
{
"code": null,
"e": 28159,
"s": 28151,
"text": "Output:"
},
{
"code": null,
"e": 28235,
"s": 28159,
"text": "Thus, by the steps mentioned above, we perform groupby without aggregation."
},
{
"code": null,
"e": 28243,
"s": 28235,
"text": "Python3"
},
{
"code": "# function to take the data as group and perform aggregationdef totalTargets(group): g = group['target'].agg('sum') group['Total_targets'] = g return group df_4 = df_3.groupby(df_3['Cat_mean_area']).apply(totalTargets)df_4",
"e": 28475,
"s": 28243,
"text": null
},
{
"code": null,
"e": 28483,
"s": 28475,
"text": "Output:"
},
{
"code": null,
"e": 28496,
"s": 28483,
"text": "simmytarika5"
},
{
"code": null,
"e": 28515,
"s": 28496,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28522,
"s": 28515,
"text": "Picked"
},
{
"code": null,
"e": 28544,
"s": 28522,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 28558,
"s": 28544,
"text": "Python-pandas"
},
{
"code": null,
"e": 28565,
"s": 28558,
"text": "Python"
},
{
"code": null,
"e": 28663,
"s": 28565,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28681,
"s": 28663,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28716,
"s": 28681,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28738,
"s": 28716,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28770,
"s": 28738,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28800,
"s": 28770,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28842,
"s": 28800,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28868,
"s": 28842,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28911,
"s": 28868,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28948,
"s": 28911,
"text": "Create a Pandas DataFrame from Lists"
}
]
|
Can we throw an Unchecked Exception from a static block in java? | A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
Live Demo
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
Hello this is a static block
This is main method
Just like any other method in Java when an exception occurs in static block you can handle it using try-catch pair.
Live Demo
import java.io.File;
import java.util.Scanner;
public class ThrowingExceptions{
static String path = "D://sample.txt";
static {
try {
Scanner sc = new Scanner(new File(path));
StringBuffer sb = new StringBuffer();
sb.append(sc.nextLine());
String data = sb.toString();
System.out.println(data);
} catch(Exception ex) {
System.out.println("");
}
}
public static void main(String args[]) {
}
}
This is a sample fileThis is main method
Whenever you throw a checked exception you need to handle it in the current method or, you can throw (postpone) it to the calling method.
You cannot use throws keyword with a static block, and more over a static block is invoked at compile time (at the time of class loading) no method invokes it.
Herefore, if you throw an exception using the throw keyword in a static block you must wrap it within try-catch blocks else a compile time error will be generated.
Live Demo
import java.io.FileNotFoundException;
public class ThrowingExceptions{
static String path = "D://sample.txt";
static {
FileNotFoundException ex = new FileNotFoundException();
throw ex;
}
public static void main(String args[]) {
}
}
ThrowingExceptions.java:4: error: initializer must be able to complete normally
static {
^
ThrowingExceptions.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
throw ex;
^
2 errors | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading."
},
{
"code": null,
"e": 1271,
"s": 1260,
"text": " Live Demo"
},
{
"code": null,
"e": 1467,
"s": 1271,
"text": "public class MyClass {\n static{\n System.out.println(\"Hello this is a static block\");\n }\n public static void main(String args[]){\n System.out.println(\"This is main method\");\n }\n}"
},
{
"code": null,
"e": 1516,
"s": 1467,
"text": "Hello this is a static block\nThis is main method"
},
{
"code": null,
"e": 1632,
"s": 1516,
"text": "Just like any other method in Java when an exception occurs in static block you can handle it using try-catch pair."
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": " Live Demo"
},
{
"code": null,
"e": 2122,
"s": 1643,
"text": "import java.io.File;\nimport java.util.Scanner;\npublic class ThrowingExceptions{\n static String path = \"D://sample.txt\";\n static {\n try {\n Scanner sc = new Scanner(new File(path));\n StringBuffer sb = new StringBuffer();\n sb.append(sc.nextLine());\n String data = sb.toString();\n System.out.println(data);\n } catch(Exception ex) {\n System.out.println(\"\");\n }\n }\n public static void main(String args[]) {\n }\n}"
},
{
"code": null,
"e": 2163,
"s": 2122,
"text": "This is a sample fileThis is main method"
},
{
"code": null,
"e": 2301,
"s": 2163,
"text": "Whenever you throw a checked exception you need to handle it in the current method or, you can throw (postpone) it to the calling method."
},
{
"code": null,
"e": 2461,
"s": 2301,
"text": "You cannot use throws keyword with a static block, and more over a static block is invoked at compile time (at the time of class loading) no method invokes it."
},
{
"code": null,
"e": 2625,
"s": 2461,
"text": "Herefore, if you throw an exception using the throw keyword in a static block you must wrap it within try-catch blocks else a compile time error will be generated."
},
{
"code": null,
"e": 2636,
"s": 2625,
"text": " Live Demo"
},
{
"code": null,
"e": 2895,
"s": 2636,
"text": "import java.io.FileNotFoundException;\npublic class ThrowingExceptions{\n static String path = \"D://sample.txt\";\n static {\n FileNotFoundException ex = new FileNotFoundException();\n throw ex;\n }\n public static void main(String args[]) {\n }\n}"
},
{
"code": null,
"e": 3149,
"s": 2895,
"text": "ThrowingExceptions.java:4: error: initializer must be able to complete normally\n static {\n ^\nThrowingExceptions.java:6: error: unreported exception FileNotFoundException; must be caught or declared to be thrown\n throw ex;\n ^\n2 errors"
}
]
|
JCL - Environment Setup | There are many Free Mainframe Emulators available for Windows which can be used to write and learn sample JCLs.
One such emulator is Hercules, which can be easily installed in Windows by following few simple steps given below:
Download and install the Hercules emulator, which is available from the Hercules' home site - : www.hercules-390.eu
Download and install the Hercules emulator, which is available from the Hercules' home site - : www.hercules-390.eu
The complete guide on various commands to write and execute a JCL can be found on URL www.jaymoseley.com/hercules/installmvs/instmvs2.htm
The complete guide on various commands to write and execute a JCL can be found on URL www.jaymoseley.com/hercules/installmvs/instmvs2.htm
Hercules is an open source software implementation of the mainframe System/370 and ESA/390 architectures, in addition to the latest 64-bit z/Architecture. Hercules runs under Linux, Windows, Solaris, FreeBSD, and Mac OS X.
A user can connect to a mainframe server in a number of ways such a thin client, dummy terminal, Virtual Client System (VCS) or Virtual Desktop System (VDS).
Every valid user is given a login id to enter into the Z/OS interface (TSO/E or ISPF). In the Z/OS interface, the JCL can be coded and stored as a member in a Partitioned Dataset (PDS). When the JCL is submitted, it is executed and the output received as explained in the job processing section of previous chapter.
The basic structure of a JCL with the common statements is given below:
//SAMPJCL JOB 1,CLASS=6,MSGCLASS=0,NOTIFY=&SYSUID (1)
//* (2)
//STEP010 EXEC PGM=SORT (3)
//SORTIN DD DSN=JCL.SAMPLE.INPUT,DISP=SHR (4)
//SORTOUT DD DSN=JCL.SAMPLE.OUTPUT, (5)
// DISP=(NEW,CATLG,CATLG),DATACLAS=DSIZE50
//SYSOUT DD SYSOUT=* (6)
//SYSUDUMP DD SYSOUT=C (6)
//SYSPRINT DD SYSOUT=* (6)
//SYSIN DD * (6)
SORT FIELDS=COPY
INCLUDE COND=(28,3,CH,EQ,C'XXX')
/* (7)
The numbered JCL statements have been explained below:
(1) JOB statement - Specifies the information required for SPOOLing of the job such as job id, priority of execution, user-id to be notified upon completion of the job.
(2) //* statement - This is a comment statement.
(3) EXEC statement - Specifies the PROC/Program to be executed. In the above example, a SORT program is being executed (i.e., sorting the input data in a particular order)
(4) Input DD statement - Specifies the type of input to be passed to the program mentioned in (3). In the above example, a Physical Sequential (PS) file is passed as input in shared mode (DISP = SHR).
(5) Output DD statement - Specifies the type of output to be produced by the program upon execution. In the above example, a PS file is created. If a statement extends beyond the 70th position in a line, then it is continued in the next line, which should start with "//" followed by one or more spaces.
(6) There can be other types of DD statements to specify additional information to the program (In the above example: The SORT condition is specified in the SYSIN DD statement) and to specify the destination for error/execution log (Example: SYSUDUMP/SYSPRINT). DD statements can be contained in a dataset (mainframe file) or as in stream data (information hard-coded within the JCL) as given in above example.
(7) /* marks the end of in stream data.
All the JCL statements except in stream data starts with //. There should be at least one space before and after JOB, EXEC and DD keywords and there should not be any spaces in rest of the statement.
Each of the JCL statements is accompanied by a set of parameters to help the Operating Systems in completing the program execution. The parameters can be of two types:
Appears at pre-defined position and order in the statement. Example: Accounting information Parameter can appear only after the JOB keyword and before the programmer name parameter and the Keyword Parameters. If a positional parameter is omitted, it has to be replaced with a comma.
Appears at pre-defined position and order in the statement. Example: Accounting information Parameter can appear only after the JOB keyword and before the programmer name parameter and the Keyword Parameters. If a positional parameter is omitted, it has to be replaced with a comma.
Positional Parameters are present in JOB and EXEC statements. In the above example, PGM is a positional parameter coded after the EXEC keyword.
Positional Parameters are present in JOB and EXEC statements. In the above example, PGM is a positional parameter coded after the EXEC keyword.
They are coded after the positional parameters, but can appear in any order. Keyword parameters can be omitted if not required. The generic syntax is KEYWORD= value. Example: MSGCLASS=X, i.e., the job log is redirected to the output SPOOL after the job completion.
They are coded after the positional parameters, but can appear in any order. Keyword parameters can be omitted if not required. The generic syntax is KEYWORD= value. Example: MSGCLASS=X, i.e., the job log is redirected to the output SPOOL after the job completion.
In the above example, CLASS, MSGCLASS and NOTIFY are keyword parameters of JOB statement. There can be keyword parameters in EXEC statement as well.
In the above example, CLASS, MSGCLASS and NOTIFY are keyword parameters of JOB statement. There can be keyword parameters in EXEC statement as well.
These parameters have been detailed out in the subsequent chapters along with appropriate examples.
12 Lectures
2 hours
Nishant Malik
73 Lectures
4.5 hours
Topictrick Education
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1976,
"s": 1864,
"text": "There are many Free Mainframe Emulators available for Windows which can be used to write and learn sample JCLs."
},
{
"code": null,
"e": 2091,
"s": 1976,
"text": "One such emulator is Hercules, which can be easily installed in Windows by following few simple steps given below:"
},
{
"code": null,
"e": 2208,
"s": 2091,
"text": "Download and install the Hercules emulator, which is available from the Hercules' home site - : www.hercules-390.eu"
},
{
"code": null,
"e": 2325,
"s": 2208,
"text": "Download and install the Hercules emulator, which is available from the Hercules' home site - : www.hercules-390.eu"
},
{
"code": null,
"e": 2463,
"s": 2325,
"text": "The complete guide on various commands to write and execute a JCL can be found on URL www.jaymoseley.com/hercules/installmvs/instmvs2.htm"
},
{
"code": null,
"e": 2601,
"s": 2463,
"text": "The complete guide on various commands to write and execute a JCL can be found on URL www.jaymoseley.com/hercules/installmvs/instmvs2.htm"
},
{
"code": null,
"e": 2824,
"s": 2601,
"text": "Hercules is an open source software implementation of the mainframe System/370 and ESA/390 architectures, in addition to the latest 64-bit z/Architecture. Hercules runs under Linux, Windows, Solaris, FreeBSD, and Mac OS X."
},
{
"code": null,
"e": 2982,
"s": 2824,
"text": "A user can connect to a mainframe server in a number of ways such a thin client, dummy terminal, Virtual Client System (VCS) or Virtual Desktop System (VDS)."
},
{
"code": null,
"e": 3298,
"s": 2982,
"text": "Every valid user is given a login id to enter into the Z/OS interface (TSO/E or ISPF). In the Z/OS interface, the JCL can be coded and stored as a member in a Partitioned Dataset (PDS). When the JCL is submitted, it is executed and the output received as explained in the job processing section of previous chapter."
},
{
"code": null,
"e": 3370,
"s": 3298,
"text": "The basic structure of a JCL with the common statements is given below:"
},
{
"code": null,
"e": 4200,
"s": 3370,
"text": "//SAMPJCL JOB 1,CLASS=6,MSGCLASS=0,NOTIFY=&SYSUID (1)\n//* (2)\n//STEP010 EXEC PGM=SORT (3) \n//SORTIN DD DSN=JCL.SAMPLE.INPUT,DISP=SHR (4)\n//SORTOUT DD DSN=JCL.SAMPLE.OUTPUT, (5)\n// DISP=(NEW,CATLG,CATLG),DATACLAS=DSIZE50 \n//SYSOUT DD SYSOUT=* (6) \n//SYSUDUMP DD SYSOUT=C (6) \n//SYSPRINT DD SYSOUT=* (6) \n//SYSIN DD * (6) \n SORT FIELDS=COPY \n INCLUDE COND=(28,3,CH,EQ,C'XXX') \n/* (7) "
},
{
"code": null,
"e": 4255,
"s": 4200,
"text": "The numbered JCL statements have been explained below:"
},
{
"code": null,
"e": 4424,
"s": 4255,
"text": "(1) JOB statement - Specifies the information required for SPOOLing of the job such as job id, priority of execution, user-id to be notified upon completion of the job."
},
{
"code": null,
"e": 4473,
"s": 4424,
"text": "(2) //* statement - This is a comment statement."
},
{
"code": null,
"e": 4645,
"s": 4473,
"text": "(3) EXEC statement - Specifies the PROC/Program to be executed. In the above example, a SORT program is being executed (i.e., sorting the input data in a particular order)"
},
{
"code": null,
"e": 4846,
"s": 4645,
"text": "(4) Input DD statement - Specifies the type of input to be passed to the program mentioned in (3). In the above example, a Physical Sequential (PS) file is passed as input in shared mode (DISP = SHR)."
},
{
"code": null,
"e": 5150,
"s": 4846,
"text": "(5) Output DD statement - Specifies the type of output to be produced by the program upon execution. In the above example, a PS file is created. If a statement extends beyond the 70th position in a line, then it is continued in the next line, which should start with \"//\" followed by one or more spaces."
},
{
"code": null,
"e": 5561,
"s": 5150,
"text": "(6) There can be other types of DD statements to specify additional information to the program (In the above example: The SORT condition is specified in the SYSIN DD statement) and to specify the destination for error/execution log (Example: SYSUDUMP/SYSPRINT). DD statements can be contained in a dataset (mainframe file) or as in stream data (information hard-coded within the JCL) as given in above example."
},
{
"code": null,
"e": 5601,
"s": 5561,
"text": "(7) /* marks the end of in stream data."
},
{
"code": null,
"e": 5801,
"s": 5601,
"text": "All the JCL statements except in stream data starts with //. There should be at least one space before and after JOB, EXEC and DD keywords and there should not be any spaces in rest of the statement."
},
{
"code": null,
"e": 5969,
"s": 5801,
"text": "Each of the JCL statements is accompanied by a set of parameters to help the Operating Systems in completing the program execution. The parameters can be of two types:"
},
{
"code": null,
"e": 6252,
"s": 5969,
"text": "Appears at pre-defined position and order in the statement. Example: Accounting information Parameter can appear only after the JOB keyword and before the programmer name parameter and the Keyword Parameters. If a positional parameter is omitted, it has to be replaced with a comma."
},
{
"code": null,
"e": 6535,
"s": 6252,
"text": "Appears at pre-defined position and order in the statement. Example: Accounting information Parameter can appear only after the JOB keyword and before the programmer name parameter and the Keyword Parameters. If a positional parameter is omitted, it has to be replaced with a comma."
},
{
"code": null,
"e": 6679,
"s": 6535,
"text": "Positional Parameters are present in JOB and EXEC statements. In the above example, PGM is a positional parameter coded after the EXEC keyword."
},
{
"code": null,
"e": 6823,
"s": 6679,
"text": "Positional Parameters are present in JOB and EXEC statements. In the above example, PGM is a positional parameter coded after the EXEC keyword."
},
{
"code": null,
"e": 7088,
"s": 6823,
"text": "They are coded after the positional parameters, but can appear in any order. Keyword parameters can be omitted if not required. The generic syntax is KEYWORD= value. Example: MSGCLASS=X, i.e., the job log is redirected to the output SPOOL after the job completion."
},
{
"code": null,
"e": 7353,
"s": 7088,
"text": "They are coded after the positional parameters, but can appear in any order. Keyword parameters can be omitted if not required. The generic syntax is KEYWORD= value. Example: MSGCLASS=X, i.e., the job log is redirected to the output SPOOL after the job completion."
},
{
"code": null,
"e": 7502,
"s": 7353,
"text": "In the above example, CLASS, MSGCLASS and NOTIFY are keyword parameters of JOB statement. There can be keyword parameters in EXEC statement as well."
},
{
"code": null,
"e": 7651,
"s": 7502,
"text": "In the above example, CLASS, MSGCLASS and NOTIFY are keyword parameters of JOB statement. There can be keyword parameters in EXEC statement as well."
},
{
"code": null,
"e": 7751,
"s": 7651,
"text": "These parameters have been detailed out in the subsequent chapters along with appropriate examples."
},
{
"code": null,
"e": 7784,
"s": 7751,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7799,
"s": 7784,
"text": " Nishant Malik"
},
{
"code": null,
"e": 7834,
"s": 7799,
"text": "\n 73 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7856,
"s": 7834,
"text": " Topictrick Education"
},
{
"code": null,
"e": 7863,
"s": 7856,
"text": " Print"
},
{
"code": null,
"e": 7874,
"s": 7863,
"text": " Add Notes"
}
]
|
Apex - Quick Guide | Apex is a proprietary language developed by the Salesforce.com. As per the official definition, Apex is a strongly typed, object-oriented programming language that allows developers to execute the flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API.
It has a Java-like syntax and acts like database stored procedures. It enables the developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages.Apex code can be initiated by Web service requests and from triggers on objects. Apex is included in Performance Edition, Unlimited Edition, Enterprise Edition, and Developer Edition.
Let us now discuss the features of Apex as a Language β
Apex has built in support for DML operations like INSERT, UPDATE, DELETE and also DML Exception handling. It has support for inline SOQL and SOSL query handling which returns the set of sObject records. We will study the sObject, SOQL, SOSL in detail in future chapters.
Apex is easy to use as it uses the syntax like Java. For example, variable declaration, loop syntax and conditional statements.
Apex is data focused and designed to execute multiple queries and DML statements together. It issues multiple transaction statements on Database.
Apex is a strongly typed language. It uses direct reference to schema objects like sObject and any invalid reference quickly fails if it is deleted or if is of wrong data type.
Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed to guard closely against runaway code, preventing it from monopolizing shared resources. Any code that violates limits fails with easy-to-understand error messages.
Apex is upgraded as part of Salesforce releases. We don't have to upgrade it manually.
Apex provides built-in support for unit test creation and execution, including test results that indicate how much code is covered, and which parts of your code can be more efficient.
Apex should be used when we are not able to implement the complex business functionality using the pre-built and existing out of the box functionalities. Below are the cases where we need to use apex over Salesforce configuration.
We can use Apex when we want to β
Create Web services with integrating other systems.
Create Web services with integrating other systems.
Create email services for email blast or email setup.
Create email services for email blast or email setup.
Perform complex validation over multiple objects at the same time and also custom validation implementation.
Perform complex validation over multiple objects at the same time and also custom validation implementation.
Create complex business processes that are not supported by existing workflow functionality or flows.
Create complex business processes that are not supported by existing workflow functionality or flows.
Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records.
Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records.
Perform some logic when a record is modified or modify the related object's record when there is some event which has caused the trigger to fire.
Perform some logic when a record is modified or modify the related object's record when there is some event which has caused the trigger to fire.
As shown in the diagram below (Reference: Salesforce Developer Documentation), Apex runs entirely on demand Force.com Platform
There are two sequence of actions when the developer saves the code and when an end user performs some action which invokes the Apex code as shown below β
When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into a set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata.
When an end-user triggers the execution of Apex, by clicking a button or accessing a Visualforce page, the platform application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before returning the result. The end-user observes no differences in execution time as compared to the standard application platform request.
Since Apex is the proprietary language of Salesforce.com, it does not support some features which a general programming language does. Following are a few features which Apex does not support β
It cannot show the elements in User Interface.
It cannot show the elements in User Interface.
You cannot change the standard SFDC provided functionality and also it is not possible to prevent the standard functionality execution.
You cannot change the standard SFDC provided functionality and also it is not possible to prevent the standard functionality execution.
Creating multiple threads is also not possible as we can do it in other languages.
Creating multiple threads is also not possible as we can do it in other languages.
Apex code typically contains many things that we might be familiar with from other programming languages.
As strongly typed language, you must declare every variable with data type in Apex. As seen in the code below (screenshot below), lstAcc is declared with data type as List of Accounts.
This will be used to fetch the data from Salesforce database. The query shown in screenshot below is fetching data from Account object.
This loop statement is used for iterating over a list or iterating over a piece of code for a specified number of times. In the code shown in the screenshot below, iteration will be same as the number of records we have.
The If statement is used for flow control in this code. Based on certain condition, it is decided whether to go for execution or to stop the execution of the particular piece of code. For example, in the code shown below, it is checking whether the list is empty or it contains records.
Performs the records insert, update, upsert, delete operation on the records in database. For example, the code given below helps in updating Accounts with new field value.
Following is an example of how an Apex code snippet will look like. We are going to study all these Apex programming concepts further in this tutorial.
In this chapter, we will understand the environment for our Salesforce Apex development. It is assumed that you already have a Salesforce edition set up for doing Apex development.
You can develop the Apex code in either Sandbox or Developer edition of Salesforce. A Sandbox organization is a copy of your organization in which you can write code and test it without taking the risk of data modification or disturbing the normal functionality. As per the standard industrial practice, you have to develop the code in Sandbox and then deploy it to the Production environment.
For this tutorial, we will be using the Developer edition of Salesforce. In the Developer edition, you will not have the option of creating a Sandbox organization. The Sandbox features are available in other editions of Salesforce.
In all the editions, we can use any of the following three tools to develop the code β
Force.com Developer Console
Force.com IDE
Code Editor in the Salesforce User Interface
Note β We will be utilizing the Developer Console throughout our tutorial for code execution as it is simple and user friendly for learning.
The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your Salesforce organization.
Follow these steps to open the Developer Console β
Step 1 β Go to Name β Developer Console
Step 2 β Click on "Developer Console" and a window will appear as in the following screenshot.
Following are a few operations that can be performed using the Developer Console.
Writing and compiling code β You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Writing and compiling code β You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Debugging β You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Debugging β You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Testing β You can view debug logs and set checkpoints that aid in debugging.
Testing β You can view debug logs and set checkpoints that aid in debugging.
Checking performance β You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage.
Checking performance β You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage.
SOQL queries β You can inspect debug logs to locate performance bottlenecks.
SOQL queries β You can inspect debug logs to locate performance bottlenecks.
Color coding and autocomplete β The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names.
Color coding and autocomplete β The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names.
All the code snippets mentioned in this tutorial need to be executed in the developer console. Follow these steps to execute steps in Developer Console.
Step 1 β Login to the Salesforce.com using login.salesforce.com. Copy the code snippets mentioned in the tutorial. For now, we will use the following sample code.
String myString = 'MyString';
System.debug('Value of String Variable'+myString);
Step 2 β To open the Developer Console, click on Name β Developer Console and then click on Execute Anonymous as shown below.
Step 3 β In this step, a window will appear and you can paste the code there.
Step 4 β When we click on Execute, the debug logs will open. Once the log appears in window as shown below, then click on the log record.
Then type 'USER' in the window as shown below and the output statement will appear in the debug window. This 'USER' statement is used for filtering the output.
So basically, you will be following all the above mentioned steps to execute any code
snippet in this tutorial.
For our tutorial, we will be implementing the CRM application for a Chemical Equipment and Processing Company. This company deals with suppliers and provides services. We will work out small code snippets related to this example throughout our tutorial to understand every concept in detail.
For executing the code in this tutorial, you will need to have two objects created: Customer and Invoice objects. If you already know how to create these objects in Salesforce, you can skip the steps given below. Else, you can follow the step by step guide below.
We will be setting up the Customer object first.
Step 1 β Go to Setup and then search for 'Object' as shown below. Then click on the Objects link as shown below.
Step 2 β Once the object page is opened, then click on the 'Create New Object' button as shown below.
Step 3 β After clicking on button, the new object creation page will appear and then enter all the object details as entered below. Object name should be Customer. You just have to enter the information in the field as shown in the screenshot below and keep other default things as it is.
Enter the information and then click on the 'Save' button β
By following the above steps, we have successfully created the Customer object.
Now that we have our Customer object set up, we will create a field 'Active' and then you can create the other fields by following similar steps. The Name and API name of the field will be given in the screenshot.
Step 1 β We will be creating a field named as 'Active' of data type as Checkbox. Go to Setup and click on it.
Step 2 β Search for 'Object' as shown below and click on it.
Step 3 β Click on object 'Customer'.
Step 4 β Once you have clicked on the Customer object link and the object detail page appears, click on the New button.
Step 5 β Now, select the data type as Checkbox and click Next.
Step 6 β Enter the field name and label as shown below.
Step 7 β Click on Visible and then click Next.
Step 8 β Now click on 'Save'.
By following the above steps, our custom field 'Active' is created. You have to follow all the above custom field creation steps for the remaining fields. This is the final view of customer object once all the fields are created β
Step 1 β Go to Setup and search for 'Object' and then click on the Objects link as shown below.
Step 2 β Once the object page is opened, then click on the 'Create New Object' button as shown below.
Step 3 β After clicking on the button, the new object creation page will appear as shown in the screenshot below. You need to enter the details here. The object name should be Invoice. This is similar to how we created the Customer object earlier in this tutorial.
Step 4 β Enter the information as shown below and then click on the 'Save' button.
By following these steps, your Invoice object will be created.
We will be creating the field Description on Invoice object as shown below β
Step 1 β Go to Setup and click on it.
Step 2 β Search for 'Object' as shown below and click on it.
Step 3 β Click on object 'Invoice'.
And then click on 'New'.
Step 4 β Select the data type as Text Area and then click on Next button.
Step 5 β Enter the information as given below.
Step 6 β Click on Visible and then Next.
Step 7 β Click on Save.
Similarly, you can create the other fields on the Invoice object.
By this, we have created the objects that are needed for this tutorial. We will be learning various examples in the subsequent chapters based on these objects.
The Apex language is strongly typed so every variable in Apex will be declared with the specific data type. All apex variables are initialized to null initially. It is always recommended for a developer to make sure that proper values are assigned to the variables. Otherwise such variables when used, will throw null pointer exceptions or any unhandled exceptions.
Apex supports the following data types β
Primitive (Integer, Double, Long, Date, Datetime, String, ID, or Boolean)
Primitive (Integer, Double, Long, Date, Datetime, String, ID, or Boolean)
Collections (Lists, Sets and Maps) (To be covered in Chapter 6)
Collections (Lists, Sets and Maps) (To be covered in Chapter 6)
sObject
sObject
Enums
Enums
Classes, Objects and Interfaces (To be covered in Chapter 11, 12 and 13)
Classes, Objects and Interfaces (To be covered in Chapter 11, 12 and 13)
In this chapter, we will look at all the Primitive Data Types, sObjects and Enums. We will be looking at Collections, Classes, Objects and Interfaces in upcoming chapters since they are key topics to be learnt individually.
In this section, we will discuss the Primitive Data Types supported by Apex.
A 32-bit number that does not include any decimal point. The value range for this starts from -2,147,483,648 and the maximum value is up to 2,147,483,647.
Example
We want to declare a variable which will store the quantity of barrels which need to be shipped to the buyer of the chemical processing plant.
Integer barrelNumbers = 1000;
system.debug(' value of barrelNumbers variable: '+barrelNumbers);
The System.debug() function prints the value of variable so that we can use this to debug or to get to know what value the variable holds currently.
Paste the above code to the Developer console and click on Execute. Once the logs are generated, then it will show the value of variable "barrelNumbers" as 1000.
This variable can either be true, false or null. Many times, this type of variable can be used as flag in programming to identify if the particular condition is set or not set.
Example
If the Boolean shipmentDispatched is to be set as true, then it can be declared as β
Boolean shipmentDispatched;
shipmentDispatched = true;
System.debug('Value of shipmentDispatched '+shipmentDispatched);
This variable type indicates a date. This can only store the date and not the time. For saving the date along with time, we will need to store it in variable of DateTime.
Example
Consider the following example to understand how the Date variable works.
//ShipmentDate can be stored when shipment is dispatched.
Date ShipmentDate = date.today();
System.debug('ShipmentDate '+ShipmentDate);
This is a 64-bit number without a decimal point. This is used when we need a range of values wider than those provided by Integer.
Example
If the company revenue is to be stored, then we will use the data type as Long.
Long companyRevenue = 21474838973344648L;
system.debug('companyRevenue'+companyRevenue);
We can refer this as any data type which is supported in Apex. For example, Class variable can be object of that class, and the sObject generic type is also an object and similarly specific object type like Account is also an Object.
Example
Consider the following example to understand how the bject variable works.
Account objAccount = new Account (Name = 'Test Chemical');
system.debug('Account value'+objAccount);
Note β You can create an object of predefined class as well, as given below β
//Class Name: MyApexClass
MyApexClass classObj = new MyApexClass();
This is the class object which will be used as class variable.
String is any set of characters within single quotes. It does not have any limit for the number of characters. Here, the heap size will be used to determine the number of characters. This puts a curb on the monopoly of resources by the Apex program and also ensures that it does not get too large.
Example
String companyName = 'Abc International';
System.debug('Value companyName variable'+companyName);
This variable is used to store the particular time. This variable should always be declared with the system static method.
The Blob is a collection of Binary data which is stored as object. This will be used when we want to store the attachment in salesforce into a variable. This data type converts the attachments into a single object. If the blob is to be converted into a string, then we can make use of the toString and the valueOf methods for the same.
This is a special data type in Salesforce. It is similar to a table in SQL and contains fields which are similar to columns in SQL. There are two types of sObjects β Standard and Custom.
For example, Account is a standard sObject and any other user-defined object (like Customer object that we created) is a Custom sObject.
Example
//Declaring an sObject variable of type Account
Account objAccount = new Account();
//Assignment of values to fields of sObjects
objAccount.Name = 'ABC Customer';
objAccount.Description = 'Test Account';
System.debug('objAccount variable value'+objAccount);
//Declaring an sObject for custom object APEX_Invoice_c
APEX_Customer_c objCustomer = new APEX_Customer_c();
//Assigning value to fields
objCustomer.APEX_Customer_Decscription_c = 'Test Customer';
System.debug('value objCustomer'+objCustomer);
Enum is an abstract data type that stores one value of a finite set of specified identifiers. You can use the keyword Enum to define an Enum. Enum can be used as any other data type in Salesforce.
Example
You can declare the possible names of Chemical Compound by executing the following
code β
//Declaring enum for Chemical Compounds
public enum Compounds {HCL, H2SO4, NACL, HG}
Compounds objC = Compounds.HCL;
System.debug('objC value: '+objC);
Java and Apex are similar in a lot of ways. Variable declaration in Java and Apex is also quite the same. We will discuss a few examples to understand how to declare local variables.
String productName = 'HCL';
Integer i = 0;
Set<string> setOfProducts = new Set<string>();
Map<id, string> mapOfProductIdToName = new Map<id, string>();
Note that all the variables are assigned with the value null.
Declaring Variables
You can declare the variables in Apex like String and Integer as follows β
String strName = 'My String'; //String variable declaration
Integer myInteger = 1; //Integer variable declaration
Boolean mtBoolean = true; //Boolean variable declaration
Apex variables are Case-Insensitive
This means that the code given below will throw an error since the variable 'm' has been declared two times and both will be treated as the same.
Integer m = 100;
for (Integer i = 0; i<10; i++) {
integer m = 1; //This statement will throw an error as m is being declared
again
System.debug('This code will throw error');
}
Scope of Variables
An Apex variable is valid from the point where it is declared in code. So it is not allowed to redefine the same variable again and in code block. Also, if you declare any variable in a method, then that variable scope will be limited to that particular method only. However, class variables can be accessed throughout the class.
Example
//Declare variable Products
List<string> Products = new List<strings>();
Products.add('HCL');
//You cannot declare this variable in this code clock or sub code block again
//If you do so then it will throw the error as the previous variable in scope
//Below statement will throw error if declared in same code block
List<string> Products = new List<strings>();
String in Apex, as in any other programming language, is any set of characters with no character limit.
Example
String companyName = 'Abc International';
System.debug('Value companyName variable'+companyName);
String class in Salesforce has many methods. We will take a look at some of the most important and frequently used string methods in this chapter.
This method will return true if the given string contains the substring mentioned.
Syntax
public Boolean contains(String substring)
Example
String myProductName1 = 'HCL';
String myProductName2 = 'NAHCL';
Boolean result = myProductName2.contains(myProductName1);
System.debug('O/p will be true as it contains the String and Output is:'+result);
This method will return true if the given string and the string passed in the method have the same binary sequence of characters and they are not null. You can compare the SFDC record id as well using this method. This method is case-sensitive.
Syntax
public Boolean equals(Object string)
Example
String myString1 = 'MyString';
String myString2 = 'MyString';
Boolean result = myString2.equals(myString1);
System.debug('Value of Result will be true as they are same and Result is:'+result);
This method will return true if stringtoCompare has the same sequence of characters as the given string. However, this method is not case-sensitive.
Syntax
public Boolean equalsIgnoreCase(String stringtoCompare)
Example
The following code will return true as string characters and sequence are same, ignoring the case sensitivity.
String myString1 = 'MySTRING';
String myString2 = 'MyString';
Boolean result = myString2.equalsIgnoreCase(myString1);
System.debug('Value of Result will be true as they are same and Result is:'+result);
This method removes the string provided in stringToRemove from the given string. This is useful when you want to remove some specific characters from string and are not aware of the exact index of the characters to remove. This method is case sensitive and will not work if the same character sequence occurs but case is different.
Syntax
public String remove(String stringToRemove)
Example
String myString1 = 'This Is MyString Example';
String stringToRemove = 'MyString';
String result = myString1.remove(stringToRemove);
System.debug('Value of Result will be 'This Is Example' as we have removed the MyString
and Result is :'+result);
This method removes the string provided in stringToRemove from the given string but only if it occurs at the end. This method is not case-sensitive.
Syntax
public String removeEndIgnoreCase(String stringToRemove)
Example
String myString1 = 'This Is MyString EXAMPLE';
String stringToRemove = 'Example';
String result = myString1.removeEndIgnoreCase(stringToRemove);
System.debug('Value of Result will be 'This Is MyString' as we have removed the 'Example'
and Result is :'+result);
This method will return true if the given string starts with the prefix provided in the
method.
Syntax
public Boolean startsWith(String prefix)
Example
String myString1 = 'This Is MyString EXAMPLE';
String prefix = 'This';
Boolean result = myString1.startsWith(prefix);
System.debug(' This will return true as our String starts with string 'This' and the
Result is :'+result);
Arrays in Apex are basically the same as Lists in Apex. There is no logical distinction between the Arrays and Lists as their internal data structure and methods are also same but the array syntax is little traditional like Java.
Below is the representation of an Array of Products β
Index 0 β HCL
Index 1 β H2SO4
Index 2 β NACL
Index 3 β H2O
Index 4 β N2
Index 5 β U296
<String> [] arrayOfProducts = new List<String>();
Suppose, we have to store the name of our Products β we can use the Array where in, we will store the Product Names as shown below. You can access the particular Product by specifying the index.
//Defining array
String [] arrayOfProducts = new List<String>();
//Adding elements in Array
arrayOfProducts.add('HCL');
arrayOfProducts.add('H2SO4');
arrayOfProducts.add('NACL');
arrayOfProducts.add('H2O');
arrayOfProducts.add('N2');
arrayOfProducts.add('U296');
for (Integer i = 0; i<arrayOfProducts.size(); i++) {
//This loop will print all the elements in array
system.debug('Values In Array: '+arrayOfProducts[i]);
}
You can access any element in array by using the index as shown below β
//Accessing the element in array
//We would access the element at Index 3
System.debug('Value at Index 3 is :'+arrayOfProducts[3]);
As in any other programming language, Constants are the variables which do not change their value once declared or assigned a value.
In Apex, Constants are used when we want to define variables which should have constant value throughout the program execution. Apex constants are declared with the keyword 'final'.
Consider a CustomerOperationClass class and a constant variable regularCustomerDiscount
inside it β
public class CustomerOperationClass {
static final Double regularCustomerDiscount = 0.1;
static Double finalPrice = 0;
public static Double provideDiscount (Integer price) {
//calculate the discount
finalPrice = price - price * regularCustomerDiscount;
return finalPrice;
}
}
To see the Output of the above class, you have to execute the following code in the Developer Console Anonymous Window β
Double finalPrice = CustomerOperationClass.provideDiscount(100);
System.debug('finalPrice '+finalPrice);
Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
In this chapter, we will be studying the basic and advanced structure of decision-making and conditional statements in Apex. Decision-making is necessary to control the flow of execution when certain condition is met or not. Following is the general form of a typical decision-making structure found in most of the programming languages
An if statement consists of a Boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
You can use one if or else if statement inside another if or else if statement(s).
Loops are used when a particular piece of code should be repeated with the desired number of iteration. Apex supports the standard traditional for loop as well as other advanced types of Loops. In this chapter, we will discuss in detail about the Loops in Apex.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages β
The following tables lists down the different Loops that handle looping requirements in Apex Programming language. Click the following links to check their detail.
This loop performs a set of statements for each item in a set of records.
Execute a sequence of statements directly over the returned set o SOQL query.
Execute a sequence of statements in traditional Java-like syntax.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Like a while statement, except that it tests the condition at the end of the loop body.
Collections is a type of variable that can store multiple number of records. For example, List can store multiple number of Account object's records. Let us now have a detailed overview of all collection types.
List can contain any number of records of primitive, collections, sObjects, user defined and built in Apex type. This is one of the most important type of collection and also, it has some system methods which have been tailored specifically to use with List. List index always starts with 0. This is synonymous to the array in Java. A list should be declared with the keyword 'List'.
Example
Below is the list which contains the List of a primitive data type (string), that is the list of cities.
List<string> ListOfCities = new List<string>();
System.debug('Value Of ListOfCities'+ListOfCities);
Declaring the initial values of list is optional. However, we will declare the initial values here. Following is an example which shows the same.
List<string> ListOfStates = new List<string> {'NY', 'LA', 'LV'};
System.debug('Value ListOfStates'+ListOfStates);
List<account> AccountToDelete = new List<account> (); //This will be null
System.debug('Value AccountToDelete'+AccountToDelete);
We can declare the nested List as well. It can go up to five levels. This is called the
Multidimensional list.
This is the list of set of integers.
List<List<Set<Integer>>> myNestedList = new List<List<Set<Integer>>>();
System.debug('value myNestedList'+myNestedList);
List can contain any number of records, but there is a limitation on heap size to prevent the performance issue and monopolizing the resources.
There are methods available for Lists which we can be utilized while programming to achieve some functionalities like calculating the size of List, adding an element, etc.
Following are some most frequently used methods β
size()
add()
get()
clear()
set()
The following example demonstrates the use of all these methods
// Initialize the List
List<string> ListOfStatesMethod = new List<string>();
// This statement would give null as output in Debug logs
System.debug('Value of List'+ ListOfStatesMethod);
// Add element to the list using add method
ListOfStatesMethod.add('New York');
ListOfStatesMethod.add('Ohio');
// This statement would give New York and Ohio as output in Debug logs
System.debug('Value of List with new States'+ ListOfStatesMethod);
// Get the element at the index 0
String StateAtFirstPosition = ListOfStatesMethod.get(0);
// This statement would give New York as output in Debug log
System.debug('Value of List at First Position'+ StateAtFirstPosition);
// set the element at 1 position
ListOfStatesMethod.set(0, 'LA');
// This statement would give output in Debug log
System.debug('Value of List with element set at First Position' + ListOfStatesMethod[0]);
// Remove all the elements in List
ListOfStatesMethod.clear();
// This statement would give output in Debug log
System.debug('Value of List'+ ListOfStatesMethod);
You can use the array notation as well to declare the List, as given below, but this is not general practice in Apex programming β
String [] ListOfStates = new List<string>();
A Set is a collection type which contains multiple number of unordered unique records. A Set cannot have duplicate records. Like Lists, Sets can be nested.
Example
We will be defining the set of products which company is selling.
Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};
System.debug('Value of ProductSet'+ProductSet);
Set does support methods which we can utilize while programming as shown below (we are extending the above example) β
// Adds an element to the set
// Define set if not defined previously
Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};
ProductSet.add('HCL');
System.debug('Set with New Value '+ProductSet);
// Removes an element from set
ProductSet.remove('HCL');
System.debug('Set with removed value '+ProductSet);
// Check whether set contains the particular element or not and returns true or false
ProductSet.contains('HCL');
System.debug('Value of Set with all values '+ProductSet);
It is a key value pair which contains the unique key for each value. Both key and value can be of any data type.
Example
The following example represents the map of the Product Name with the Product code.
// Initialize the Map
Map<string, string> ProductCodeToProductName = new Map<string, string>
{'1000'=>'HCL', '1001'=>'H2SO4'};
// This statement would give as output as key value pair in Debug log
System.debug('value of ProductCodeToProductName'+ProductCodeToProductName);
Following are a few examples which demonstrate the methods that can be used with Map β
// Define a new map
Map<string, string> ProductCodeToProductName = new Map<string, string>();
// Insert a new key-value pair in the map where '1002' is key and 'Acetone' is value
ProductCodeToProductName.put('1002', 'Acetone');
// Insert a new key-value pair in the map where '1003' is key and 'Ketone' is value
ProductCodeToProductName.put('1003', 'Ketone');
// Assert that the map contains a specified key and respective value
System.assert(ProductCodeToProductName.containsKey('1002'));
System.debug('If output is true then Map contains the key and output is:'
+ ProductCodeToProductName.containsKey('1002'));
// Retrieves a value, given a particular key
String value = ProductCodeToProductName.get('1002');
System.debug('Value at the Specified key using get function: '+value);
// Return a set that contains all of the keys in the map
Set SetOfKeys = ProductCodeToProductName.keySet();
System.debug('Value of Set with Keys '+SetOfKeys);
Map values may be unordered and hence we should not rely on the order in which the values are stored and try to access the map always using keys. Map value can be null. Map keys when declared String are case-sensitive; for example, ABC and abc will be considered as different keys and treated as unique.
A class is a template or blueprint from which objects are created. An object is an instance of a class. This is the standard definition of Class. Apex Classes are similar to Java Classes.
For example, InvoiceProcessor class describes the class which has all the methods and actions that can be performed on the Invoice. If you create an instance of this class, then it will represent the single invoice which is currently in context.
You can create class in Apex from the Developer Console, Force.com Eclipse IDE and from Apex Class detail page as well.
Follow these steps to create an Apex class from the Developer Console β
Step 1 β Go to Name and click on the Developer Console.
Step 2 β Click on File β New and then click on the Apex class.
Follow these steps to create a class from Force.com IDE β
Step 1 β Open Force.com Eclipse IDE
Step 2 β Create a New Project by clicking on File β New β Apex Class.
Step 3 β Provide the Name for the Class and click on OK.
Once this is done, the new class will be created.
Follow these steps to create a class from Apex Class Detail Page β
Step 1 β Click on Name β Setup.
Step 2 β Search for 'Apex Class' and click on the link. It will open the Apex Class details
page.
Step 3 β Click on 'New' and then provide the Name for class and then click Save.
Below is the sample structure for Apex class definition.
Syntax
private | public | global
[virtual | abstract | with sharing | without sharing]
class ClassName [implements InterfaceNameList] [extends ClassName] {
// Classs Body
}
This definition uses a combination of access modifiers, sharing modes, class name and class body. We will look at all these options further.
Example
Following is a sample structure for Apex class definition β
public class MySampleApexClass { //Class definition and body
public static Integer myValue = 0; //Class Member variable
public static String myString = ''; //Class Member variable
public static Integer getCalculatedValue () {
// Method definition and body
// do some calculation
myValue = myValue+10;
return myValue;
}
}
If you declare the access modifier as 'Private', then this class will be known only locally and you cannot access this class outside of that particular piece. By default, classes have this modifier.
If you declare the class as 'Public' then this implies that this class is accessible to your organization and your defined namespace. Normally, most of the Apex classes are defined with this keyword.
If you declare the class as 'global' then this will be accessible by all apex codes irrespective of your organization. If you have method defined with web service keyword, then you must declare the containing class with global keyword.
Let us now discuss the different modes of sharing.
This is a special feature of Apex Classes in Salesforce. When a class is specified with 'With Sharing' keyword then it has following implications: When the class will get executed, it will respect the User's access settings and profile permission. Suppose, User's action has triggered the record update for 30 records, but user has access to only 20 records and 10 records are not accessible. Then, if the class is performing the action to update the records, only 20 records will be updated to which the user has access and rest of 10 records will not be updated. This is also called as the User mode.
Even if the User does not have access to 10 records out of 30, all the 30 records will be updated as the Class is running in the System mode, i.e., it has been defined with Without Sharing keyword. This is called the System Mode.
If you use the 'virtual' keyword, then it indicates that this class can be extended and overrides are allowed. If the methods need to be overridden, then the classes should be declared with the virtual keyword.
If you declare the class as 'abstract', then it will only contain the signature of method and not the actual implementation.
Syntax
[public | private | protected | global] [final] [static] data_type
variable_name [= value]
In the above syntax β
Variable data type and variable name are mandatory
Access modifiers and value are optional.
Example
public static final Integer myvalue;
There are two modifiers for Class Methods in Apex β Public or Protected. Return type is mandatory for method and if method is not returning anything then you must mention void as the return type. Additionally, Body is also required for method.
Syntax
[public | private | protected | global]
[override]
[static]
return_data_type method_name (input parameters) {
// Method body goes here
}
Those parameters mentioned in the square brackets are optional. However, the following components are essential β
return_data_type
method_name
Using access modifiers, you can specify access level for the class methods. For Example, Public method will be accessible from anywhere in the class and outside of the Class. Private method will be accessible only within the class. Global will be accessible by all the Apex classes and can be exposed as web service method accessible by other apex classes.
Example
//Method definition and body
public static Integer getCalculatedValue () {
//do some calculation
myValue = myValue+10;
return myValue;
}
This method has return type as Integer and takes no parameter.
A Method can have parameters as shown in the following example β
// Method definition and body, this method takes parameter price which will then be used
// in method.
public static Integer getCalculatedValueViaPrice (Decimal price) {
// do some calculation
myValue = myValue+price;
return myValue;
}
A constructor is a code that is invoked when an object is created from the class blueprint. It has the same name as the class name.
We do not need to define the constructor for every class, as by default a no-argument constructor gets called. Constructors are useful for initialization of variables or when a process is to be done at the time of class initialization. For example, you will like to assign values to certain Integer variables as 0 when the class gets called.
Example
// Class definition and body
public class MySampleApexClass2 {
public static Double myValue; // Class Member variable
public static String myString; // Class Member variable
public MySampleApexClass2 () {
myValue = 100; //initialized variable when class is called
}
public static Double getCalculatedValue () { // Method definition and body
// do some calculation
myValue = myValue+10;
return myValue;
}
public static Double getCalculatedValueViaPrice (Decimal price) {
// Method definition and body
// do some calculation
myValue = myValue+price; // Final Price would be 100+100=200.00
return myValue;
}
}
You can call the method of class via constructor as well. This may be useful when programming Apex for visual force controller. When class object is created, then constructor is called as shown below β
// Class and constructor has been instantiated
MySampleApexClass2 objClass = new MySampleApexClass2();
Double FinalPrice = MySampleApexClass2.getCalculatedValueViaPrice(100);
System.debug('FinalPrice: '+FinalPrice);
Constructors can be overloaded, i.e., a class can have more than one constructor defined with different parameters.
Example
public class MySampleApexClass3 { // Class definition and body
public static Double myValue; // Class Member variable
public static String myString; // Class Member variable
public MySampleApexClass3 () {
myValue = 100; // initialized variable when class is called
System.debug('myValue variable with no Overaloading'+myValue);
}
public MySampleApexClass3 (Integer newPrice) { // Overloaded constructor
myValue = newPrice; // initialized variable when class is called
System.debug('myValue variable with Overaloading'+myValue);
}
public static Double getCalculatedValue () { // Method definition and body
// do some calculation
myValue = myValue+10;
return myValue;
}
public static Double getCalculatedValueViaPrice (Decimal price) {
// Method definition and body
// do some calculation
myValue = myValue+price;
return myValue;
}
}
You can execute this class as we have executed it in previous example.
// Developer Console Code
MySampleApexClass3 objClass = new MySampleApexClass3();
Double FinalPrice = MySampleApexClass3.getCalculatedValueViaPrice(100);
System.debug('FinalPrice: '+FinalPrice);
An instance of class is called Object. In terms of Salesforce, object can be of class or you can create an object of sObject as well.
You can create an object of class as you might have done in Java or other object-oriented programming language.
Following is an example Class called MyClass β
// Sample Class Example
public class MyClass {
Integer myInteger = 10;
public void myMethod (Integer multiplier) {
Integer multiplicationResult;
multiplicationResult = multiplier*myInteger;
System.debug('Multiplication is '+multiplicationResult);
}
}
This is an instance class, i.e., to call or access the variables or methods of this class, you must create an instance of this class and then you can perform all the operations.
// Object Creation
// Creating an object of class
MyClass objClass = new MyClass();
// Calling Class method using Class instance
objClass.myMethod(100);
sObjects are the objects of Salesforce in which you store the data. For example, Account, Contact, etc., are custom objects. You can create object instances of these sObjects.
Following is an example of sObject initialization and shows how you can access the field of that particular object using dot notation and assign the values to fields.
// Execute the below code in Developer console by simply pasting it
// Standard Object Initialization for Account sObject
Account objAccount = new Account(); // Object initialization
objAccount.Name = 'Testr Account'; // Assigning the value to field Name of Account
objAccount.Description = 'Test Account';
insert objAccount; // Creating record using DML
System.debug('Records Has been created '+objAccount);
// Custom sObject initialization and assignment of values to field
APEX_Customer_c objCustomer = new APEX_Customer_c ();
objCustomer.Name = 'ABC Customer';
objCustomer.APEX_Customer_Decscription_c = 'Test Description';
insert objCustomer;
System.debug('Records Has been created '+objCustomer);
Static methods and variables are initialized only once when a class is loaded. Static variables are not transmitted as part of the view state for a Visualforce page.
Following is an example of Static method as well as Static variable.
// Sample Class Example with Static Method
public class MyStaticClass {
Static Integer myInteger = 10;
public static void myMethod (Integer multiplier) {
Integer multiplicationResult;
multiplicationResult = multiplier * myInteger;
System.debug('Multiplication is '+multiplicationResult);
}
}
// Calling the Class Method using Class Name and not using the instance object
MyStaticClass.myMethod(100);
Static Variable Use
Static variables will be instantiated only once when class is loaded and this phenomenon can be used to avoid the trigger recursion. Static variable value will be same within the same execution context and any class, trigger or code which is executing can refer to it and prevent the recursion.
An interface is like an Apex class in which none of the methods have been implemented. It only contains the method signatures, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.
Interfaces are used mainly for providing the abstraction layer for your code. They separate the implementation from declaration of the method.
Let's take an example of our Chemical Company. Suppose that we need to provide the discount to Premium and Ordinary customers and discounts for both will be different.
We will create an Interface called the DiscountProcessor.
// Interface
public interface DiscountProcessor {
Double percentageDiscountTobeApplied(); // method signature only
}
// Premium Customer Class
public class PremiumCustomer implements DiscountProcessor {
//Method Call
public Double percentageDiscountTobeApplied () {
// For Premium customer, discount should be 30%
return 0.30;
}
}
// Normal Customer Class
public class NormalCustomer implements DiscountProcessor {
// Method Call
public Double percentageDiscountTobeApplied () {
// For Premium customer, discount should be 10%
return 0.10;
}
}
When you implement the Interface then it is mandatory to implement the method of that Interface. If you do not implement the Interface methods, it will throw an error. You should use Interfaces when you want to make the method implementation mandatory for the developer.
SFDC do have standard interfaces like Database.Batchable, Schedulable, etc. For example, if you implement the Database.Batchable Interface, then you must implement the three methods defined in the Interface β Start, Execute and Finish.
Below is an example for Standard Salesforce provided Database.Batchable Interface which sends out emails to users with the Batch Status. This interface has 3 methods, Start, Execute and Finish. Using this interface, we can implement the Batchable functionality and it also provides the BatchableContext variable which we can use to get more information about the Batch which is executing and to perform other functionalities.
global class CustomerProessingBatch implements Database.Batchable<sobject7>,
Schedulable {
// Add here your email address
global String [] email = new String[] {'[email protected]'};
// Start Method
global Database.Querylocator start (Database.BatchableContext BC) {
// This is the Query which will determine the scope of Records and fetching the same
return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,
APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today
&& APEX_Active__c = true');
}
// Execute method
global void execute (Database.BatchableContext BC, List<sobject> scope) {
List<apex_customer__c> customerList = new List<apex_customer__c>();
List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>();
for (sObject objScope: scope) {
// type casting from generic sOject to APEX_Customer__c
APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;
newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';
newObjScope.APEX_Customer_Status__c = 'Processed';
// Add records to the List
updtaedCustomerList.add(newObjScope);
}
// Check if List is empty or not
if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {
// Update the Records
Database.update(updtaedCustomerList); System.debug('List Size
'+updtaedCustomerList.size());
}
}
// Finish Method
global void finish(Database.BatchableContext BC) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// get the job Id
AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,
a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,
a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];
System.debug('$$$ Jobid is'+BC.getJobId());
// below code will send an email to User about the status
mail.setToAddresses(email);
// Add here your email address
mail.setReplyTo('[email protected]');
mail.setSenderDisplayName('Apex Batch Processing Module');
mail.setSubject('Batch Processing '+a.Status);
mail.setPlainTextBody('The Batch Apex job processed
'+a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item
processed are'+a.JobItemsProcessed);
Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});
}
// Scheduler Method to scedule the class
global void execute(SchedulableContext sc) {
CustomerProessingBatch conInstance = new CustomerProessingBatch();
database.executebatch(conInstance,100);
}
}
To execute this class, you have to run the below code in the Developer Console.
CustomerProessingBatch objBatch = new CustomerProessingBatch ();
Database.executeBatch(objBatch);
In this chapter, we will discuss how to perform the different Database Modification Functionalities in Salesforce. There are two says with which we can perform the functionalities.
DML are the actions which are performed in order to perform insert, update, delete, upsert, restoring records, merging records, or converting leads operation.
DML is one of the most important part in Apex as almost every business case involves the changes and modifications to database.
All operations which you can perform using DML statements can be performed using Database methods as well. Database methods are the system methods which you can use to perform DML operations. Database methods provide more flexibility as compared to DML Statements.
In this chapter, we will be looking at the first approach using DML Statements. We will look at the Database Methods in a subsequent chapter.
Let us now consider the instance of the Chemical supplier company again. Our Invoice records have fields as Status, Amount Paid, Amount Remaining, Next Pay Date and Invoice Number. Invoices which have been created today and have their status as 'Pending', should be updated to 'Paid'.
Insert operation is used to create new records in Database. You can create records of any Standard or Custom object using the Insert DML statement.
Example
We can create new records in APEX_Invoice__c object as new invoices are being generated for new customer orders every day. We will create a Customer record first and then we can create an Invoice record for that new Customer record.
// fetch the invoices created today, Note, you must have at least one invoice
// created today
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c WHERE createdDate = today];
// create List to hold the updated invoice records
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test ABC';
//DML for Inserting the new Customer Records
insert objCust;
for (APEX_Invoice__c objInvoice: invoiceList) {
if (objInvoice.APEX_Status__c == 'Pending') {
objInvoice.APEX_Status__c = 'Paid';
updatedInvoiceList.add(objInvoice);
}
}
// DML Statement to update the invoice status
update updatedInvoiceList;
// Prints the value of updated invoices
System.debug('List has been updated and updated values are' + updatedInvoiceList);
// Inserting the New Records using insert DML statement
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Amount_Paid__c = 1000;
objNewInvoice.APEX_Customer__c = objCust.id;
// DML which is creating the new Invoice record which will be linked with newly
// created Customer record
insert objNewInvoice;
System.debug('New Invoice Id is '+objNewInvoice.id+' and the Invoice Number is'
+ objNewInvoice.Name);
Update operation is to perform updates on existing records. In this example, we will be updating the Status field of an existing Invoice record to 'Paid'.
Example
// Update Statement Example for updating the invoice status. You have to create
and Invoice records before executing this code. This program is updating the
record which is at index 0th position of the List.
// First, fetch the invoice created today
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c];
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
// Update the first record in the List
invoiceList[0].APEX_Status__c = 'Pending';
updatedInvoiceList.add(invoiceList[0]);
// DML Statement to update the invoice status
update updatedInvoiceList;
// Prints the value of updated invoices
System.debug('List has been updated and updated values of records are'
+ updatedInvoiceList[0]);
Upsert Operation is used to perform an update operation and if the records to be updated are not present in database, then create new records as well.
Example
Suppose, the customer records in Customer object need to be updated. We will update the existing Customer record if it is already present, else create a new one. This will be based on the value of field APEX_External_Id__c. This field will be our field to identify if the records are already present or not.
Note β Before executing this code, please create a record in Customer object with the external Id field value as '12341' and then execute the code given below β
// Example for upserting the Customer records
List<apex_customer__c> CustomerList = new List<apex_customer__c>();
for (Integer i = 0; i < 10; i++) {
apex_customer__c objcust=new apex_customer__c(name = 'Test' +i,
apex_external_id__c='1234' +i);
customerlist.add(objcust);
} //Upserting the Customer Records
upsert CustomerList;
System.debug('Code iterated for 10 times and created 9 records as one record with
External Id 12341 is already present');
for (APEX_Customer_c objCustomer: CustomerList) {
if (objCustomer.APEX_External_Id_c == '12341') {
system.debug('The Record which is already present is '+objCustomer);
}
}
You can perform the delete operation using the Delete DML.
Example
In this case, we will delete the invoices which have been created for the testing purpose, that is the ones which contain the name as 'Test'.
You can execute this snippet from the Developer console as well without creating the class.
// fetch the invoice created today
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c WHERE createdDate = today];
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test';
// Inserting the Customer Records
insert objCust;
for (APEX_Invoice__c objInvoice: invoiceList) {
if (objInvoice.APEX_Status__c == 'Pending') {
objInvoice.APEX_Status__c = 'Paid';
updatedInvoiceList.add(objInvoice);
}
}
// DML Statement to update the invoice status
update updatedInvoiceList;
// Prints the value of updated invoices
System.debug('List has been updated and updated values are' + updatedInvoiceList);
// Inserting the New Records using insert DML statement
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Amount_Paid__c = 1000;
objNewInvoice.APEX_Customer__c = objCust.id;
// DML which is creating the new record
insert objNewInvoice;
System.debug('New Invoice Id is' + objNewInvoice.id);
// Deleting the Test invoices from Database
// fetch the invoices which are created for Testing, Select name which Customer Name
// is Test.
List<apex_invoice__c> invoiceListToDelete = [SELECT id FROM APEX_Invoice__c
WHERE APEX_Customer__r.Name = 'Test'];
// DML Statement to delete the Invoices
delete invoiceListToDelete;
System.debug('Success, '+invoiceListToDelete.size()+' Records has been deleted');
You can undelete the record which has been deleted and is present in Recycle bin. All the relationships which the deleted record has, will also be restored.
Example
Suppose, the Records deleted in the previous example need to be restored. This can be achieved using the following example. The code in the previous example has been modified for this example.
// fetch the invoice created today
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c WHERE createdDate = today];
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test';
// Inserting the Customer Records
insert objCust;
for (APEX_Invoice__c objInvoice: invoiceList) {
if (objInvoice.APEX_Status__c == 'Pending') {
objInvoice.APEX_Status__c = 'Paid';
updatedInvoiceList.add(objInvoice);
}
}
// DML Statement to update the invoice status
update updatedInvoiceList;
// Prints the value of updated invoices
System.debug('List has been updated and updated values are' + updatedInvoiceList);
// Inserting the New Records using insert DML statement
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Amount_Paid__c = 1000;
objNewInvoice.APEX_Customer__c = objCust.id;
// DML which is creating the new record
insert objNewInvoice;
System.debug('New Invoice Id is '+objNewInvoice.id);
// Deleting the Test invoices from Database
// fetch the invoices which are created for Testing, Select name which Customer Name
// is Test.
List<apex_invoice__c> invoiceListToDelete = [SELECT id FROM APEX_Invoice__c
WHERE APEX_Customer__r.Name = 'Test'];
// DML Statement to delete the Invoices
delete invoiceListToDelete;
system.debug('Deleted Record Count is ' + invoiceListToDelete.size());
System.debug('Success, '+invoiceListToDelete.size() + 'Records has been deleted');
// Restore the deleted records using undelete statement
undelete invoiceListToDelete;
System.debug('Undeleted Record count is '+invoiceListToDelete.size()+'. This should
be same as Deleted Record count');
Database class methods is another way of working with DML statements which are more flexible than DML Statements like insert, update, etc.
Inserting new records via database methods is also quite simple and flexible. Let us consider the previous scenario wherein, we have inserted new records using the DML statements. We will be inserting the same using Database methods.
// Insert Operation Using Database methods
// Insert Customer Records First using simple DML Statement. This Customer Record will be
// used when we will create Invoice Records
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test';
insert objCust; // Inserting the Customer Records
// Insert Operation Using Database methods
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
List<apex_invoice__c> InvoiceListToInsert = new List<apex_invoice__c>();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Customer__c = objCust.id;
objNewInvoice.APEX_Amount_Paid__c = 1000;
InvoiceListToInsert.add(objNewInvoice);
Database.SaveResult[] srList = Database.insert(InvoiceListToInsert, false);
// Database method to insert the records in List
// Iterate through each returned result by the method
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// This condition will be executed for successful records and will fetch the ids
// of successful records
System.debug('Successfully inserted Invoice. Invoice ID: ' + sr.getId());
// Get the invoice id of inserted Account
} else {
// This condition will be executed for failed records
for(Database.Error objErr : sr.getErrors()) {
System.debug('The following error has occurred.');
// Printing error message in Debug log
System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());
System.debug('Invoice oject field which are affected by the error:'
+ objErr.getFields());
}
}
}
Let us now consider our business case example using the database methods. Suppose we need to update the status field of Invoice object but at the same time, we also require information like status of records, failed record ids, success count, etc. This is not possible by using DML Statements, hence we must use Database methods to get the status of our operation.
We will be updating the Invoice's 'Status' field if it is in status 'Pending' and date of creation is today.
The code given below will help in updating the Invoice records using the Database.update method. Also, create an Invoice record before executing this code.
// Code to update the records using the Database methods
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c WHERE createdDate = today];
// fetch the invoice created today
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
for (APEX_Invoice__c objInvoice: invoiceList) {
if (objInvoice.APEX_Status__c == 'Pending') {
objInvoice.APEX_Status__c = 'Paid';
updatedInvoiceList.add(objInvoice); //Adding records to the list
}
}
Database.SaveResult[] srList = Database.update(updatedInvoiceList, false);
// Database method to update the records in List
// Iterate through each returned result by the method
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// This condition will be executed for successful records and will fetch
// the ids of successful records
System.debug('Successfully updated Invoice. Invoice ID is : ' + sr.getId());
} else {
// This condition will be executed for failed records
for(Database.Error objErr : sr.getErrors()) {
System.debug('The following error has occurred.');
// Printing error message in Debug log
System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());
System.debug('Invoice oject field which are affected by the error:'
+ objErr.getFields());
}
}
}
We will be looking at only the Insert and Update operations in this tutorial. The other operations are quite similar to these operations and what we did in the last chapter.
Every business or application has search functionality as one of the basic requirements. For this, Salesforce.com provides two major approaches using SOSL and SOQL. Let us discuss the SOSL approach in detail in this chapter.
Searching the text string across the object and across the field will be done by using SOSL. This is Salesforce Object Search Language. It has the capability of searching a particular string across multiple objects.
SOSL statements evaluate to a list of sObjects, wherein, each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query.
Consider a business case wherein, we need to develop a program which can search a specified string. Suppose, we need to search for string 'ABC' in the Customer Name field of Invoice object. The code goes as follows β
First, you have to create a single record in Invoice object with Customer name as 'ABC' so that we can get valid result when searched.
// Program To Search the given string in all Object
// List to hold the returned results of sObject generic type
List<list<SObject>> invoiceSearchList = new List<List<SObject>>();
// SOSL query which will search for 'ABC' string in Customer Name field of Invoice Object
invoiceSearchList = [FIND 'ABC*' IN ALL FIELDS RETURNING APEX_Invoice_c
(Id,APEX_Customer_r.Name)];
// Returned result will be printed
System.debug('Search Result '+invoiceSearchList);
// Now suppose, you would like to search string 'ABC' in two objects,
// that is Invoice and Account. Then for this query goes like this:
// Program To Search the given string in Invoice and Account object,
// you could specify more objects if you want, create an Account with Name as ABC.
// List to hold the returned results of sObject generic type
List<List<SObject>> invoiceAndSearchList = new List<List<SObject>>();
// SOSL query which will search for 'ABC' string in Invoice and in Account object's fields
invoiceAndSearchList = [FIND 'ABC*' IN ALL FIELDS RETURNING APEX_Invoice__c
(Id,APEX_Customer__r.Name), Account];
// Returned result will be printed
System.debug('Search Result '+invoiceAndSearchList);
// This list will hold the returned results for Invoice Object
APEX_Invoice__c [] searchedInvoice = ((List<APEX_Invoice_c>)invoiceAndSearchList[0]);
// This list will hold the returned results for Account Object
Account [] searchedAccount = ((List<Account>)invoiceAndSearchList[1]);
System.debug('Value of searchedInvoice'+searchedInvoice+'Value of searchedAccount'
+ searchedAccount);
This is almost the same as SOQL. You can use this to fetch the object records from one object only at a time. You can write nested queries and also fetch the records from parent or child object on which you are querying now.
We will explore SOQL in the next chapter.
This is Salesforce Object Query Language designed to work with SFDC Database. It can search a record on a given criterion only in single sObject.
Like SOSL, it cannot search across multiple objects but it does support nested queries.
Consider our ongoing example of Chemical Company. Suppose, we need a list of records which are created today and whose customer name is not 'test'. In this case, we will have to use the SOQL query as given below β
// fetching the Records via SOQL
List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
InvoiceList = [SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM
APEX_Invoice__c WHERE createdDate = today AND APEX_Customer__r.Name != 'Test'];
// SOQL query for given criteria
// Printing the fetched records
System.debug('We have total '+InvoiceList.size()+' Records in List');
for (APEX_Invoice__c objInvoice: InvoiceList) {
System.debug('Record Value is '+objInvoice);
// Printing the Record fetched
}
You can run the SOQL query via the Query Editor in the Developer console as shown below.
Run the query given below in the Developer Console. Search for the Invoice records created today.
SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM APEX_Invoice__c
WHERE createdDate = today
You must select the fields for which you need the values, otherwise, it can throw run time errors.
This is one of the most important parts in SFDC as many times we need to traverse through the parent child object relationship
Also, there may be cases when you need to insert two associated objects records in Database. For example, Invoice object has relationship with the Customer object and hence one Customer can have many invoices.
Suppose, you are creating the invoice and then you need to relate this invoice to Customer. You can use the following code for this functionality β
// Now create the invoice record and relate it with the Customer object
// Before executing this, please create a Customer Records with Name 'Customer
// Creation Test'
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
// Relating Invoice to customer via id field of Customer object
objInvoice.APEX_Customer__c = [SELECT id FROM APEX_Customer__c WHERE Name =
'Customer Creation Test' LIMIT 1].id;
objInvoice.APEX_Status__c = 'Pending';
insert objInvoice; //Creating Invoice
System.debug('Newly Created Invoice'+objInvoice); //Newly created invoice
Execute this code snippet in the Developer Console. Once executed, copy the Id of invoice from the Developer console and then open the same in SFDC as shown below. You can see that the Parent record has already been assigned to Invoice record as shown below.
Let us now consider an example wherein, all the invoices related to particular customer record need to be in one place. For this, you must know the child relationship name. To see the child relationship name, go to the field detail page on the child object and check the "Child Relationship" value. In our example, it is invoices appended by __r at the end.
In this example, we will need to set up data, create a customer with name as 'ABC Customer' record and then add 3 invoices to that customer.
Now, we will fetch the invoices the Customer 'ABC Customer' has. Following is the query for the same β
// Fetching Child Records using SOQL
List<apex_customer__c> ListCustomers = [SELECT Name, Id,
(SELECT id, Name FROM Invoices__r) FROM APEX_Customer__c WHERE Name = 'ABC Customer'];
// Query for fetching the Child records along with Parent
System.debug('ListCustomers '+ListCustomers); // Parent Record
List<apex_invoice__c> ListOfInvoices = ListCustomers[0].Invoices__r;
// By this notation, you could fetch the child records and save it in List
System.debug('ListOfInvoices values of Child '+ListOfInvoices);
// Child records
You can see the Record values in the Debug logs.
Suppose, you need to fetch the Customer Name of Invoice the creation date of which is today, then you can use the query given below for the same β
Fetch the Parent record's value along with the child object.
// Fetching Parent Record Field value using SOQL
List<apex_invoice__c> ListOfInvoicesWithCustomerName = new List<apex_invoice__c>();
ListOfInvoicesWithCustomerName = [SELECT Name, id, APEX_Customer__r.Name
FROM APEX_Invoice__c LIMIT 10];
// Fetching the Parent record's values
for (APEX_Invoice__c objInv: ListOfInvoicesWithCustomerName) {
System.debug('Invoice Customer Name is '+objInv.APEX_Customer__r.Name);
// Will print the values, all the Customer Records will be printed
}
Here we have used the notation APEX_Customer__r.Name, where APEX_Customer__r is parent relationship name, here you have to append the __r at the end of the Parent field and then you can fetch the parent field value.
SOQL does have aggregate function as we have in SQL. Aggregate functions allow us to roll up and summarize the data. Let us now understand the function in detail.
Suppose, you wanted to know that what is the average revenue we are getting from Customer 'ABC Customer', then you can use this function to take up the average.
// Getting Average of all the invoices for a Perticular Customer
AggregateResult[] groupedResults = [SELECT
AVG(APEX_Amount_Paid__c)averageAmount FROM APEX_Invoice__c WHERE
APEX_Customer__r.Name = 'ABC Customer'];
Object avgPaidAmount = groupedResults[0].get('averageAmount');
System.debug('Total Average Amount Received From Customer ABC is '+avgPaidAmount);
Check the output in Debug logs. Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a readonly sObject and is only used for query results. It is useful when we need to generate the Report on Large data.
There are other aggregate functions as well which you can be used to perform data
summary.
MIN() β This can be used to find the minimum value
MAX() β This can be used to find the maximum value.
You can use the Apex variable in SOQL query to fetch the desired results. Apex variables
can be referenced by the Colon (:) notation.
// Apex Variable Reference
String CustomerName = 'ABC Customer';
List<apex_customer__c> ListCustomer = [SELECT Id, Name FROM APEX_Customer__c
WHERE Name = :CustomerName];
// Query Using Apex variable
System.debug('ListCustomer Name'+ListCustomer); // Customer Name
Apex security refers to the process of applying security settings and enforcing the sharing rules on running code. Apex classes have security setting that can be controlled via two keywords.
Apex generally runs in system context, that is, the current user's permissions. Field-level security, and sharing rules are not taken into account during code execution. Only the anonymous block code executes with the permission of the user who is executing the code.
Our Apex code should not expose the sensitive data to User which is hidden via security and sharing settings. Hence, Apex security and enforcing the sharing rule is most important.
If you use this keyword, then the Apex code will enforce the Sharing settings of current user to Apex code. This does not enforce the Profile permission, only the data level sharing settings.
Let us consider an example wherein, our User has access to 5 records, but the total number of records is 10. So when the Apex class will be declared with the "With Sharing" Keyword, it will return only 5 records on which the user has access to.
Example
First, make sure that you have created at least 10 records in the Customer object with 'Name' of 5 records as 'ABC Customer' and rest 5 records as 'XYZ Customer'. Then, create a sharing rule which will share the 'ABC Customer' with all Users. We also need to make sure that we have set the OWD of Customer object as Private.
Paste the code given below to Anonymous block in the Developer Console.
// Class With Sharing
public with sharing class MyClassWithSharing {
// Query To fetch 10 records
List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10];
public Integer executeQuery () {
System.debug('List will have only 5 records and the actual records are'
+ CustomerList.size()+' as user has access to'+CustomerList);
Integer ListSize = CustomerList.size();
return ListSize;
}
}
// Save the above class and then execute as below
// Execute class using the object of class
MyClassWithSharing obj = new MyClassWithSharing();
Integer ListSize = obj.executeQuery();
As the name suggests, class declared with this keyword executes in System mode, i.e., irrespective of the User's access to the record, query will fetch all the records.
// Class Without Sharing
public without sharing class MyClassWithoutSharing {
List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10];
// Query To fetch 10 records, this will return all the records
public Integer executeQuery () {
System.debug('List will have only 5 records and the actula records are'
+ CustomerList.size()+' as user has access to'+CustomerList);
Integer ListSize = CustomerList.size();
return ListSize;
}
}
// Output will be 10 records.
You can enable or disable an Apex class for particular profile. The steps for the same are given below. You can determine which profile should have access to which class.
Step 1 β From Setup, click Develop β Apex Classes.
Step 2 β Click the name of the class that you want to restrict. We have clicked on CustomerOperationClass.
Step 3 β Click on Security.
Step 4 β Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click on Remove.
Step 5 β Click on Save.
Step 1 β From Setup, click Manage Users β Permission Sets.
Step 2 β Select a permission set.
Step 3 β Click on Apex Class Access.
Step 4 β Click on Edit.
Step 5 β Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex classes that you want to disable from the Enabled Apex Classes list and click remove.
Step 6 β Click the Save button.
Apex invoking refers to the process of executing the Apex class. Apex class can only be executed when it is invoked via one of the ways listed below β
Triggers and Anonymous block
Triggers and Anonymous block
A trigger invoked for specified events
A trigger invoked for specified events
Asynchronous Apex
Asynchronous Apex
Scheduling an Apex class to run at specified intervals, or running a batch job
Scheduling an Apex class to run at specified intervals, or running a batch job
Web Services class
Web Services class
Apex Email Service class
Apex Email Service class
Apex Web Services, which allow exposing your methods via SOAP and REST Web services
Apex Web Services, which allow exposing your methods via SOAP and REST Web services
Visualforce Controllers
Visualforce Controllers
Apex Email Service to process inbound email
Apex Email Service to process inbound email
Invoking Apex Using JavaScript
Invoking Apex Using JavaScript
The Ajax toolkit to invoke Web service methods implemented in Apex
The Ajax toolkit to invoke Web service methods implemented in Apex
We will now understand a few common ways to invoke Apex.
You can invoke the Apex class via execute anonymous in the Developer Console as shown below β
Step 1 β Open the Developer Console.
Step 2 β Click on Debug.
Step 3 β Execute anonymous window will open as shown below. Now, click on the Execute
button β
Step 4 β Open the Debug Log when it will appear in the Logs pane.
You can call an Apex class from Trigger as well. Triggers are called when a specified event occurs and triggers can call the Apex class when executing.
Following is the sample code that shows how a class gets executed when a Trigger is called.
// Class which will gets called from trigger
public without sharing class MyClassWithSharingTrigger {
public static Integer executeQuery (List<apex_customer__c> CustomerList) {
// perform some logic and operations here
Integer ListSize = CustomerList.size();
return ListSize;
}
}
// Trigger Code
trigger Customer_After_Insert_Example on APEX_Customer__c (after insert) {
System.debug('Trigger is Called and it will call Apex Class');
MyClassWithSharingTrigger.executeQuery(Trigger.new); // Calling Apex class and
// method of an Apex class
}
// This example is for reference, no need to execute and will have detail look on
// triggers later chapters.
Apex class can be called from the Visualforce page as well. We can specify the controller or the controller extension and the specified Apex class gets called.
VF Page Code
Apex Class Code (Controller Extension)
Apex triggers are like stored procedures which execute when a particular event occurs. A trigger executes before and after an event occurs on record.
trigger triggerName on ObjectName (trigger_events) { Trigger_code_block }
Following are the events on which we can fir the trigger β
insert
update
delete
merge
upsert
undelete
Suppose we received a business requirement that we need to create an Invoice Record when Customer's 'Customer Status' field changes to Active from Inactive. For this, we will create a trigger on APEX_Customer__c object by following these steps β
Step 1 β Go to sObject
Step 2 β Click on Customer
Step 3 β Click on 'New' button in the Trigger related list and add the trigger code as give below.
// Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
List InvoiceList = new List();
for (APEX_Customer__c objCustomer: Trigger.new) {
if (objCustomer.APEX_Customer_Status__c == 'Active') {
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
// DML to insert the Invoice List in SFDC
insert InvoiceList;
}
Trigger.new β This is the context variable which stores the records currently in the trigger context, either being inserted or updated. In this case, this variable has Customer object's records which have been updated.
There are other context variables which are available in the context β trigger.old, trigger.newMap, trigger.OldMap.
The above trigger will execute when there is an update operation on the Customer records. Suppose, the invoice record needs to be inserted only when the Customer Status changes from Inactive to Active and not every time; for this, we can use another context variable trigger.oldMap which will store the key as record id and the value as old record values.
// Modified Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
for (APEX_Customer__c objCustomer: Trigger.new) {
// condition to check the old value and new value
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
// DML to insert the Invoice List in SFDC
insert InvoiceList;
}
We have used the Trigger.oldMap variable which as explained earlier, is a context variable which stores the Id and old value of records which are being updated.
Design patterns are used to make our code more efficient and to avoid hitting the governor limits. Often developers can write inefficient code that can cause repeated instantiation of objects. This can result in inefficient, poorly performing code, and potentially the breaching of governor limits. This most commonly occurs in triggers, as they can operate against a set of records.
We will see some important design pattern strategies in this chapter.
In real business case, it will be possible that you may need to process thousands of records in one go. If your trigger is not designed to handle such situations, then it may fail while
processing the records. There are some best practices which you need to follow while implementing the triggers. All triggers are bulk triggers by default, and can process multiple records at a time. You should always plan to process more than one record at a time.
Consider a business case, wherein, you need to process large number of records and you have written the trigger as given below. This is the same example which we had taken for inserting the invoice record when the Customer Status changes from Inactive to Active.
// Bad Trigger Example
trigger Customer_After_Insert on APEX_Customer__c (after update) {
for (APEX_Customer__c objCustomer: Trigger.new) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
insert objInvoice; //DML to insert the Invoice List in SFDC
}
}
}
You can now see that the DML Statement has been written in for the loop block which will work when processing only few records but when you are processing some hundreds of records, it will reach the DML Statement limit per transaction which is the governor limit. We will have a detailed look on Governor Limits in a subsequent chapter.
To avoid this, we have to make the trigger efficient for processing multiple records at a time.
The following example will help you understand the same β
// Modified Trigger Code-Bulk Trigger
trigger Customer_After_Insert on APEX_Customer__c (after update) {
List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
for (APEX_Customer__c objCustomer: Trigger.new) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
//condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);//Adding records to List
}
}
insert InvoiceList;
// DML to insert the Invoice List in SFDC, this list contains the all records
// which need to be modified and will fire only one DML
}
This trigger will only fire 1 DML statement as it will be operating over a List and the List has all the records which need to be modified.
By this way, you can avoid the DML statement governor limits.
Writing the whole code in trigger is also not a good practice. Hence you should call the Apex class and delegate the processing from Trigger to Apex class as shown below. Trigger Helper class is the class which does all the processing for trigger.
Let us consider our invoice record creation example again.
// Below is the Trigger without Helper class
trigger Customer_After_Insert on APEX_Customer__c (after update) {
List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
for (APEX_Customer__c objCustomer: Trigger.new) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
insert InvoiceList; // DML to insert the Invoice List in SFDC
}
// Below is the trigger with helper class
// Trigger with Helper Class
trigger Customer_After_Insert on APEX_Customer__c (after update) {
CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap);
// Trigger calls the helper class and does not have any code in Trigger
}
public class CustomerTriggerHelper {
public static void createInvoiceRecords (List<apex_customer__c>
customerList, Map<id, apex_customer__c> oldMapCustomer) {
List<apex_invoice__c> InvoiceList = new Listvapex_invoice__c>();
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
// objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
insert InvoiceList; // DML to insert the Invoice List in SFDC
}
}
In this, all the processing has been delegated to the helper class and when we need a new functionality we can simply add the code to the helper class without modifying the trigger.
Always create a single trigger on each object. Multiple triggers on the same object can cause the conflict and errors if it reaches the governor limits.
You can use the context variable to call the different methods from helper class as per the requirement. Consider our previous example. Suppose that our createInvoice method should be called only when the record is updated and on multiple events. Then we can control the execution as below β
// Trigger with Context variable for controlling the calling flow
trigger Customer_After_Insert on APEX_Customer__c (after update, after insert) {
if (trigger.isAfter && trigger.isUpdate) {
// This condition will check for trigger events using isAfter and isUpdate
// context variable
CustomerTriggerHelper.createInvoiceRecords(Trigger.new);
// Trigger calls the helper class and does not have any code in Trigger
// and this will be called only when trigger ids after update
}
}
// Helper Class
public class CustomerTriggerHelper {
//Method To Create Invoice Records
public static void createInvoiceRecords (List<apex_customer__c> customerList) {
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
insert InvoiceList; // DML to insert the Invoice List in SFDC
}
}
Governor execution limits ensure the efficient use of resources on the Force.com multitenant platform. It is the limit specified by the Salesforce.com on code execution for efficient processing.
As we know, Apex runs in multi-tenant environment, i.e., a single resource is shared by all the customers and organizations. So, it is necessary to make sure that no one monopolizes the resources and hence Salesforce.com has created the set of limits which governs and limits the code execution. Whenever any of the governor limits are crossed, it will throw error and will halt the execution of program.
From a Developer's perspective, it is important to ensure that our code should be scalable and should not hit the limits.
All these limits are applied on per transaction basis. A single trigger execution is one transaction.
As we have seen, the trigger design pattern helps avoid the limit error. We will now see other important limits.
You can issue only 100 queries per transaction, that is, when your code will issue more than 100 SOQL queries then it will throw error.
This example shows how SOQL query limit can be reached β
The following trigger iterates over a list of customers and updates the child record's (Invoice) description with string 'Ok to Pay'.
// Helper class:Below code needs o be checked.
public class CustomerTriggerHelper {
public static void isAfterUpdateCall(Trigger.new) {
createInvoiceRecords(trigger.new);//Method call
updateCustomerDescription(trigger.new);
}
// Method To Create Invoice Records
public static void createInvoiceRecords (List<apex_customer__c> customerList) {
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
insert InvoiceList; // DML to insert the Invoice List in SFDC
}
// Method to update the invoice records
public static updateCustomerDescription (List<apex_customer__c> customerList) {
for (APEX_Customer__c objCust: customerList) {
List<apex_customer__c> invList = [SELECT Id, Name,
APEX_Description__c FROM APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id];
// This query will fire for the number of records customer list has and will
// hit the governor limit when records are more than 100
for (APEX_Invoice__c objInv: invList) {
objInv.APEX_Description__c = 'OK To Pay';
update objInv;
// Update invoice, this will also hit the governor limit for DML if large
// number(150) of records are there
}
}
}
}
When the 'updateCustomerDescription' method is called and the number of customer records are more than 100, then it will hit the SOQL limit. To avoid this, never write the SOQL query in the For Loop. In this case, the SOQL query has been written in the For loop.
Following is an example which will show how to avoid the DML as well as the SOQL limit. We have used the nested relationship query to fetch the invoice records and used the context variable trigger.newMap to get the map of id and Customer records.
// SOQL-Good Way to Write Query and avoid limit exception
// Helper Class
public class CustomerTriggerHelper {
public static void isAfterUpdateCall(Trigger.new) {
createInvoiceRecords(trigger.new); //Method call
updateCustomerDescription(trigger.new, trigger.newMap);
}
// Method To Create Invoice Records
public static void createInvoiceRecords (List<apex_customer__c> customerList) {
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
insert InvoiceList; // DML to insert the Invoice List in SFDC
}
// Method to update the invoice records
public static updateCustomerDescription (List<apex_customer__c>
customerList, Map<id, apex_customer__c> newMapVariable) {
List<apex_customer__c> customerListWithInvoice = [SELECT id,
Name,(SELECT Id, Name, APEX_Description__c FROM APEX_Invoice__r) FROM
APEX_Customer__c WHERE Id IN :newMapVariable.keySet()];
// Query will be for only one time and fetches all the records
List<apex_invoice__c> invoiceToUpdate = new
List<apex_invoice__c>();
for (APEX_Customer__c objCust: customerList) {
for (APEX_Invoice__c objInv: invList) {
objInv.APEX_Description__c = 'OK To Pay';
invoiceToUpdate.add(objInv);
// Add the modified records to List
}
}
update invoiceToUpdate;
}
}
This example shows the Bulk trigger along with the trigger helper class pattern. You must save the helper class first and then save the trigger.
Note β Paste the below code in 'CustomerTriggerHelper' class which we have created earlier.
// Helper Class
public class CustomerTriggerHelper {
public static void isAfterUpdateCall(List<apex_customer__c> customerList,
Map<id, apex_customer__c> mapIdToCustomers, Map<id, apex_customer__c>
mapOldItToCustomers) {
createInvoiceRecords(customerList, mapOldItToCustomers); //Method call
updateCustomerDescription(customerList,mapIdToCustomers,
mapOldItToCustomers);
}
// Method To Create Invoice Records
public static void createInvoiceRecords (List<apex_customer__c>
customerList, Map<id, apex_customer__c> mapOldItToCustomers) {
List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
List<apex_customer__c> customerToInvoice = [SELECT id, Name FROM
APEX_Customer__c LIMIT 1];
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
mapOldItToCustomers.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
//condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
objInvoice.APEX_Customer__c = objCustomer.id;
InvoiceList.add(objInvoice);
}
}
system.debug('InvoiceList&&&'+InvoiceList);
insert InvoiceList;
// DML to insert the Invoice List in SFDC. This also follows the Bulk pattern
}
// Method to update the invoice records
public static void updateCustomerDescription (List<apex_customer__c>
customerList, Map<id, apex_customer__c> newMapVariable, Map<id,
apex_customer__c> oldCustomerMap) {
List<apex_customer__c> customerListWithInvoice = [SELECT id,
Name,(SELECT Id, Name, APEX_Description__c FROM Invoices__r) FROM
APEX_Customer__c WHERE Id IN :newMapVariable.keySet()];
// Query will be for only one time and fetches all the records
List<apex_invoice__c> invoiceToUpdate = new List<apex_invoice__c>();
List<apex_invoice__c> invoiceFetched = new List<apex_invoice__c>();
invoiceFetched = customerListWithInvoice[0].Invoices__r;
system.debug('invoiceFetched'+invoiceFetched);
system.debug('customerListWithInvoice****'+customerListWithInvoice);
for (APEX_Customer__c objCust: customerList) {
system.debug('objCust.Invoices__r'+objCust.Invoices__r);
if (objCust.APEX_Active__c == true &&
oldCustomerMap.get(objCust.id).APEX_Active__c == false) {
for (APEX_Invoice__c objInv: invoiceFetched) {
system.debug('I am in For Loop'+objInv);
objInv.APEX_Description__c = 'OK To Pay';
invoiceToUpdate.add(objInv);
// Add the modified records to List
}
}
}
system.debug('Value of List ***'+invoiceToUpdate);
update invoiceToUpdate;
// This statement is Bulk DML which performs the DML on List and avoids
// the DML Governor limit
}
}
// Trigger Code for this class: Paste this code in 'Customer_After_Insert'
// trigger on Customer Object
trigger Customer_After_Insert on APEX_Customer__c (after update) {
CustomerTriggerHelper.isAfterUpdateCall(Trigger.new, trigger.newMap,
trigger.oldMap);
// Trigger calls the helper class and does not have any code in Trigger
}
Following table lists down the important governor limits.
In this chapter, we will understand Batch Processing in Apex. Consider a scenario wherein, we will process large number of records on daily basis, probably the cleaning of data or maybe deleting some unused data.
Batch Apex is asynchronous execution of Apex code, specially designed for processing the large number of records and has greater flexibility in governor limits than the synchronous code.
When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex.
When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex.
Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data.
Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data.
When we are using the Batch Apex, we must implement the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.
You can monitor the class by following these steps β
To monitor or stop the execution of the batch Apex Batch job, go to Setup β Monitoring β Apex Jobs or Jobs β Apex Jobs.
Database.Batchable interface has the following three methods that need to be implemented β
Start
Execute
Finish
Let us now understand each method in detail.
The Start method is one of the three methods of the Database.Batchable interface.
Syntax
global void execute(Database.BatchableContext BC, list<sobject<) {}
This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating.
Consider the following points to understand the method β
Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed.
Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed.
Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed.
Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed.
Let us now understand the Execute method of the Database.Batchable interface.
Syntax
global void execute(Database.BatchableContext BC, list<sobject<) {}
where, list<sObject< is returned by the Database.QueryLocator method.
This method gets called after the Start method and does all the processing required for Batch Job.
We will now discuss the Finish method of the Database.Batchable interface.
Syntax
global void finish(Database.BatchableContext BC) {}
This method gets called at the end and you can do some finishing activities like sending an email with information about the batch job records processed and status.
Let us consider an example of our existing Chemical Company and assume that we have requirement to update the Customer Status and Customer Description field of Customer Records which have been marked as Active and which have created Date as today. This should be done on daily basis and an email should be sent to a User about the status of the Batch Processing. Update the Customer Status as 'Processed' and Customer Description as 'Updated Via Batch Job'.
// Batch Job for Processing the Records
global class CustomerProessingBatch implements Database.Batchable<sobject> {
global String [] email = new String[] {'[email protected]'};
// Add here your email address here
// Start Method
global Database.Querylocator start (Database.BatchableContext BC) {
return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,
APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today
AND APEX_Active__c = true');
// Query which will be determine the scope of Records fetching the same
}
// Execute method
global void execute (Database.BatchableContext BC, List<sobject> scope) {
List<apex_customer__c> customerList = new List<apex_customer__c>();
List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>();
// List to hold updated customer
for (sObject objScope: scope) {
APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;
// type casting from generic sOject to APEX_Customer__c
newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';
newObjScope.APEX_Customer_Status__c = 'Processed';
updtaedCustomerList.add(newObjScope); // Add records to the List
System.debug('Value of UpdatedCustomerList '+updtaedCustomerList);
}
if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {
// Check if List is empty or not
Database.update(updtaedCustomerList); System.debug('List Size '
+ updtaedCustomerList.size());
// Update the Records
}
}
// Finish Method
global void finish(Database.BatchableContext BC) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Below code will fetch the job Id
AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,
a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,
a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];
// get the job Id
System.debug('$$$ Jobid is'+BC.getJobId());
// below code will send an email to User about the status
mail.setToAddresses(email);
mail.setReplyTo('[email protected]'); // Add here your email address
mail.setSenderDisplayName('Apex Batch Processing Module');
mail.setSubject('Batch Processing '+a.Status);
mail.setPlainTextBody('The Batch Apex job processed'
+ a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item
processed are'+a.JobItemsProcessed);
Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});
}
}
To execute this code, first save it and then paste the following code in Execute anonymous. This will create the object of class and Database.execute method will execute the Batch job. Once the job is completed then an email will be sent to the specified email address. Make sure that you have a customer record which has Active as checked.
// Paste in Developer Console
CustomerProessingBatch objClass = new CustomerProessingBatch();
Database.executeBatch (objClass);
Once this class is executed, then check the email address you have provided where you will receive the email with information. Also, you can check the status of the batch job via the Monitoring page and steps as provided above.
If you check the debug logs, then you can find the List size which indicates how many records have been processed.
Limitations
We can only have 5 batch job processing at a time. This is one of the limitations of Batch Apex.
You can schedule the Apex class via Apex detail page as given below β
Step 1 β Go to Setup β Apex Classes, Click on Apex Classes.
Step 2 β Click on the Schedule Apex button.
Step 3 β Provide details.
You can schedule the Apex Batch Job using Schedulable Interface as given below β
// Batch Job for Processing the Records
global class CustomerProessingBatch implements Database.Batchable<sobject> {
global String [] email = new String[] {'[email protected]'};
// Add here your email address here
// Start Method
global Database.Querylocator start (Database.BatchableContext BC) {
return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,
APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today
AND APEX_Active__c = true');
// Query which will be determine the scope of Records fetching the same
}
// Execute method
global void execute (Database.BatchableContext BC, List<sobject> scope) {
List<apex_customer__c> customerList = new List<apex_customer__c>();
List<apex_customer__c> updtaedCustomerList = new
List<apex_customer__c>();//List to hold updated customer
for (sObject objScope: scope) {
APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;//type
casting from generic sOject to APEX_Customer__c
newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';
newObjScope.APEX_Customer_Status__c = 'Processed';
updtaedCustomerList.add(newObjScope);//Add records to the List
System.debug('Value of UpdatedCustomerList '+updtaedCustomerList);
}
if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {
// Check if List is empty or not
Database.update(updtaedCustomerList); System.debug('List Size'
+ updtaedCustomerList.size());
// Update the Records
}
}
// Finish Method
global void finish(Database.BatchableContext BC) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Below code will fetch the job Id
AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,
a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,
a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id
System.debug('$$$ Jobid is'+BC.getJobId());
// below code will send an email to User about the status
mail.setToAddresses(email);
mail.setReplyTo('[email protected]');//Add here your email address
mail.setSenderDisplayName('Apex Batch Processing Module');
mail.setSubject('Batch Processing '+a.Status);
mail.setPlainTextBody('The Batch Apex job processed'
+ a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item
processed are'+a.JobItemsProcessed);
Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});
}
// Scheduler Method to scedule the class
global void execute(SchedulableContext sc) {
CustomerProessingBatch conInstance = new CustomerProessingBatch();
database.executebatch(conInstance,100);
}
}
// Paste in Developer Console
CustomerProessingBatch objClass = new CustomerProcessingBatch();
Database.executeBatch (objClass);
Debugging is an important part in any programming development. In Apex, we have certain tools that can be used for debugging. One of them is the system.debug() method which prints the value and output of variable in the debug logs.
We can use the following two tools for debugging β
Developer Console
Debug Logs
You can use the Developer console and execute anonymous functionality for debugging the Apex as below β
Example
Consider our existing example of fetching the customer records which have been created today. We just want to know if the query is returning the results or not and if yes, then we will check the value of List.
Paste the code given below in execute anonymous window and follow the steps which we have done for opening execute anonymous window.
Step 1 β Open the Developer console
Step 2 β Open the Execute anonymous from 'Debug' as shown below.
Step 3 β Open the Execute Anonymous window and paste the following code and click on execute.
// Debugging The Apex
List<apex_customer__c> customerList = new List<apex_customer__c>();
customerList = [SELECT Id, Name FROM APEX_Customer__c WHERE CreatedDate =
today];
// Our Query
System.debug('Records on List are '+customerList+' And Records are '+customerList);
// Debug statement to check the value of List and Size
Step 4 β Open the Logs as shown below.
Step 5 β Enter 'USER' in filter condition as shown below.
Step 6 β Open the USER DEBUG Statement as shown below.
You can debug the same class via debug logs as well. Suppose, you have a trigger in Customer object and it needs to be debugged for some variable values, then you can do this via the debug logs as shown below β
This is the Trigger Code which updates the Description field if the modified customer is active and you want to check the values of variables and records currently in scope β
trigger CustomerTrigger on APEX_Customer__c (before update) {
List<apex_customer__c> customerList = new List<apex_customer__c>();
for (APEX_Customer__c objCust: Trigger.new) {
System.debug('objCust current value is'+objCust);
if (objCust.APEX_Active__c == true) {
objCust.APEX_Customer_Description__c = 'updated';
System.debug('The record which has satisfied the condition '+objCust);
}
}
}
Follow the steps given below to generate the Debug logs.
Step 1 β Set the Debug logs for your user. Go to Setup and type 'Debug Log' in search
setup window and then click on Link.
Step 2 β Set the debug logs as following.
Step 3 β Enter the name of User which requires setup. Enter your name here.
Step 4 β Modify the customer records as event should occur to generate the debug log.
Step 5 β Now go to the debug logs section again. Open the debug logs and click on Reset.
Step 6 β Click on the view link of the first debug log.
Step 7 β Search for the string 'USER' by using the browser search as shown below.
The debug statement will show the value of the field at which we have set the point.
Testing is the integrated part of Apex or any other application development. In Apex, we have separate test classes to develop for all the unit testing.
In SFDC, the code must have 75% code coverage in order to be deployed to Production. This code coverage is performed by the test classes. Test classes are the code snippets which test the functionality of other Apex class.
Let us write a test class for one of our codes which we have written previously. We will write test class to cover our Trigger and Helper class code. Below is the trigger and helper class which needs to be covered.
// Trigger with Helper Class
trigger Customer_After_Insert on APEX_Customer__c (after update) {
CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap);
//Trigger calls the helper class and does not have any code in Trigger
}
// Helper Class:
public class CustomerTriggerHelper {
public static void createInvoiceRecords (List<apex_customer__c>
customerList, Map<id, apex_customer__c> oldMapCustomer) {
List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
objInvoice.APEX_Customer__c = objCustomer.id;
InvoiceList.add(objInvoice);
}
}
insert InvoiceList; // DML to insert the Invoice List in SFDC
}
}
In this section, we will understand how to create a Test Class.
We need to create data for test class in our test class itself. Test class by default does not have access to organization data but if you set @isTest(seeAllData = true), then it will have the access to organization's data as well.
By using this annotation, you declared that this is a test class and it will not be counted against the organization's total code limit.
Unit test methods are the methods which do not take arguments, commit no data to the database, send no emails, and are declared with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest.
We have used the 'myUnitTest' test method in our examples.
These are the standard test methods which are available for test classes. These methods contain the event or action for which we will be simulating our test. Like in this example, we will test our trigger and helper class to simulate the fire trigger by updating the records as we have done to start and stop block. This also provides separate governor limit to the code which is in start and stop block.
This method checks the desired output with the actual. In this case, we are expecting an Invoice record to be inserted so we added assert to check the same.
Example
/**
* This class contains unit tests for validating the behavior of Apex classes
* and triggers.
*
* Unit tests are class methods that verify whether a particular piece
* of code is working properly. Unit test methods take no arguments,
* commit no data to the database, and are flagged with the testMethod
* keyword in the method definition.
*
* All test methods in an organization are executed whenever Apex code is deployed
* to a production organization to confirm correctness, ensure code
* coverage, and prevent regressions. All Apex classes are
* required to have at least 75% code coverage in order to be deployed
* to a production organization. In addition, all triggers must have some code coverage.
*
* The @isTest class annotation indicates this class only contains test
* methods. Classes defined with the @isTest annotation do not count against
* the organization size limit for all Apex scripts.
*
* See the Apex Language Reference for more information about Testing and Code Coverage.
*/
@isTest
private class CustomerTriggerTestClass {
static testMethod void myUnitTest() {
//Create Data for Customer Objet
APEX_Customer__c objCust = new APEX_Customer__c();
objCust.Name = 'Test Customer';
objCust.APEX_Customer_Status__c = 'Inactive';
insert objCust;
// Now, our trigger will fire on After update event so update the Records
Test.startTest(); // Starts the scope of test
objCust.APEX_Customer_Status__c = 'Active';
update objCust;
Test.stopTest(); // Ends the scope of test
// Now check if it is giving desired results using system.assert
// Statement.New invoice should be created
List<apex_invoice__c> invList = [SELECT Id, APEX_Customer__c FROM
APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id];
system.assertEquals(1,invList.size());
// Check if one record is created in Invoivce sObject
}
}
Follow the steps given below to run the test class β
Step 1 β Go to Apex classes β click on the class name 'CustomerTriggerTestClass'.
Step 2 β Click on Run Test button as shown.
Step 3 β Check status
Step 4 β Now check the class and trigger for which we have written the test
Our testing is successful and completed.
Till now we have developed code in Developer Edition, but in real life scenario, you have to do this development in Sandbox and then you might need to deploy this to another sandbox or production environment and this is called the deployment. In short, this is the movement of metadata from one organization to another. The reason behind this is that you cannot develop Apex in your Salesforce production organization. Live users accessing the system while you are developing can destabilize your data or corrupt your application.
Tools available for deployment β
Force.com IDE
Change Sets
SOAP API
Force.com Migration Tool
As we are using the Developer Edition for our development and learning purpose, we cannot use the Change Set or other tools which need the SFDC enterprise or other paid edition. Hence, we will be elaborating the Force.com IDE deployment method in this tutorial.
Step 1 β Open Eclipse and open the class trigger that needs to be deployed.
Step 2 β Once you click on 'Deploy to server', then enter the username and password of the organization wherein, the Component needs to be deployed.
By performing the above mentioned steps, your Apex components will be deployed to the target organization.
You can deploy Validation rules, workflow rules, Apex classes and Trigger from one organization to other by connecting them via the deployment settings. In this case, organizations must be connected.
To open the deployment setup, follow the steps given below. Remember that this feature is not available in the Developer Edition β
Step 1 β Go to Setup and search for 'Deploy'.
Step 2 β Click on 'Outbound Change Set' in order to create change set to deploy.
Step 3 β Add components to change set using the 'Add' button and then Save and click on Upload.
Step 4 β Go to the Target organization and click on the inbound change set and finally click on deploy.
We will just have a small overview of this method as this is not a commonly-used method.
You can use the method calls given below to deploy your metadata.
compileAndTest()
compileClasses()
compileTriggers()
This tool is used for the scripted deployment. You have to download the Force.com Migration tool and then you can perform the file based deployment. You can download the Force.com migration tool and then do the scripted deployment.
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2370,
"s": 2052,
"text": "Apex is a proprietary language developed by the Salesforce.com. As per the official definition, Apex is a strongly typed, object-oriented programming language that allows developers to execute the flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API."
},
{
"code": null,
"e": 2764,
"s": 2370,
"text": "It has a Java-like syntax and acts like database stored procedures. It enables the developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages.Apex code can be initiated by Web service requests and from triggers on objects. Apex is included in Performance Edition, Unlimited Edition, Enterprise Edition, and Developer Edition."
},
{
"code": null,
"e": 2820,
"s": 2764,
"text": "Let us now discuss the features of Apex as a Language β"
},
{
"code": null,
"e": 3091,
"s": 2820,
"text": "Apex has built in support for DML operations like INSERT, UPDATE, DELETE and also DML Exception handling. It has support for inline SOQL and SOSL query handling which returns the set of sObject records. We will study the sObject, SOQL, SOSL in detail in future chapters."
},
{
"code": null,
"e": 3219,
"s": 3091,
"text": "Apex is easy to use as it uses the syntax like Java. For example, variable declaration, loop syntax and conditional statements."
},
{
"code": null,
"e": 3365,
"s": 3219,
"text": "Apex is data focused and designed to execute multiple queries and DML statements together. It issues multiple transaction statements on Database."
},
{
"code": null,
"e": 3542,
"s": 3365,
"text": "Apex is a strongly typed language. It uses direct reference to schema objects like sObject and any invalid reference quickly fails if it is deleted or if is of wrong data type."
},
{
"code": null,
"e": 3797,
"s": 3542,
"text": "Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed to guard closely against runaway code, preventing it from monopolizing shared resources. Any code that violates limits fails with easy-to-understand error messages."
},
{
"code": null,
"e": 3884,
"s": 3797,
"text": "Apex is upgraded as part of Salesforce releases. We don't have to upgrade it manually."
},
{
"code": null,
"e": 4068,
"s": 3884,
"text": "Apex provides built-in support for unit test creation and execution, including test results that indicate how much code is covered, and which parts of your code can be more efficient."
},
{
"code": null,
"e": 4299,
"s": 4068,
"text": "Apex should be used when we are not able to implement the complex business functionality using the pre-built and existing out of the box functionalities. Below are the cases where we need to use apex over Salesforce configuration."
},
{
"code": null,
"e": 4333,
"s": 4299,
"text": "We can use Apex when we want to β"
},
{
"code": null,
"e": 4385,
"s": 4333,
"text": "Create Web services with integrating other systems."
},
{
"code": null,
"e": 4437,
"s": 4385,
"text": "Create Web services with integrating other systems."
},
{
"code": null,
"e": 4491,
"s": 4437,
"text": "Create email services for email blast or email setup."
},
{
"code": null,
"e": 4545,
"s": 4491,
"text": "Create email services for email blast or email setup."
},
{
"code": null,
"e": 4654,
"s": 4545,
"text": "Perform complex validation over multiple objects at the same time and also custom validation implementation."
},
{
"code": null,
"e": 4763,
"s": 4654,
"text": "Perform complex validation over multiple objects at the same time and also custom validation implementation."
},
{
"code": null,
"e": 4865,
"s": 4763,
"text": "Create complex business processes that are not supported by existing workflow functionality or flows."
},
{
"code": null,
"e": 4967,
"s": 4865,
"text": "Create complex business processes that are not supported by existing workflow functionality or flows."
},
{
"code": null,
"e": 5148,
"s": 4967,
"text": "Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records."
},
{
"code": null,
"e": 5329,
"s": 5148,
"text": "Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records."
},
{
"code": null,
"e": 5475,
"s": 5329,
"text": "Perform some logic when a record is modified or modify the related object's record when there is some event which has caused the trigger to fire."
},
{
"code": null,
"e": 5621,
"s": 5475,
"text": "Perform some logic when a record is modified or modify the related object's record when there is some event which has caused the trigger to fire."
},
{
"code": null,
"e": 5748,
"s": 5621,
"text": "As shown in the diagram below (Reference: Salesforce Developer Documentation), Apex runs entirely on demand Force.com Platform"
},
{
"code": null,
"e": 5903,
"s": 5748,
"text": "There are two sequence of actions when the developer saves the code and when an end user performs some action which invokes the Apex code as shown below β"
},
{
"code": null,
"e": 6150,
"s": 5903,
"text": "When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into a set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata."
},
{
"code": null,
"e": 6528,
"s": 6150,
"text": "When an end-user triggers the execution of Apex, by clicking a button or accessing a Visualforce page, the platform application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before returning the result. The end-user observes no differences in execution time as compared to the standard application platform request."
},
{
"code": null,
"e": 6722,
"s": 6528,
"text": "Since Apex is the proprietary language of Salesforce.com, it does not support some features which a general programming language does. Following are a few features which Apex does not support β"
},
{
"code": null,
"e": 6769,
"s": 6722,
"text": "It cannot show the elements in User Interface."
},
{
"code": null,
"e": 6816,
"s": 6769,
"text": "It cannot show the elements in User Interface."
},
{
"code": null,
"e": 6952,
"s": 6816,
"text": "You cannot change the standard SFDC provided functionality and also it is not possible to prevent the standard functionality execution."
},
{
"code": null,
"e": 7088,
"s": 6952,
"text": "You cannot change the standard SFDC provided functionality and also it is not possible to prevent the standard functionality execution."
},
{
"code": null,
"e": 7171,
"s": 7088,
"text": "Creating multiple threads is also not possible as we can do it in other languages."
},
{
"code": null,
"e": 7254,
"s": 7171,
"text": "Creating multiple threads is also not possible as we can do it in other languages."
},
{
"code": null,
"e": 7360,
"s": 7254,
"text": "Apex code typically contains many things that we might be familiar with from other programming languages."
},
{
"code": null,
"e": 7545,
"s": 7360,
"text": "As strongly typed language, you must declare every variable with data type in Apex. As seen in the code below (screenshot below), lstAcc is declared with data type as List of Accounts."
},
{
"code": null,
"e": 7681,
"s": 7545,
"text": "This will be used to fetch the data from Salesforce database. The query shown in screenshot below is fetching data from Account object."
},
{
"code": null,
"e": 7902,
"s": 7681,
"text": "This loop statement is used for iterating over a list or iterating over a piece of code for a specified number of times. In the code shown in the screenshot below, iteration will be same as the number of records we have."
},
{
"code": null,
"e": 8189,
"s": 7902,
"text": "The If statement is used for flow control in this code. Based on certain condition, it is decided whether to go for execution or to stop the execution of the particular piece of code. For example, in the code shown below, it is checking whether the list is empty or it contains records."
},
{
"code": null,
"e": 8362,
"s": 8189,
"text": "Performs the records insert, update, upsert, delete operation on the records in database. For example, the code given below helps in updating Accounts with new field value."
},
{
"code": null,
"e": 8514,
"s": 8362,
"text": "Following is an example of how an Apex code snippet will look like. We are going to study all these Apex programming concepts further in this tutorial."
},
{
"code": null,
"e": 8695,
"s": 8514,
"text": "In this chapter, we will understand the environment for our Salesforce Apex development. It is assumed that you already have a Salesforce edition set up for doing Apex development."
},
{
"code": null,
"e": 9089,
"s": 8695,
"text": "You can develop the Apex code in either Sandbox or Developer edition of Salesforce. A Sandbox organization is a copy of your organization in which you can write code and test it without taking the risk of data modification or disturbing the normal functionality. As per the standard industrial practice, you have to develop the code in Sandbox and then deploy it to the Production environment."
},
{
"code": null,
"e": 9321,
"s": 9089,
"text": "For this tutorial, we will be using the Developer edition of Salesforce. In the Developer edition, you will not have the option of creating a Sandbox organization. The Sandbox features are available in other editions of Salesforce."
},
{
"code": null,
"e": 9408,
"s": 9321,
"text": "In all the editions, we can use any of the following three tools to develop the code β"
},
{
"code": null,
"e": 9436,
"s": 9408,
"text": "Force.com Developer Console"
},
{
"code": null,
"e": 9450,
"s": 9436,
"text": "Force.com IDE"
},
{
"code": null,
"e": 9495,
"s": 9450,
"text": "Code Editor in the Salesforce User Interface"
},
{
"code": null,
"e": 9636,
"s": 9495,
"text": "Note β We will be utilizing the Developer Console throughout our tutorial for code execution as it is simple and user friendly for learning."
},
{
"code": null,
"e": 9811,
"s": 9636,
"text": "The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your Salesforce organization."
},
{
"code": null,
"e": 9862,
"s": 9811,
"text": "Follow these steps to open the Developer Console β"
},
{
"code": null,
"e": 9902,
"s": 9862,
"text": "Step 1 β Go to Name β Developer Console"
},
{
"code": null,
"e": 9997,
"s": 9902,
"text": "Step 2 β Click on \"Developer Console\" and a window will appear as in the following screenshot."
},
{
"code": null,
"e": 10079,
"s": 9997,
"text": "Following are a few operations that can be performed using the Developer Console."
},
{
"code": null,
"e": 10272,
"s": 10079,
"text": "Writing and compiling code β You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported."
},
{
"code": null,
"e": 10465,
"s": 10272,
"text": "Writing and compiling code β You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported."
},
{
"code": null,
"e": 10641,
"s": 10465,
"text": "Debugging β You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported."
},
{
"code": null,
"e": 10817,
"s": 10641,
"text": "Debugging β You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported."
},
{
"code": null,
"e": 10894,
"s": 10817,
"text": "Testing β You can view debug logs and set checkpoints that aid in debugging."
},
{
"code": null,
"e": 10971,
"s": 10894,
"text": "Testing β You can view debug logs and set checkpoints that aid in debugging."
},
{
"code": null,
"e": 11146,
"s": 10971,
"text": "Checking performance β You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage."
},
{
"code": null,
"e": 11321,
"s": 11146,
"text": "Checking performance β You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage."
},
{
"code": null,
"e": 11399,
"s": 11321,
"text": "SOQL queries β You can inspect debug logs to locate performance bottlenecks. "
},
{
"code": null,
"e": 11477,
"s": 11399,
"text": "SOQL queries β You can inspect debug logs to locate performance bottlenecks. "
},
{
"code": null,
"e": 11649,
"s": 11477,
"text": "Color coding and autocomplete β The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names."
},
{
"code": null,
"e": 11821,
"s": 11649,
"text": "Color coding and autocomplete β The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names."
},
{
"code": null,
"e": 11974,
"s": 11821,
"text": "All the code snippets mentioned in this tutorial need to be executed in the developer console. Follow these steps to execute steps in Developer Console."
},
{
"code": null,
"e": 12137,
"s": 11974,
"text": "Step 1 β Login to the Salesforce.com using login.salesforce.com. Copy the code snippets mentioned in the tutorial. For now, we will use the following sample code."
},
{
"code": null,
"e": 12218,
"s": 12137,
"text": "String myString = 'MyString';\nSystem.debug('Value of String Variable'+myString);"
},
{
"code": null,
"e": 12344,
"s": 12218,
"text": "Step 2 β To open the Developer Console, click on Name β Developer Console and then click on Execute Anonymous as shown below."
},
{
"code": null,
"e": 12422,
"s": 12344,
"text": "Step 3 β In this step, a window will appear and you can paste the code there."
},
{
"code": null,
"e": 12560,
"s": 12422,
"text": "Step 4 β When we click on Execute, the debug logs will open. Once the log appears in window as shown below, then click on the log record."
},
{
"code": null,
"e": 12720,
"s": 12560,
"text": "Then type 'USER' in the window as shown below and the output statement will appear in the debug window. This 'USER' statement is used for filtering the output."
},
{
"code": null,
"e": 12832,
"s": 12720,
"text": "So basically, you will be following all the above mentioned steps to execute any code\nsnippet in this tutorial."
},
{
"code": null,
"e": 13124,
"s": 12832,
"text": "For our tutorial, we will be implementing the CRM application for a Chemical Equipment and Processing Company. This company deals with suppliers and provides services. We will work out small code snippets related to this example throughout our tutorial to understand every concept in detail."
},
{
"code": null,
"e": 13388,
"s": 13124,
"text": "For executing the code in this tutorial, you will need to have two objects created: Customer and Invoice objects. If you already know how to create these objects in Salesforce, you can skip the steps given below. Else, you can follow the step by step guide below."
},
{
"code": null,
"e": 13437,
"s": 13388,
"text": "We will be setting up the Customer object first."
},
{
"code": null,
"e": 13550,
"s": 13437,
"text": "Step 1 β Go to Setup and then search for 'Object' as shown below. Then click on the Objects link as shown below."
},
{
"code": null,
"e": 13652,
"s": 13550,
"text": "Step 2 β Once the object page is opened, then click on the 'Create New Object' button as shown below."
},
{
"code": null,
"e": 13941,
"s": 13652,
"text": "Step 3 β After clicking on button, the new object creation page will appear and then enter all the object details as entered below. Object name should be Customer. You just have to enter the information in the field as shown in the screenshot below and keep other default things as it is."
},
{
"code": null,
"e": 14001,
"s": 13941,
"text": "Enter the information and then click on the 'Save' button β"
},
{
"code": null,
"e": 14081,
"s": 14001,
"text": "By following the above steps, we have successfully created the Customer object."
},
{
"code": null,
"e": 14295,
"s": 14081,
"text": "Now that we have our Customer object set up, we will create a field 'Active' and then you can create the other fields by following similar steps. The Name and API name of the field will be given in the screenshot."
},
{
"code": null,
"e": 14405,
"s": 14295,
"text": "Step 1 β We will be creating a field named as 'Active' of data type as Checkbox. Go to Setup and click on it."
},
{
"code": null,
"e": 14466,
"s": 14405,
"text": "Step 2 β Search for 'Object' as shown below and click on it."
},
{
"code": null,
"e": 14503,
"s": 14466,
"text": "Step 3 β Click on object 'Customer'."
},
{
"code": null,
"e": 14623,
"s": 14503,
"text": "Step 4 β Once you have clicked on the Customer object link and the object detail page appears, click on the New button."
},
{
"code": null,
"e": 14686,
"s": 14623,
"text": "Step 5 β Now, select the data type as Checkbox and click Next."
},
{
"code": null,
"e": 14742,
"s": 14686,
"text": "Step 6 β Enter the field name and label as shown below."
},
{
"code": null,
"e": 14789,
"s": 14742,
"text": "Step 7 β Click on Visible and then click Next."
},
{
"code": null,
"e": 14819,
"s": 14789,
"text": "Step 8 β Now click on 'Save'."
},
{
"code": null,
"e": 15050,
"s": 14819,
"text": "By following the above steps, our custom field 'Active' is created. You have to follow all the above custom field creation steps for the remaining fields. This is the final view of customer object once all the fields are created β"
},
{
"code": null,
"e": 15146,
"s": 15050,
"text": "Step 1 β Go to Setup and search for 'Object' and then click on the Objects link as shown below."
},
{
"code": null,
"e": 15248,
"s": 15146,
"text": "Step 2 β Once the object page is opened, then click on the 'Create New Object' button as shown below."
},
{
"code": null,
"e": 15513,
"s": 15248,
"text": "Step 3 β After clicking on the button, the new object creation page will appear as shown in the screenshot below. You need to enter the details here. The object name should be Invoice. This is similar to how we created the Customer object earlier in this tutorial."
},
{
"code": null,
"e": 15596,
"s": 15513,
"text": "Step 4 β Enter the information as shown below and then click on the 'Save' button."
},
{
"code": null,
"e": 15659,
"s": 15596,
"text": "By following these steps, your Invoice object will be created."
},
{
"code": null,
"e": 15736,
"s": 15659,
"text": "We will be creating the field Description on Invoice object as shown below β"
},
{
"code": null,
"e": 15774,
"s": 15736,
"text": "Step 1 β Go to Setup and click on it."
},
{
"code": null,
"e": 15835,
"s": 15774,
"text": "Step 2 β Search for 'Object' as shown below and click on it."
},
{
"code": null,
"e": 15871,
"s": 15835,
"text": "Step 3 β Click on object 'Invoice'."
},
{
"code": null,
"e": 15896,
"s": 15871,
"text": "And then click on 'New'."
},
{
"code": null,
"e": 15970,
"s": 15896,
"text": "Step 4 β Select the data type as Text Area and then click on Next button."
},
{
"code": null,
"e": 16017,
"s": 15970,
"text": "Step 5 β Enter the information as given below."
},
{
"code": null,
"e": 16058,
"s": 16017,
"text": "Step 6 β Click on Visible and then Next."
},
{
"code": null,
"e": 16082,
"s": 16058,
"text": "Step 7 β Click on Save."
},
{
"code": null,
"e": 16148,
"s": 16082,
"text": "Similarly, you can create the other fields on the Invoice object."
},
{
"code": null,
"e": 16308,
"s": 16148,
"text": "By this, we have created the objects that are needed for this tutorial. We will be learning various examples in the subsequent chapters based on these objects."
},
{
"code": null,
"e": 16674,
"s": 16308,
"text": "The Apex language is strongly typed so every variable in Apex will be declared with the specific data type. All apex variables are initialized to null initially. It is always recommended for a developer to make sure that proper values are assigned to the variables. Otherwise such variables when used, will throw null pointer exceptions or any unhandled exceptions."
},
{
"code": null,
"e": 16715,
"s": 16674,
"text": "Apex supports the following data types β"
},
{
"code": null,
"e": 16789,
"s": 16715,
"text": "Primitive (Integer, Double, Long, Date, Datetime, String, ID, or Boolean)"
},
{
"code": null,
"e": 16863,
"s": 16789,
"text": "Primitive (Integer, Double, Long, Date, Datetime, String, ID, or Boolean)"
},
{
"code": null,
"e": 16927,
"s": 16863,
"text": "Collections (Lists, Sets and Maps) (To be covered in Chapter 6)"
},
{
"code": null,
"e": 16991,
"s": 16927,
"text": "Collections (Lists, Sets and Maps) (To be covered in Chapter 6)"
},
{
"code": null,
"e": 16999,
"s": 16991,
"text": "sObject"
},
{
"code": null,
"e": 17007,
"s": 16999,
"text": "sObject"
},
{
"code": null,
"e": 17013,
"s": 17007,
"text": "Enums"
},
{
"code": null,
"e": 17019,
"s": 17013,
"text": "Enums"
},
{
"code": null,
"e": 17092,
"s": 17019,
"text": "Classes, Objects and Interfaces (To be covered in Chapter 11, 12 and 13)"
},
{
"code": null,
"e": 17165,
"s": 17092,
"text": "Classes, Objects and Interfaces (To be covered in Chapter 11, 12 and 13)"
},
{
"code": null,
"e": 17389,
"s": 17165,
"text": "In this chapter, we will look at all the Primitive Data Types, sObjects and Enums. We will be looking at Collections, Classes, Objects and Interfaces in upcoming chapters since they are key topics to be learnt individually."
},
{
"code": null,
"e": 17466,
"s": 17389,
"text": "In this section, we will discuss the Primitive Data Types supported by Apex."
},
{
"code": null,
"e": 17621,
"s": 17466,
"text": "A 32-bit number that does not include any decimal point. The value range for this starts from -2,147,483,648 and the maximum value is up to 2,147,483,647."
},
{
"code": null,
"e": 17629,
"s": 17621,
"text": "Example"
},
{
"code": null,
"e": 17772,
"s": 17629,
"text": "We want to declare a variable which will store the quantity of barrels which need to be shipped to the buyer of the chemical processing plant."
},
{
"code": null,
"e": 17868,
"s": 17772,
"text": "Integer barrelNumbers = 1000;\nsystem.debug(' value of barrelNumbers variable: '+barrelNumbers);"
},
{
"code": null,
"e": 18017,
"s": 17868,
"text": "The System.debug() function prints the value of variable so that we can use this to debug or to get to know what value the variable holds currently."
},
{
"code": null,
"e": 18179,
"s": 18017,
"text": "Paste the above code to the Developer console and click on Execute. Once the logs are generated, then it will show the value of variable \"barrelNumbers\" as 1000."
},
{
"code": null,
"e": 18356,
"s": 18179,
"text": "This variable can either be true, false or null. Many times, this type of variable can be used as flag in programming to identify if the particular condition is set or not set."
},
{
"code": null,
"e": 18364,
"s": 18356,
"text": "Example"
},
{
"code": null,
"e": 18449,
"s": 18364,
"text": "If the Boolean shipmentDispatched is to be set as true, then it can be declared as β"
},
{
"code": null,
"e": 18569,
"s": 18449,
"text": "Boolean shipmentDispatched;\nshipmentDispatched = true;\nSystem.debug('Value of shipmentDispatched '+shipmentDispatched);"
},
{
"code": null,
"e": 18740,
"s": 18569,
"text": "This variable type indicates a date. This can only store the date and not the time. For saving the date along with time, we will need to store it in variable of DateTime."
},
{
"code": null,
"e": 18748,
"s": 18740,
"text": "Example"
},
{
"code": null,
"e": 18822,
"s": 18748,
"text": "Consider the following example to understand how the Date variable works."
},
{
"code": null,
"e": 18958,
"s": 18822,
"text": "//ShipmentDate can be stored when shipment is dispatched.\nDate ShipmentDate = date.today();\nSystem.debug('ShipmentDate '+ShipmentDate);"
},
{
"code": null,
"e": 19089,
"s": 18958,
"text": "This is a 64-bit number without a decimal point. This is used when we need a range of values wider than those provided by Integer."
},
{
"code": null,
"e": 19097,
"s": 19089,
"text": "Example"
},
{
"code": null,
"e": 19177,
"s": 19097,
"text": "If the company revenue is to be stored, then we will use the data type as Long."
},
{
"code": null,
"e": 19266,
"s": 19177,
"text": "Long companyRevenue = 21474838973344648L;\nsystem.debug('companyRevenue'+companyRevenue);"
},
{
"code": null,
"e": 19500,
"s": 19266,
"text": "We can refer this as any data type which is supported in Apex. For example, Class variable can be object of that class, and the sObject generic type is also an object and similarly specific object type like Account is also an Object."
},
{
"code": null,
"e": 19508,
"s": 19500,
"text": "Example"
},
{
"code": null,
"e": 19583,
"s": 19508,
"text": "Consider the following example to understand how the bject variable works."
},
{
"code": null,
"e": 19684,
"s": 19583,
"text": "Account objAccount = new Account (Name = 'Test Chemical');\nsystem.debug('Account value'+objAccount);"
},
{
"code": null,
"e": 19762,
"s": 19684,
"text": "Note β You can create an object of predefined class as well, as given below β"
},
{
"code": null,
"e": 19830,
"s": 19762,
"text": "//Class Name: MyApexClass\nMyApexClass classObj = new MyApexClass();"
},
{
"code": null,
"e": 19893,
"s": 19830,
"text": "This is the class object which will be used as class variable."
},
{
"code": null,
"e": 20191,
"s": 19893,
"text": "String is any set of characters within single quotes. It does not have any limit for the number of characters. Here, the heap size will be used to determine the number of characters. This puts a curb on the monopoly of resources by the Apex program and also ensures that it does not get too large."
},
{
"code": null,
"e": 20199,
"s": 20191,
"text": "Example"
},
{
"code": null,
"e": 20297,
"s": 20199,
"text": "String companyName = 'Abc International';\nSystem.debug('Value companyName variable'+companyName);"
},
{
"code": null,
"e": 20420,
"s": 20297,
"text": "This variable is used to store the particular time. This variable should always be declared with the system static method."
},
{
"code": null,
"e": 20756,
"s": 20420,
"text": "The Blob is a collection of Binary data which is stored as object. This will be used when we want to store the attachment in salesforce into a variable. This data type converts the attachments into a single object. If the blob is to be converted into a string, then we can make use of the toString and the valueOf methods for the same."
},
{
"code": null,
"e": 20943,
"s": 20756,
"text": "This is a special data type in Salesforce. It is similar to a table in SQL and contains fields which are similar to columns in SQL. There are two types of sObjects β Standard and Custom."
},
{
"code": null,
"e": 21080,
"s": 20943,
"text": "For example, Account is a standard sObject and any other user-defined object (like Customer object that we created) is a Custom sObject."
},
{
"code": null,
"e": 21088,
"s": 21080,
"text": "Example"
},
{
"code": null,
"e": 21593,
"s": 21088,
"text": "//Declaring an sObject variable of type Account\nAccount objAccount = new Account();\n\n//Assignment of values to fields of sObjects\nobjAccount.Name = 'ABC Customer';\nobjAccount.Description = 'Test Account';\nSystem.debug('objAccount variable value'+objAccount);\n\n//Declaring an sObject for custom object APEX_Invoice_c\nAPEX_Customer_c objCustomer = new APEX_Customer_c();\n\n//Assigning value to fields\nobjCustomer.APEX_Customer_Decscription_c = 'Test Customer';\nSystem.debug('value objCustomer'+objCustomer);"
},
{
"code": null,
"e": 21790,
"s": 21593,
"text": "Enum is an abstract data type that stores one value of a finite set of specified identifiers. You can use the keyword Enum to define an Enum. Enum can be used as any other data type in Salesforce."
},
{
"code": null,
"e": 21798,
"s": 21790,
"text": "Example"
},
{
"code": null,
"e": 21888,
"s": 21798,
"text": "You can declare the possible names of Chemical Compound by executing the following\ncode β"
},
{
"code": null,
"e": 22040,
"s": 21888,
"text": "//Declaring enum for Chemical Compounds\npublic enum Compounds {HCL, H2SO4, NACL, HG}\nCompounds objC = Compounds.HCL;\nSystem.debug('objC value: '+objC);"
},
{
"code": null,
"e": 22223,
"s": 22040,
"text": "Java and Apex are similar in a lot of ways. Variable declaration in Java and Apex is also quite the same. We will discuss a few examples to understand how to declare local variables."
},
{
"code": null,
"e": 22375,
"s": 22223,
"text": "String productName = 'HCL';\nInteger i = 0;\nSet<string> setOfProducts = new Set<string>();\nMap<id, string> mapOfProductIdToName = new Map<id, string>();"
},
{
"code": null,
"e": 22437,
"s": 22375,
"text": "Note that all the variables are assigned with the value null."
},
{
"code": null,
"e": 22457,
"s": 22437,
"text": "Declaring Variables"
},
{
"code": null,
"e": 22532,
"s": 22457,
"text": "You can declare the variables in Apex like String and Integer as follows β"
},
{
"code": null,
"e": 22717,
"s": 22532,
"text": "String strName = 'My String'; //String variable declaration\nInteger myInteger = 1; //Integer variable declaration\nBoolean mtBoolean = true; //Boolean variable declaration"
},
{
"code": null,
"e": 22753,
"s": 22717,
"text": "Apex variables are Case-Insensitive"
},
{
"code": null,
"e": 22899,
"s": 22753,
"text": "This means that the code given below will throw an error since the variable 'm' has been declared two times and both will be treated as the same."
},
{
"code": null,
"e": 23085,
"s": 22899,
"text": "Integer m = 100;\nfor (Integer i = 0; i<10; i++) {\n integer m = 1; //This statement will throw an error as m is being declared\n again\n System.debug('This code will throw error');\n}"
},
{
"code": null,
"e": 23104,
"s": 23085,
"text": "Scope of Variables"
},
{
"code": null,
"e": 23434,
"s": 23104,
"text": "An Apex variable is valid from the point where it is declared in code. So it is not allowed to redefine the same variable again and in code block. Also, if you declare any variable in a method, then that variable scope will be limited to that particular method only. However, class variables can be accessed throughout the class."
},
{
"code": null,
"e": 23442,
"s": 23434,
"text": "Example"
},
{
"code": null,
"e": 23804,
"s": 23442,
"text": "//Declare variable Products\nList<string> Products = new List<strings>();\nProducts.add('HCL');\n\n//You cannot declare this variable in this code clock or sub code block again\n//If you do so then it will throw the error as the previous variable in scope\n//Below statement will throw error if declared in same code block\nList<string> Products = new List<strings>();"
},
{
"code": null,
"e": 23908,
"s": 23804,
"text": "String in Apex, as in any other programming language, is any set of characters with no character limit."
},
{
"code": null,
"e": 23916,
"s": 23908,
"text": "Example"
},
{
"code": null,
"e": 24014,
"s": 23916,
"text": "String companyName = 'Abc International';\nSystem.debug('Value companyName variable'+companyName);"
},
{
"code": null,
"e": 24161,
"s": 24014,
"text": "String class in Salesforce has many methods. We will take a look at some of the most important and frequently used string methods in this chapter."
},
{
"code": null,
"e": 24244,
"s": 24161,
"text": "This method will return true if the given string contains the substring mentioned."
},
{
"code": null,
"e": 24251,
"s": 24244,
"text": "Syntax"
},
{
"code": null,
"e": 24294,
"s": 24251,
"text": "public Boolean contains(String substring)\n"
},
{
"code": null,
"e": 24302,
"s": 24294,
"text": "Example"
},
{
"code": null,
"e": 24506,
"s": 24302,
"text": "String myProductName1 = 'HCL';\nString myProductName2 = 'NAHCL';\nBoolean result = myProductName2.contains(myProductName1);\nSystem.debug('O/p will be true as it contains the String and Output is:'+result);"
},
{
"code": null,
"e": 24751,
"s": 24506,
"text": "This method will return true if the given string and the string passed in the method have the same binary sequence of characters and they are not null. You can compare the SFDC record id as well using this method. This method is case-sensitive."
},
{
"code": null,
"e": 24758,
"s": 24751,
"text": "Syntax"
},
{
"code": null,
"e": 24796,
"s": 24758,
"text": "public Boolean equals(Object string)\n"
},
{
"code": null,
"e": 24804,
"s": 24796,
"text": "Example"
},
{
"code": null,
"e": 24997,
"s": 24804,
"text": "String myString1 = 'MyString';\nString myString2 = 'MyString';\nBoolean result = myString2.equals(myString1);\nSystem.debug('Value of Result will be true as they are same and Result is:'+result);"
},
{
"code": null,
"e": 25146,
"s": 24997,
"text": "This method will return true if stringtoCompare has the same sequence of characters as the given string. However, this method is not case-sensitive."
},
{
"code": null,
"e": 25153,
"s": 25146,
"text": "Syntax"
},
{
"code": null,
"e": 25210,
"s": 25153,
"text": "public Boolean equalsIgnoreCase(String stringtoCompare)\n"
},
{
"code": null,
"e": 25218,
"s": 25210,
"text": "Example"
},
{
"code": null,
"e": 25329,
"s": 25218,
"text": "The following code will return true as string characters and sequence are same, ignoring the case sensitivity."
},
{
"code": null,
"e": 25532,
"s": 25329,
"text": "String myString1 = 'MySTRING';\nString myString2 = 'MyString';\nBoolean result = myString2.equalsIgnoreCase(myString1);\nSystem.debug('Value of Result will be true as they are same and Result is:'+result);"
},
{
"code": null,
"e": 25864,
"s": 25532,
"text": "This method removes the string provided in stringToRemove from the given string. This is useful when you want to remove some specific characters from string and are not aware of the exact index of the characters to remove. This method is case sensitive and will not work if the same character sequence occurs but case is different."
},
{
"code": null,
"e": 25871,
"s": 25864,
"text": "Syntax"
},
{
"code": null,
"e": 25916,
"s": 25871,
"text": "public String remove(String stringToRemove)\n"
},
{
"code": null,
"e": 25924,
"s": 25916,
"text": "Example"
},
{
"code": null,
"e": 26175,
"s": 25924,
"text": "String myString1 = 'This Is MyString Example';\nString stringToRemove = 'MyString';\nString result = myString1.remove(stringToRemove);\nSystem.debug('Value of Result will be 'This Is Example' as we have removed the MyString \n and Result is :'+result);"
},
{
"code": null,
"e": 26324,
"s": 26175,
"text": "This method removes the string provided in stringToRemove from the given string but only if it occurs at the end. This method is not case-sensitive."
},
{
"code": null,
"e": 26331,
"s": 26324,
"text": "Syntax"
},
{
"code": null,
"e": 26389,
"s": 26331,
"text": "public String removeEndIgnoreCase(String stringToRemove)\n"
},
{
"code": null,
"e": 26397,
"s": 26389,
"text": "Example"
},
{
"code": null,
"e": 26661,
"s": 26397,
"text": "String myString1 = 'This Is MyString EXAMPLE';\nString stringToRemove = 'Example';\nString result = myString1.removeEndIgnoreCase(stringToRemove);\nSystem.debug('Value of Result will be 'This Is MyString' as we have removed the 'Example'\n and Result is :'+result);"
},
{
"code": null,
"e": 26757,
"s": 26661,
"text": "This method will return true if the given string starts with the prefix provided in the\nmethod."
},
{
"code": null,
"e": 26764,
"s": 26757,
"text": "Syntax"
},
{
"code": null,
"e": 26806,
"s": 26764,
"text": "public Boolean startsWith(String prefix)\n"
},
{
"code": null,
"e": 26814,
"s": 26806,
"text": "Example"
},
{
"code": null,
"e": 27043,
"s": 26814,
"text": "String myString1 = 'This Is MyString EXAMPLE';\nString prefix = 'This';\nBoolean result = myString1.startsWith(prefix);\nSystem.debug(' This will return true as our String starts with string 'This' and the \n Result is :'+result);"
},
{
"code": null,
"e": 27273,
"s": 27043,
"text": "Arrays in Apex are basically the same as Lists in Apex. There is no logical distinction between the Arrays and Lists as their internal data structure and methods are also same but the array syntax is little traditional like Java."
},
{
"code": null,
"e": 27327,
"s": 27273,
"text": "Below is the representation of an Array of Products β"
},
{
"code": null,
"e": 27341,
"s": 27327,
"text": "Index 0 β HCL"
},
{
"code": null,
"e": 27357,
"s": 27341,
"text": "Index 1 β H2SO4"
},
{
"code": null,
"e": 27372,
"s": 27357,
"text": "Index 2 β NACL"
},
{
"code": null,
"e": 27386,
"s": 27372,
"text": "Index 3 β H2O"
},
{
"code": null,
"e": 27399,
"s": 27386,
"text": "Index 4 β N2"
},
{
"code": null,
"e": 27414,
"s": 27399,
"text": "Index 5 β U296"
},
{
"code": null,
"e": 27465,
"s": 27414,
"text": "<String> [] arrayOfProducts = new List<String>();\n"
},
{
"code": null,
"e": 27660,
"s": 27465,
"text": "Suppose, we have to store the name of our Products β we can use the Array where in, we will store the Product Names as shown below. You can access the particular Product by specifying the index."
},
{
"code": null,
"e": 28089,
"s": 27660,
"text": "//Defining array\nString [] arrayOfProducts = new List<String>();\n\n//Adding elements in Array\narrayOfProducts.add('HCL');\narrayOfProducts.add('H2SO4');\narrayOfProducts.add('NACL');\narrayOfProducts.add('H2O');\narrayOfProducts.add('N2');\narrayOfProducts.add('U296');\n\nfor (Integer i = 0; i<arrayOfProducts.size(); i++) {\n //This loop will print all the elements in array\n system.debug('Values In Array: '+arrayOfProducts[i]);\n}"
},
{
"code": null,
"e": 28161,
"s": 28089,
"text": "You can access any element in array by using the index as shown below β"
},
{
"code": null,
"e": 28293,
"s": 28161,
"text": "//Accessing the element in array\n//We would access the element at Index 3\nSystem.debug('Value at Index 3 is :'+arrayOfProducts[3]);"
},
{
"code": null,
"e": 28426,
"s": 28293,
"text": "As in any other programming language, Constants are the variables which do not change their value once declared or assigned a value."
},
{
"code": null,
"e": 28608,
"s": 28426,
"text": "In Apex, Constants are used when we want to define variables which should have constant value throughout the program execution. Apex constants are declared with the keyword 'final'."
},
{
"code": null,
"e": 28708,
"s": 28608,
"text": "Consider a CustomerOperationClass class and a constant variable regularCustomerDiscount\ninside it β"
},
{
"code": null,
"e": 29018,
"s": 28708,
"text": "public class CustomerOperationClass {\n static final Double regularCustomerDiscount = 0.1;\n static Double finalPrice = 0;\n \n public static Double provideDiscount (Integer price) {\n //calculate the discount\n finalPrice = price - price * regularCustomerDiscount;\n return finalPrice;\n }\n}"
},
{
"code": null,
"e": 29139,
"s": 29018,
"text": "To see the Output of the above class, you have to execute the following code in the Developer Console Anonymous Window β"
},
{
"code": null,
"e": 29244,
"s": 29139,
"text": "Double finalPrice = CustomerOperationClass.provideDiscount(100);\nSystem.debug('finalPrice '+finalPrice);"
},
{
"code": null,
"e": 29559,
"s": 29244,
"text": "Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false."
},
{
"code": null,
"e": 29896,
"s": 29559,
"text": "In this chapter, we will be studying the basic and advanced structure of decision-making and conditional statements in Apex. Decision-making is necessary to control the flow of execution when certain condition is met or not. Following is the general form of a typical decision-making structure found in most of the programming languages"
},
{
"code": null,
"e": 29981,
"s": 29896,
"text": "An if statement consists of a Boolean expression followed by one or more statements."
},
{
"code": null,
"e": 30097,
"s": 29981,
"text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false."
},
{
"code": null,
"e": 30255,
"s": 30097,
"text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement."
},
{
"code": null,
"e": 30338,
"s": 30255,
"text": "You can use one if or else if statement inside another if or else if statement(s)."
},
{
"code": null,
"e": 30600,
"s": 30338,
"text": "Loops are used when a particular piece of code should be repeated with the desired number of iteration. Apex supports the standard traditional for loop as well as other advanced types of Loops. In this chapter, we will discuss in detail about the Loops in Apex."
},
{
"code": null,
"e": 30781,
"s": 30600,
"text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages β"
},
{
"code": null,
"e": 30945,
"s": 30781,
"text": "The following tables lists down the different Loops that handle looping requirements in Apex Programming language. Click the following links to check their detail."
},
{
"code": null,
"e": 31019,
"s": 30945,
"text": "This loop performs a set of statements for each item in a set of records."
},
{
"code": null,
"e": 31097,
"s": 31019,
"text": "Execute a sequence of statements directly over the returned set o SOQL query."
},
{
"code": null,
"e": 31163,
"s": 31097,
"text": "Execute a sequence of statements in traditional Java-like syntax."
},
{
"code": null,
"e": 31294,
"s": 31163,
"text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 31382,
"s": 31294,
"text": "Like a while statement, except that it tests the condition at the end of the loop body."
},
{
"code": null,
"e": 31593,
"s": 31382,
"text": "Collections is a type of variable that can store multiple number of records. For example, List can store multiple number of Account object's records. Let us now have a detailed overview of all collection types."
},
{
"code": null,
"e": 31977,
"s": 31593,
"text": "List can contain any number of records of primitive, collections, sObjects, user defined and built in Apex type. This is one of the most important type of collection and also, it has some system methods which have been tailored specifically to use with List. List index always starts with 0. This is synonymous to the array in Java. A list should be declared with the keyword 'List'."
},
{
"code": null,
"e": 31985,
"s": 31977,
"text": "Example"
},
{
"code": null,
"e": 32090,
"s": 31985,
"text": "Below is the list which contains the List of a primitive data type (string), that is the list of cities."
},
{
"code": null,
"e": 32190,
"s": 32090,
"text": "List<string> ListOfCities = new List<string>();\nSystem.debug('Value Of ListOfCities'+ListOfCities);"
},
{
"code": null,
"e": 32336,
"s": 32190,
"text": "Declaring the initial values of list is optional. However, we will declare the initial values here. Following is an example which shows the same."
},
{
"code": null,
"e": 32450,
"s": 32336,
"text": "List<string> ListOfStates = new List<string> {'NY', 'LA', 'LV'};\nSystem.debug('Value ListOfStates'+ListOfStates);"
},
{
"code": null,
"e": 32579,
"s": 32450,
"text": "List<account> AccountToDelete = new List<account> (); //This will be null\nSystem.debug('Value AccountToDelete'+AccountToDelete);"
},
{
"code": null,
"e": 32690,
"s": 32579,
"text": "We can declare the nested List as well. It can go up to five levels. This is called the\nMultidimensional list."
},
{
"code": null,
"e": 32727,
"s": 32690,
"text": "This is the list of set of integers."
},
{
"code": null,
"e": 32848,
"s": 32727,
"text": "List<List<Set<Integer>>> myNestedList = new List<List<Set<Integer>>>();\nSystem.debug('value myNestedList'+myNestedList);"
},
{
"code": null,
"e": 32992,
"s": 32848,
"text": "List can contain any number of records, but there is a limitation on heap size to prevent the performance issue and monopolizing the resources."
},
{
"code": null,
"e": 33164,
"s": 32992,
"text": "There are methods available for Lists which we can be utilized while programming to achieve some functionalities like calculating the size of List, adding an element, etc."
},
{
"code": null,
"e": 33214,
"s": 33164,
"text": "Following are some most frequently used methods β"
},
{
"code": null,
"e": 33221,
"s": 33214,
"text": "size()"
},
{
"code": null,
"e": 33227,
"s": 33221,
"text": "add()"
},
{
"code": null,
"e": 33233,
"s": 33227,
"text": "get()"
},
{
"code": null,
"e": 33241,
"s": 33233,
"text": "clear()"
},
{
"code": null,
"e": 33247,
"s": 33241,
"text": "set()"
},
{
"code": null,
"e": 33311,
"s": 33247,
"text": "The following example demonstrates the use of all these methods"
},
{
"code": null,
"e": 34347,
"s": 33311,
"text": "// Initialize the List\nList<string> ListOfStatesMethod = new List<string>();\n\n// This statement would give null as output in Debug logs\nSystem.debug('Value of List'+ ListOfStatesMethod);\n\n// Add element to the list using add method\nListOfStatesMethod.add('New York');\nListOfStatesMethod.add('Ohio');\n\n// This statement would give New York and Ohio as output in Debug logs\nSystem.debug('Value of List with new States'+ ListOfStatesMethod);\n\n// Get the element at the index 0\nString StateAtFirstPosition = ListOfStatesMethod.get(0);\n\n// This statement would give New York as output in Debug log\nSystem.debug('Value of List at First Position'+ StateAtFirstPosition);\n\n// set the element at 1 position\nListOfStatesMethod.set(0, 'LA');\n\n// This statement would give output in Debug log\nSystem.debug('Value of List with element set at First Position' + ListOfStatesMethod[0]);\n\n// Remove all the elements in List\nListOfStatesMethod.clear();\n\n// This statement would give output in Debug log\nSystem.debug('Value of List'+ ListOfStatesMethod);"
},
{
"code": null,
"e": 34478,
"s": 34347,
"text": "You can use the array notation as well to declare the List, as given below, but this is not general practice in Apex programming β"
},
{
"code": null,
"e": 34524,
"s": 34478,
"text": "String [] ListOfStates = new List<string>();\n"
},
{
"code": null,
"e": 34680,
"s": 34524,
"text": "A Set is a collection type which contains multiple number of unordered unique records. A Set cannot have duplicate records. Like Lists, Sets can be nested."
},
{
"code": null,
"e": 34688,
"s": 34680,
"text": "Example"
},
{
"code": null,
"e": 34754,
"s": 34688,
"text": "We will be defining the set of products which company is selling."
},
{
"code": null,
"e": 34875,
"s": 34754,
"text": "Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};\nSystem.debug('Value of ProductSet'+ProductSet);\n"
},
{
"code": null,
"e": 34993,
"s": 34875,
"text": "Set does support methods which we can utilize while programming as shown below (we are extending the above example) β"
},
{
"code": null,
"e": 35489,
"s": 34993,
"text": "// Adds an element to the set\n// Define set if not defined previously\nSet<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};\nProductSet.add('HCL');\nSystem.debug('Set with New Value '+ProductSet);\n\n// Removes an element from set\nProductSet.remove('HCL');\nSystem.debug('Set with removed value '+ProductSet);\n\n// Check whether set contains the particular element or not and returns true or false\nProductSet.contains('HCL');\nSystem.debug('Value of Set with all values '+ProductSet);"
},
{
"code": null,
"e": 35602,
"s": 35489,
"text": "It is a key value pair which contains the unique key for each value. Both key and value can be of any data type."
},
{
"code": null,
"e": 35610,
"s": 35602,
"text": "Example"
},
{
"code": null,
"e": 35694,
"s": 35610,
"text": "The following example represents the map of the Product Name with the Product code."
},
{
"code": null,
"e": 35968,
"s": 35694,
"text": "// Initialize the Map\nMap<string, string> ProductCodeToProductName = new Map<string, string>\n{'1000'=>'HCL', '1001'=>'H2SO4'};\n\n// This statement would give as output as key value pair in Debug log\nSystem.debug('value of ProductCodeToProductName'+ProductCodeToProductName);"
},
{
"code": null,
"e": 36055,
"s": 35968,
"text": "Following are a few examples which demonstrate the methods that can be used with Map β"
},
{
"code": null,
"e": 37004,
"s": 36055,
"text": "// Define a new map\nMap<string, string> ProductCodeToProductName = new Map<string, string>();\n\n// Insert a new key-value pair in the map where '1002' is key and 'Acetone' is value\nProductCodeToProductName.put('1002', 'Acetone');\n\n// Insert a new key-value pair in the map where '1003' is key and 'Ketone' is value\nProductCodeToProductName.put('1003', 'Ketone');\n\n// Assert that the map contains a specified key and respective value\nSystem.assert(ProductCodeToProductName.containsKey('1002'));\nSystem.debug('If output is true then Map contains the key and output is:'\n + ProductCodeToProductName.containsKey('1002'));\n\n// Retrieves a value, given a particular key\nString value = ProductCodeToProductName.get('1002');\nSystem.debug('Value at the Specified key using get function: '+value);\n\n// Return a set that contains all of the keys in the map\nSet SetOfKeys = ProductCodeToProductName.keySet();\nSystem.debug('Value of Set with Keys '+SetOfKeys);"
},
{
"code": null,
"e": 37308,
"s": 37004,
"text": "Map values may be unordered and hence we should not rely on the order in which the values are stored and try to access the map always using keys. Map value can be null. Map keys when declared String are case-sensitive; for example, ABC and abc will be considered as different keys and treated as unique."
},
{
"code": null,
"e": 37496,
"s": 37308,
"text": "A class is a template or blueprint from which objects are created. An object is an instance of a class. This is the standard definition of Class. Apex Classes are similar to Java Classes."
},
{
"code": null,
"e": 37742,
"s": 37496,
"text": "For example, InvoiceProcessor class describes the class which has all the methods and actions that can be performed on the Invoice. If you create an instance of this class, then it will represent the single invoice which is currently in context."
},
{
"code": null,
"e": 37862,
"s": 37742,
"text": "You can create class in Apex from the Developer Console, Force.com Eclipse IDE and from Apex Class detail page as well."
},
{
"code": null,
"e": 37934,
"s": 37862,
"text": "Follow these steps to create an Apex class from the Developer Console β"
},
{
"code": null,
"e": 37990,
"s": 37934,
"text": "Step 1 β Go to Name and click on the Developer Console."
},
{
"code": null,
"e": 38053,
"s": 37990,
"text": "Step 2 β Click on File β New and then click on the Apex class."
},
{
"code": null,
"e": 38111,
"s": 38053,
"text": "Follow these steps to create a class from Force.com IDE β"
},
{
"code": null,
"e": 38147,
"s": 38111,
"text": "Step 1 β Open Force.com Eclipse IDE"
},
{
"code": null,
"e": 38217,
"s": 38147,
"text": "Step 2 β Create a New Project by clicking on File β New β Apex Class."
},
{
"code": null,
"e": 38274,
"s": 38217,
"text": "Step 3 β Provide the Name for the Class and click on OK."
},
{
"code": null,
"e": 38324,
"s": 38274,
"text": "Once this is done, the new class will be created."
},
{
"code": null,
"e": 38391,
"s": 38324,
"text": "Follow these steps to create a class from Apex Class Detail Page β"
},
{
"code": null,
"e": 38423,
"s": 38391,
"text": "Step 1 β Click on Name β Setup."
},
{
"code": null,
"e": 38521,
"s": 38423,
"text": "Step 2 β Search for 'Apex Class' and click on the link. It will open the Apex Class details\npage."
},
{
"code": null,
"e": 38602,
"s": 38521,
"text": "Step 3 β Click on 'New' and then provide the Name for class and then click Save."
},
{
"code": null,
"e": 38659,
"s": 38602,
"text": "Below is the sample structure for Apex class definition."
},
{
"code": null,
"e": 38666,
"s": 38659,
"text": "Syntax"
},
{
"code": null,
"e": 38836,
"s": 38666,
"text": "private | public | global\n[virtual | abstract | with sharing | without sharing]\nclass ClassName [implements InterfaceNameList] [extends ClassName] {\n // Classs Body\n}\n"
},
{
"code": null,
"e": 38977,
"s": 38836,
"text": "This definition uses a combination of access modifiers, sharing modes, class name and class body. We will look at all these options further."
},
{
"code": null,
"e": 38985,
"s": 38977,
"text": "Example"
},
{
"code": null,
"e": 39045,
"s": 38985,
"text": "Following is a sample structure for Apex class definition β"
},
{
"code": null,
"e": 39407,
"s": 39045,
"text": "public class MySampleApexClass { //Class definition and body\n public static Integer myValue = 0; //Class Member variable\n public static String myString = ''; //Class Member variable\n \n public static Integer getCalculatedValue () {\n // Method definition and body\n // do some calculation\n myValue = myValue+10;\n return myValue;\n }\n}"
},
{
"code": null,
"e": 39606,
"s": 39407,
"text": "If you declare the access modifier as 'Private', then this class will be known only locally and you cannot access this class outside of that particular piece. By default, classes have this modifier."
},
{
"code": null,
"e": 39806,
"s": 39606,
"text": "If you declare the class as 'Public' then this implies that this class is accessible to your organization and your defined namespace. Normally, most of the Apex classes are defined with this keyword."
},
{
"code": null,
"e": 40042,
"s": 39806,
"text": "If you declare the class as 'global' then this will be accessible by all apex codes irrespective of your organization. If you have method defined with web service keyword, then you must declare the containing class with global keyword."
},
{
"code": null,
"e": 40093,
"s": 40042,
"text": "Let us now discuss the different modes of sharing."
},
{
"code": null,
"e": 40696,
"s": 40093,
"text": "This is a special feature of Apex Classes in Salesforce. When a class is specified with 'With Sharing' keyword then it has following implications: When the class will get executed, it will respect the User's access settings and profile permission. Suppose, User's action has triggered the record update for 30 records, but user has access to only 20 records and 10 records are not accessible. Then, if the class is performing the action to update the records, only 20 records will be updated to which the user has access and rest of 10 records will not be updated. This is also called as the User mode."
},
{
"code": null,
"e": 40926,
"s": 40696,
"text": "Even if the User does not have access to 10 records out of 30, all the 30 records will be updated as the Class is running in the System mode, i.e., it has been defined with Without Sharing keyword. This is called the System Mode."
},
{
"code": null,
"e": 41137,
"s": 40926,
"text": "If you use the 'virtual' keyword, then it indicates that this class can be extended and overrides are allowed. If the methods need to be overridden, then the classes should be declared with the virtual keyword."
},
{
"code": null,
"e": 41262,
"s": 41137,
"text": "If you declare the class as 'abstract', then it will only contain the signature of method and not the actual implementation."
},
{
"code": null,
"e": 41269,
"s": 41262,
"text": "Syntax"
},
{
"code": null,
"e": 41361,
"s": 41269,
"text": "[public | private | protected | global] [final] [static] data_type\nvariable_name [= value]\n"
},
{
"code": null,
"e": 41383,
"s": 41361,
"text": "In the above syntax β"
},
{
"code": null,
"e": 41434,
"s": 41383,
"text": "Variable data type and variable name are mandatory"
},
{
"code": null,
"e": 41475,
"s": 41434,
"text": "Access modifiers and value are optional."
},
{
"code": null,
"e": 41483,
"s": 41475,
"text": "Example"
},
{
"code": null,
"e": 41520,
"s": 41483,
"text": "public static final Integer myvalue;"
},
{
"code": null,
"e": 41764,
"s": 41520,
"text": "There are two modifiers for Class Methods in Apex β Public or Protected. Return type is mandatory for method and if method is not returning anything then you must mention void as the return type. Additionally, Body is also required for method."
},
{
"code": null,
"e": 41771,
"s": 41764,
"text": "Syntax"
},
{
"code": null,
"e": 41913,
"s": 41771,
"text": "[public | private | protected | global]\n[override]\n[static]\n\nreturn_data_type method_name (input parameters) {\n // Method body goes here\n}\n"
},
{
"code": null,
"e": 42027,
"s": 41913,
"text": "Those parameters mentioned in the square brackets are optional. However, the following components are essential β"
},
{
"code": null,
"e": 42044,
"s": 42027,
"text": "return_data_type"
},
{
"code": null,
"e": 42056,
"s": 42044,
"text": "method_name"
},
{
"code": null,
"e": 42413,
"s": 42056,
"text": "Using access modifiers, you can specify access level for the class methods. For Example, Public method will be accessible from anywhere in the class and outside of the Class. Private method will be accessible only within the class. Global will be accessible by all the Apex classes and can be exposed as web service method accessible by other apex classes."
},
{
"code": null,
"e": 42421,
"s": 42413,
"text": "Example"
},
{
"code": null,
"e": 42571,
"s": 42421,
"text": "//Method definition and body\npublic static Integer getCalculatedValue () {\n \n //do some calculation\n myValue = myValue+10;\n return myValue;\n}"
},
{
"code": null,
"e": 42634,
"s": 42571,
"text": "This method has return type as Integer and takes no parameter."
},
{
"code": null,
"e": 42699,
"s": 42634,
"text": "A Method can have parameters as shown in the following example β"
},
{
"code": null,
"e": 42946,
"s": 42699,
"text": "// Method definition and body, this method takes parameter price which will then be used \n// in method.\n\npublic static Integer getCalculatedValueViaPrice (Decimal price) {\n // do some calculation\n myValue = myValue+price;\n return myValue;\n}"
},
{
"code": null,
"e": 43078,
"s": 42946,
"text": "A constructor is a code that is invoked when an object is created from the class blueprint. It has the same name as the class name."
},
{
"code": null,
"e": 43420,
"s": 43078,
"text": "We do not need to define the constructor for every class, as by default a no-argument constructor gets called. Constructors are useful for initialization of variables or when a process is to be done at the time of class initialization. For example, you will like to assign values to certain Integer variables as 0 when the class gets called."
},
{
"code": null,
"e": 43428,
"s": 43420,
"text": "Example"
},
{
"code": null,
"e": 44113,
"s": 43428,
"text": "// Class definition and body\npublic class MySampleApexClass2 {\n public static Double myValue; // Class Member variable\n public static String myString; // Class Member variable\n\n public MySampleApexClass2 () {\n myValue = 100; //initialized variable when class is called\n }\n\n public static Double getCalculatedValue () { // Method definition and body\n // do some calculation\n myValue = myValue+10;\n return myValue;\n }\n\n public static Double getCalculatedValueViaPrice (Decimal price) {\n // Method definition and body\n // do some calculation\n myValue = myValue+price; // Final Price would be 100+100=200.00\n return myValue;\n }\n}"
},
{
"code": null,
"e": 44315,
"s": 44113,
"text": "You can call the method of class via constructor as well. This may be useful when programming Apex for visual force controller. When class object is created, then constructor is called as shown below β"
},
{
"code": null,
"e": 44531,
"s": 44315,
"text": "// Class and constructor has been instantiated\nMySampleApexClass2 objClass = new MySampleApexClass2();\nDouble FinalPrice = MySampleApexClass2.getCalculatedValueViaPrice(100);\nSystem.debug('FinalPrice: '+FinalPrice);"
},
{
"code": null,
"e": 44647,
"s": 44531,
"text": "Constructors can be overloaded, i.e., a class can have more than one constructor defined with different parameters."
},
{
"code": null,
"e": 44655,
"s": 44647,
"text": "Example"
},
{
"code": null,
"e": 45594,
"s": 44655,
"text": "public class MySampleApexClass3 { // Class definition and body\n public static Double myValue; // Class Member variable\n public static String myString; // Class Member variable\n\n public MySampleApexClass3 () {\n myValue = 100; // initialized variable when class is called\n System.debug('myValue variable with no Overaloading'+myValue);\n }\n\n public MySampleApexClass3 (Integer newPrice) { // Overloaded constructor\n myValue = newPrice; // initialized variable when class is called\n System.debug('myValue variable with Overaloading'+myValue);\n }\n\n public static Double getCalculatedValue () { // Method definition and body\n // do some calculation\n myValue = myValue+10;\n return myValue;\n }\n\n public static Double getCalculatedValueViaPrice (Decimal price) {\n // Method definition and body\n // do some calculation\n myValue = myValue+price;\n return myValue;\n }\n}"
},
{
"code": null,
"e": 45665,
"s": 45594,
"text": "You can execute this class as we have executed it in previous example."
},
{
"code": null,
"e": 45860,
"s": 45665,
"text": "// Developer Console Code\nMySampleApexClass3 objClass = new MySampleApexClass3();\nDouble FinalPrice = MySampleApexClass3.getCalculatedValueViaPrice(100);\nSystem.debug('FinalPrice: '+FinalPrice);"
},
{
"code": null,
"e": 45994,
"s": 45860,
"text": "An instance of class is called Object. In terms of Salesforce, object can be of class or you can create an object of sObject as well."
},
{
"code": null,
"e": 46106,
"s": 45994,
"text": "You can create an object of class as you might have done in Java or other object-oriented programming language."
},
{
"code": null,
"e": 46153,
"s": 46106,
"text": "Following is an example Class called MyClass β"
},
{
"code": null,
"e": 46435,
"s": 46153,
"text": "// Sample Class Example\npublic class MyClass {\n Integer myInteger = 10;\n \n public void myMethod (Integer multiplier) {\n Integer multiplicationResult;\n multiplicationResult = multiplier*myInteger;\n System.debug('Multiplication is '+multiplicationResult);\n }\n}"
},
{
"code": null,
"e": 46613,
"s": 46435,
"text": "This is an instance class, i.e., to call or access the variables or methods of this class, you must create an instance of this class and then you can perform all the operations."
},
{
"code": null,
"e": 46767,
"s": 46613,
"text": "// Object Creation\n// Creating an object of class\nMyClass objClass = new MyClass();\n\n// Calling Class method using Class instance\nobjClass.myMethod(100);"
},
{
"code": null,
"e": 46943,
"s": 46767,
"text": "sObjects are the objects of Salesforce in which you store the data. For example, Account, Contact, etc., are custom objects. You can create object instances of these sObjects."
},
{
"code": null,
"e": 47110,
"s": 46943,
"text": "Following is an example of sObject initialization and shows how you can access the field of that particular object using dot notation and assign the values to fields."
},
{
"code": null,
"e": 47814,
"s": 47110,
"text": "// Execute the below code in Developer console by simply pasting it\n// Standard Object Initialization for Account sObject\nAccount objAccount = new Account(); // Object initialization\nobjAccount.Name = 'Testr Account'; // Assigning the value to field Name of Account\nobjAccount.Description = 'Test Account';\ninsert objAccount; // Creating record using DML\nSystem.debug('Records Has been created '+objAccount);\n\n// Custom sObject initialization and assignment of values to field\nAPEX_Customer_c objCustomer = new APEX_Customer_c ();\nobjCustomer.Name = 'ABC Customer';\nobjCustomer.APEX_Customer_Decscription_c = 'Test Description';\ninsert objCustomer;\nSystem.debug('Records Has been created '+objCustomer);"
},
{
"code": null,
"e": 47980,
"s": 47814,
"text": "Static methods and variables are initialized only once when a class is loaded. Static variables are not transmitted as part of the view state for a Visualforce page."
},
{
"code": null,
"e": 48049,
"s": 47980,
"text": "Following is an example of Static method as well as Static variable."
},
{
"code": null,
"e": 48481,
"s": 48049,
"text": "// Sample Class Example with Static Method\npublic class MyStaticClass {\n Static Integer myInteger = 10;\n \n public static void myMethod (Integer multiplier) {\n Integer multiplicationResult;\n multiplicationResult = multiplier * myInteger;\n System.debug('Multiplication is '+multiplicationResult);\n }\n}\n\n// Calling the Class Method using Class Name and not using the instance object\nMyStaticClass.myMethod(100);"
},
{
"code": null,
"e": 48501,
"s": 48481,
"text": "Static Variable Use"
},
{
"code": null,
"e": 48796,
"s": 48501,
"text": "Static variables will be instantiated only once when class is loaded and this phenomenon can be used to avoid the trigger recursion. Static variable value will be same within the same execution context and any class, trigger or code which is executing can refer to it and prevent the recursion."
},
{
"code": null,
"e": 49085,
"s": 48796,
"text": "An interface is like an Apex class in which none of the methods have been implemented. It only contains the method signatures, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface."
},
{
"code": null,
"e": 49228,
"s": 49085,
"text": "Interfaces are used mainly for providing the abstraction layer for your code. They separate the implementation from declaration of the method."
},
{
"code": null,
"e": 49396,
"s": 49228,
"text": "Let's take an example of our Chemical Company. Suppose that we need to provide the discount to Premium and Ordinary customers and discounts for both will be different."
},
{
"code": null,
"e": 49454,
"s": 49396,
"text": "We will create an Interface called the DiscountProcessor."
},
{
"code": null,
"e": 50067,
"s": 49454,
"text": "// Interface\npublic interface DiscountProcessor {\n Double percentageDiscountTobeApplied(); // method signature only\n}\n\n// Premium Customer Class\npublic class PremiumCustomer implements DiscountProcessor {\n \n //Method Call\n public Double percentageDiscountTobeApplied () {\n \n // For Premium customer, discount should be 30%\n return 0.30;\n }\n}\n\n// Normal Customer Class\npublic class NormalCustomer implements DiscountProcessor {\n \n // Method Call\n public Double percentageDiscountTobeApplied () {\n \n // For Premium customer, discount should be 10%\n return 0.10;\n }\n}"
},
{
"code": null,
"e": 50338,
"s": 50067,
"text": "When you implement the Interface then it is mandatory to implement the method of that Interface. If you do not implement the Interface methods, it will throw an error. You should use Interfaces when you want to make the method implementation mandatory for the developer."
},
{
"code": null,
"e": 50574,
"s": 50338,
"text": "SFDC do have standard interfaces like Database.Batchable, Schedulable, etc. For example, if you implement the Database.Batchable Interface, then you must implement the three methods defined in the Interface β Start, Execute and Finish."
},
{
"code": null,
"e": 51000,
"s": 50574,
"text": "Below is an example for Standard Salesforce provided Database.Batchable Interface which sends out emails to users with the Batch Status. This interface has 3 methods, Start, Execute and Finish. Using this interface, we can implement the Batchable functionality and it also provides the BatchableContext variable which we can use to get more information about the Batch which is executing and to perform other functionalities."
},
{
"code": null,
"e": 53774,
"s": 51000,
"text": "global class CustomerProessingBatch implements Database.Batchable<sobject7>,\nSchedulable {\n // Add here your email address\n global String [] email = new String[] {'[email protected]'};\n\n // Start Method\n global Database.Querylocator start (Database.BatchableContext BC) {\n \n // This is the Query which will determine the scope of Records and fetching the same\n return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,\n APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today\n && APEX_Active__c = true');\n }\n\n // Execute method\n global void execute (Database.BatchableContext BC, List<sobject> scope) {\n List<apex_customer__c> customerList = new List<apex_customer__c>();\n List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>();\n \n for (sObject objScope: scope) {\n // type casting from generic sOject to APEX_Customer__c\n APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;\n newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';\n newObjScope.APEX_Customer_Status__c = 'Processed';\n \n // Add records to the List\n updtaedCustomerList.add(newObjScope);\n }\n\n // Check if List is empty or not\n if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {\n \n // Update the Records\n Database.update(updtaedCustomerList); System.debug('List Size\n '+updtaedCustomerList.size());\n }\n }\n\n // Finish Method\n global void finish(Database.BatchableContext BC) {\n Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();\n \n // get the job Id\n AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,\n a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,\n a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];\n System.debug('$$$ Jobid is'+BC.getJobId());\n \n // below code will send an email to User about the status\n mail.setToAddresses(email);\n \n // Add here your email address\n mail.setReplyTo('[email protected]');\n mail.setSenderDisplayName('Apex Batch Processing Module');\n mail.setSubject('Batch Processing '+a.Status);\n mail.setPlainTextBody('The Batch Apex job processed\n '+a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item\n processed are'+a.JobItemsProcessed);\n Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});\n }\n\n // Scheduler Method to scedule the class\n global void execute(SchedulableContext sc) {\n CustomerProessingBatch conInstance = new CustomerProessingBatch();\n database.executebatch(conInstance,100);\n }\n}"
},
{
"code": null,
"e": 53854,
"s": 53774,
"text": "To execute this class, you have to run the below code in the Developer Console."
},
{
"code": null,
"e": 53952,
"s": 53854,
"text": "CustomerProessingBatch objBatch = new CustomerProessingBatch ();\nDatabase.executeBatch(objBatch);"
},
{
"code": null,
"e": 54133,
"s": 53952,
"text": "In this chapter, we will discuss how to perform the different Database Modification Functionalities in Salesforce. There are two says with which we can perform the functionalities."
},
{
"code": null,
"e": 54292,
"s": 54133,
"text": "DML are the actions which are performed in order to perform insert, update, delete, upsert, restoring records, merging records, or converting leads operation."
},
{
"code": null,
"e": 54420,
"s": 54292,
"text": "DML is one of the most important part in Apex as almost every business case involves the changes and modifications to database."
},
{
"code": null,
"e": 54685,
"s": 54420,
"text": "All operations which you can perform using DML statements can be performed using Database methods as well. Database methods are the system methods which you can use to perform DML operations. Database methods provide more flexibility as compared to DML Statements."
},
{
"code": null,
"e": 54827,
"s": 54685,
"text": "In this chapter, we will be looking at the first approach using DML Statements. We will look at the Database Methods in a subsequent chapter."
},
{
"code": null,
"e": 55112,
"s": 54827,
"text": "Let us now consider the instance of the Chemical supplier company again. Our Invoice records have fields as Status, Amount Paid, Amount Remaining, Next Pay Date and Invoice Number. Invoices which have been created today and have their status as 'Pending', should be updated to 'Paid'."
},
{
"code": null,
"e": 55260,
"s": 55112,
"text": "Insert operation is used to create new records in Database. You can create records of any Standard or Custom object using the Insert DML statement."
},
{
"code": null,
"e": 55268,
"s": 55260,
"text": "Example"
},
{
"code": null,
"e": 55501,
"s": 55268,
"text": "We can create new records in APEX_Invoice__c object as new invoices are being generated for new customer orders every day. We will create a Customer record first and then we can create an Invoice record for that new Customer record."
},
{
"code": null,
"e": 56859,
"s": 55501,
"text": "// fetch the invoices created today, Note, you must have at least one invoice \n// created today\n\nList<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,\n createdDate FROM APEX_Invoice__c WHERE createdDate = today];\n\n// create List to hold the updated invoice records\nList<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();\nAPEX_Customer__c objCust = new APEX_Customer__C();\nobjCust.Name = 'Test ABC';\n\n//DML for Inserting the new Customer Records\ninsert objCust;\nfor (APEX_Invoice__c objInvoice: invoiceList) {\n if (objInvoice.APEX_Status__c == 'Pending') {\n objInvoice.APEX_Status__c = 'Paid';\n updatedInvoiceList.add(objInvoice);\n }\n}\n\n// DML Statement to update the invoice status\nupdate updatedInvoiceList;\n\n// Prints the value of updated invoices\nSystem.debug('List has been updated and updated values are' + updatedInvoiceList);\n\n// Inserting the New Records using insert DML statement\nAPEX_Invoice__c objNewInvoice = new APEX_Invoice__c();\nobjNewInvoice.APEX_Status__c = 'Pending';\nobjNewInvoice.APEX_Amount_Paid__c = 1000;\nobjNewInvoice.APEX_Customer__c = objCust.id;\n\n// DML which is creating the new Invoice record which will be linked with newly\n// created Customer record\ninsert objNewInvoice;\nSystem.debug('New Invoice Id is '+objNewInvoice.id+' and the Invoice Number is'\n + objNewInvoice.Name);"
},
{
"code": null,
"e": 57014,
"s": 56859,
"text": "Update operation is to perform updates on existing records. In this example, we will be updating the Status field of an existing Invoice record to 'Paid'."
},
{
"code": null,
"e": 57022,
"s": 57014,
"text": "Example"
},
{
"code": null,
"e": 57789,
"s": 57022,
"text": "// Update Statement Example for updating the invoice status. You have to create\nand Invoice records before executing this code. This program is updating the\nrecord which is at index 0th position of the List.\n\n// First, fetch the invoice created today\nList<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,\ncreatedDate FROM APEX_Invoice__c];\nList<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();\n\n// Update the first record in the List\ninvoiceList[0].APEX_Status__c = 'Pending';\nupdatedInvoiceList.add(invoiceList[0]);\n\n// DML Statement to update the invoice status\nupdate updatedInvoiceList;\n\n// Prints the value of updated invoices\nSystem.debug('List has been updated and updated values of records are' \n + updatedInvoiceList[0]);"
},
{
"code": null,
"e": 57940,
"s": 57789,
"text": "Upsert Operation is used to perform an update operation and if the records to be updated are not present in database, then create new records as well."
},
{
"code": null,
"e": 57948,
"s": 57940,
"text": "Example"
},
{
"code": null,
"e": 58256,
"s": 57948,
"text": "Suppose, the customer records in Customer object need to be updated. We will update the existing Customer record if it is already present, else create a new one. This will be based on the value of field APEX_External_Id__c. This field will be our field to identify if the records are already present or not."
},
{
"code": null,
"e": 58417,
"s": 58256,
"text": "Note β Before executing this code, please create a record in Customer object with the external Id field value as '12341' and then execute the code given below β"
},
{
"code": null,
"e": 59067,
"s": 58417,
"text": "// Example for upserting the Customer records\nList<apex_customer__c> CustomerList = new List<apex_customer__c>();\nfor (Integer i = 0; i < 10; i++) {\n apex_customer__c objcust=new apex_customer__c(name = 'Test' +i,\n apex_external_id__c='1234' +i);\n customerlist.add(objcust);\n} //Upserting the Customer Records\n\nupsert CustomerList;\n\nSystem.debug('Code iterated for 10 times and created 9 records as one record with \n External Id 12341 is already present');\n\nfor (APEX_Customer_c objCustomer: CustomerList) {\n if (objCustomer.APEX_External_Id_c == '12341') {\n system.debug('The Record which is already present is '+objCustomer);\n }\n}"
},
{
"code": null,
"e": 59126,
"s": 59067,
"text": "You can perform the delete operation using the Delete DML."
},
{
"code": null,
"e": 59134,
"s": 59126,
"text": "Example"
},
{
"code": null,
"e": 59276,
"s": 59134,
"text": "In this case, we will delete the invoices which have been created for the testing purpose, that is the ones which contain the name as 'Test'."
},
{
"code": null,
"e": 59368,
"s": 59276,
"text": "You can execute this snippet from the Developer console as well without creating the class."
},
{
"code": null,
"e": 60886,
"s": 59368,
"text": "// fetch the invoice created today\nList<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,\ncreatedDate FROM APEX_Invoice__c WHERE createdDate = today];\nList<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();\nAPEX_Customer__c objCust = new APEX_Customer__C();\nobjCust.Name = 'Test';\n\n// Inserting the Customer Records\ninsert objCust;\nfor (APEX_Invoice__c objInvoice: invoiceList) {\n if (objInvoice.APEX_Status__c == 'Pending') {\n objInvoice.APEX_Status__c = 'Paid';\n updatedInvoiceList.add(objInvoice);\n }\n}\n\n// DML Statement to update the invoice status\nupdate updatedInvoiceList;\n\n// Prints the value of updated invoices\nSystem.debug('List has been updated and updated values are' + updatedInvoiceList);\n\n// Inserting the New Records using insert DML statement\nAPEX_Invoice__c objNewInvoice = new APEX_Invoice__c();\nobjNewInvoice.APEX_Status__c = 'Pending';\nobjNewInvoice.APEX_Amount_Paid__c = 1000;\nobjNewInvoice.APEX_Customer__c = objCust.id;\n\n// DML which is creating the new record\ninsert objNewInvoice;\nSystem.debug('New Invoice Id is' + objNewInvoice.id);\n\n// Deleting the Test invoices from Database\n// fetch the invoices which are created for Testing, Select name which Customer Name\n// is Test.\nList<apex_invoice__c> invoiceListToDelete = [SELECT id FROM APEX_Invoice__c\n WHERE APEX_Customer__r.Name = 'Test'];\n\n// DML Statement to delete the Invoices\ndelete invoiceListToDelete;\nSystem.debug('Success, '+invoiceListToDelete.size()+' Records has been deleted');"
},
{
"code": null,
"e": 61043,
"s": 60886,
"text": "You can undelete the record which has been deleted and is present in Recycle bin. All the relationships which the deleted record has, will also be restored."
},
{
"code": null,
"e": 61051,
"s": 61043,
"text": "Example"
},
{
"code": null,
"e": 61244,
"s": 61051,
"text": "Suppose, the Records deleted in the previous example need to be restored. This can be achieved using the following example. The code in the previous example has been modified for this example."
},
{
"code": null,
"e": 63043,
"s": 61244,
"text": "// fetch the invoice created today\nList<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,\ncreatedDate FROM APEX_Invoice__c WHERE createdDate = today];\nList<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();\nAPEX_Customer__c objCust = new APEX_Customer__C();\nobjCust.Name = 'Test';\n\n// Inserting the Customer Records\ninsert objCust;\nfor (APEX_Invoice__c objInvoice: invoiceList) {\n if (objInvoice.APEX_Status__c == 'Pending') {\n objInvoice.APEX_Status__c = 'Paid';\n updatedInvoiceList.add(objInvoice);\n }\n}\n\n// DML Statement to update the invoice status\nupdate updatedInvoiceList;\n\n// Prints the value of updated invoices\nSystem.debug('List has been updated and updated values are' + updatedInvoiceList);\n\n// Inserting the New Records using insert DML statement\nAPEX_Invoice__c objNewInvoice = new APEX_Invoice__c();\nobjNewInvoice.APEX_Status__c = 'Pending';\nobjNewInvoice.APEX_Amount_Paid__c = 1000;\nobjNewInvoice.APEX_Customer__c = objCust.id;\n\n// DML which is creating the new record\ninsert objNewInvoice;\nSystem.debug('New Invoice Id is '+objNewInvoice.id);\n\n// Deleting the Test invoices from Database\n// fetch the invoices which are created for Testing, Select name which Customer Name\n// is Test.\nList<apex_invoice__c> invoiceListToDelete = [SELECT id FROM APEX_Invoice__c\n WHERE APEX_Customer__r.Name = 'Test'];\n\n// DML Statement to delete the Invoices\ndelete invoiceListToDelete;\nsystem.debug('Deleted Record Count is ' + invoiceListToDelete.size());\nSystem.debug('Success, '+invoiceListToDelete.size() + 'Records has been deleted');\n\n// Restore the deleted records using undelete statement\nundelete invoiceListToDelete;\nSystem.debug('Undeleted Record count is '+invoiceListToDelete.size()+'. This should \n be same as Deleted Record count');"
},
{
"code": null,
"e": 63182,
"s": 63043,
"text": "Database class methods is another way of working with DML statements which are more flexible than DML Statements like insert, update, etc."
},
{
"code": null,
"e": 63416,
"s": 63182,
"text": "Inserting new records via database methods is also quite simple and flexible. Let us consider the previous scenario wherein, we have inserted new records using the DML statements. We will be inserting the same using Database methods."
},
{
"code": null,
"e": 64997,
"s": 63416,
"text": "// Insert Operation Using Database methods\n// Insert Customer Records First using simple DML Statement. This Customer Record will be\n// used when we will create Invoice Records\nAPEX_Customer__c objCust = new APEX_Customer__C();\nobjCust.Name = 'Test';\ninsert objCust; // Inserting the Customer Records\n\n// Insert Operation Using Database methods\nAPEX_Invoice__c objNewInvoice = new APEX_Invoice__c();\nList<apex_invoice__c> InvoiceListToInsert = new List<apex_invoice__c>();\nobjNewInvoice.APEX_Status__c = 'Pending';\nobjNewInvoice.APEX_Customer__c = objCust.id;\nobjNewInvoice.APEX_Amount_Paid__c = 1000;\nInvoiceListToInsert.add(objNewInvoice);\nDatabase.SaveResult[] srList = Database.insert(InvoiceListToInsert, false);\n\n// Database method to insert the records in List\n// Iterate through each returned result by the method\n\nfor (Database.SaveResult sr : srList) {\n if (sr.isSuccess()) {\n // This condition will be executed for successful records and will fetch the ids \n // of successful records\n System.debug('Successfully inserted Invoice. Invoice ID: ' + sr.getId());\n // Get the invoice id of inserted Account\n } else {\n // This condition will be executed for failed records\n for(Database.Error objErr : sr.getErrors()) {\n System.debug('The following error has occurred.');\n \n // Printing error message in Debug log\n System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());\n System.debug('Invoice oject field which are affected by the error:' \n + objErr.getFields());\n }\n }\n}"
},
{
"code": null,
"e": 65362,
"s": 64997,
"text": "Let us now consider our business case example using the database methods. Suppose we need to update the status field of Invoice object but at the same time, we also require information like status of records, failed record ids, success count, etc. This is not possible by using DML Statements, hence we must use Database methods to get the status of our operation."
},
{
"code": null,
"e": 65471,
"s": 65362,
"text": "We will be updating the Invoice's 'Status' field if it is in status 'Pending' and date of creation is today."
},
{
"code": null,
"e": 65627,
"s": 65471,
"text": "The code given below will help in updating the Invoice records using the Database.update method. Also, create an Invoice record before executing this code."
},
{
"code": null,
"e": 67038,
"s": 65627,
"text": "// Code to update the records using the Database methods\nList<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,\n createdDate FROM APEX_Invoice__c WHERE createdDate = today];\n\n// fetch the invoice created today\nList<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();\nfor (APEX_Invoice__c objInvoice: invoiceList) {\n if (objInvoice.APEX_Status__c == 'Pending') {\n objInvoice.APEX_Status__c = 'Paid';\n updatedInvoiceList.add(objInvoice); //Adding records to the list\n }\n}\n\nDatabase.SaveResult[] srList = Database.update(updatedInvoiceList, false);\n// Database method to update the records in List\n\n// Iterate through each returned result by the method\nfor (Database.SaveResult sr : srList) {\n if (sr.isSuccess()) {\n // This condition will be executed for successful records and will fetch\n // the ids of successful records\n System.debug('Successfully updated Invoice. Invoice ID is : ' + sr.getId());\n } else {\n // This condition will be executed for failed records\n for(Database.Error objErr : sr.getErrors()) {\n System.debug('The following error has occurred.');\n \n // Printing error message in Debug log\n System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());\n System.debug('Invoice oject field which are affected by the error:' \n + objErr.getFields());\n }\n }\n}"
},
{
"code": null,
"e": 67212,
"s": 67038,
"text": "We will be looking at only the Insert and Update operations in this tutorial. The other operations are quite similar to these operations and what we did in the last chapter."
},
{
"code": null,
"e": 67437,
"s": 67212,
"text": "Every business or application has search functionality as one of the basic requirements. For this, Salesforce.com provides two major approaches using SOSL and SOQL. Let us discuss the SOSL approach in detail in this chapter."
},
{
"code": null,
"e": 67653,
"s": 67437,
"text": "Searching the text string across the object and across the field will be done by using SOSL. This is Salesforce Object Search Language. It has the capability of searching a particular string across multiple objects."
},
{
"code": null,
"e": 67876,
"s": 67653,
"text": "SOSL statements evaluate to a list of sObjects, wherein, each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query."
},
{
"code": null,
"e": 68093,
"s": 67876,
"text": "Consider a business case wherein, we need to develop a program which can search a specified string. Suppose, we need to search for string 'ABC' in the Customer Name field of Invoice object. The code goes as follows β"
},
{
"code": null,
"e": 68228,
"s": 68093,
"text": "First, you have to create a single record in Invoice object with Customer name as 'ABC' so that we can get valid result when searched."
},
{
"code": null,
"e": 69801,
"s": 68228,
"text": "// Program To Search the given string in all Object\n// List to hold the returned results of sObject generic type\nList<list<SObject>> invoiceSearchList = new List<List<SObject>>();\n\n// SOSL query which will search for 'ABC' string in Customer Name field of Invoice Object\ninvoiceSearchList = [FIND 'ABC*' IN ALL FIELDS RETURNING APEX_Invoice_c\n (Id,APEX_Customer_r.Name)];\n\n// Returned result will be printed\nSystem.debug('Search Result '+invoiceSearchList);\n\n// Now suppose, you would like to search string 'ABC' in two objects,\n// that is Invoice and Account. Then for this query goes like this:\n\n// Program To Search the given string in Invoice and Account object,\n// you could specify more objects if you want, create an Account with Name as ABC.\n\n// List to hold the returned results of sObject generic type\nList<List<SObject>> invoiceAndSearchList = new List<List<SObject>>();\n\n// SOSL query which will search for 'ABC' string in Invoice and in Account object's fields\ninvoiceAndSearchList = [FIND 'ABC*' IN ALL FIELDS RETURNING APEX_Invoice__c\n (Id,APEX_Customer__r.Name), Account];\n\n// Returned result will be printed\nSystem.debug('Search Result '+invoiceAndSearchList);\n\n// This list will hold the returned results for Invoice Object\nAPEX_Invoice__c [] searchedInvoice = ((List<APEX_Invoice_c>)invoiceAndSearchList[0]);\n\n// This list will hold the returned results for Account Object\nAccount [] searchedAccount = ((List<Account>)invoiceAndSearchList[1]);\nSystem.debug('Value of searchedInvoice'+searchedInvoice+'Value of searchedAccount'\n + searchedAccount);"
},
{
"code": null,
"e": 70026,
"s": 69801,
"text": "This is almost the same as SOQL. You can use this to fetch the object records from one object only at a time. You can write nested queries and also fetch the records from parent or child object on which you are querying now."
},
{
"code": null,
"e": 70068,
"s": 70026,
"text": "We will explore SOQL in the next chapter."
},
{
"code": null,
"e": 70214,
"s": 70068,
"text": "This is Salesforce Object Query Language designed to work with SFDC Database. It can search a record on a given criterion only in single sObject."
},
{
"code": null,
"e": 70302,
"s": 70214,
"text": "Like SOSL, it cannot search across multiple objects but it does support nested queries."
},
{
"code": null,
"e": 70516,
"s": 70302,
"text": "Consider our ongoing example of Chemical Company. Suppose, we need a list of records which are created today and whose customer name is not 'test'. In this case, we will have to use the SOQL query as given below β"
},
{
"code": null,
"e": 71042,
"s": 70516,
"text": "// fetching the Records via SOQL\nList<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\nInvoiceList = [SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM\n APEX_Invoice__c WHERE createdDate = today AND APEX_Customer__r.Name != 'Test'];\n// SOQL query for given criteria\n\n// Printing the fetched records\nSystem.debug('We have total '+InvoiceList.size()+' Records in List');\n\nfor (APEX_Invoice__c objInvoice: InvoiceList) {\n System.debug('Record Value is '+objInvoice); \n // Printing the Record fetched\n}"
},
{
"code": null,
"e": 71131,
"s": 71042,
"text": "You can run the SOQL query via the Query Editor in the Developer console as shown below."
},
{
"code": null,
"e": 71229,
"s": 71131,
"text": "Run the query given below in the Developer Console. Search for the Invoice records created today."
},
{
"code": null,
"e": 71334,
"s": 71229,
"text": "SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM APEX_Invoice__c\n WHERE createdDate = today"
},
{
"code": null,
"e": 71433,
"s": 71334,
"text": "You must select the fields for which you need the values, otherwise, it can throw run time errors."
},
{
"code": null,
"e": 71560,
"s": 71433,
"text": "This is one of the most important parts in SFDC as many times we need to traverse through the parent child object relationship"
},
{
"code": null,
"e": 71770,
"s": 71560,
"text": "Also, there may be cases when you need to insert two associated objects records in Database. For example, Invoice object has relationship with the Customer object and hence one Customer can have many invoices."
},
{
"code": null,
"e": 71918,
"s": 71770,
"text": "Suppose, you are creating the invoice and then you need to relate this invoice to Customer. You can use the following code for this functionality β"
},
{
"code": null,
"e": 72474,
"s": 71918,
"text": "// Now create the invoice record and relate it with the Customer object\n// Before executing this, please create a Customer Records with Name 'Customer\n// Creation Test'\nAPEX_Invoice__c objInvoice = new APEX_Invoice__c();\n\n// Relating Invoice to customer via id field of Customer object\nobjInvoice.APEX_Customer__c = [SELECT id FROM APEX_Customer__c WHERE Name =\n 'Customer Creation Test' LIMIT 1].id;\nobjInvoice.APEX_Status__c = 'Pending';\ninsert objInvoice; //Creating Invoice\nSystem.debug('Newly Created Invoice'+objInvoice); //Newly created invoice"
},
{
"code": null,
"e": 72733,
"s": 72474,
"text": "Execute this code snippet in the Developer Console. Once executed, copy the Id of invoice from the Developer console and then open the same in SFDC as shown below. You can see that the Parent record has already been assigned to Invoice record as shown below."
},
{
"code": null,
"e": 73091,
"s": 72733,
"text": "Let us now consider an example wherein, all the invoices related to particular customer record need to be in one place. For this, you must know the child relationship name. To see the child relationship name, go to the field detail page on the child object and check the \"Child Relationship\" value. In our example, it is invoices appended by __r at the end."
},
{
"code": null,
"e": 73232,
"s": 73091,
"text": "In this example, we will need to set up data, create a customer with name as 'ABC Customer' record and then add 3 invoices to that customer."
},
{
"code": null,
"e": 73335,
"s": 73232,
"text": "Now, we will fetch the invoices the Customer 'ABC Customer' has. Following is the query for the same β"
},
{
"code": null,
"e": 73868,
"s": 73335,
"text": "// Fetching Child Records using SOQL\nList<apex_customer__c> ListCustomers = [SELECT Name, Id, \n (SELECT id, Name FROM Invoices__r) FROM APEX_Customer__c WHERE Name = 'ABC Customer'];\n\n// Query for fetching the Child records along with Parent\nSystem.debug('ListCustomers '+ListCustomers); // Parent Record\n\nList<apex_invoice__c> ListOfInvoices = ListCustomers[0].Invoices__r;\n// By this notation, you could fetch the child records and save it in List\nSystem.debug('ListOfInvoices values of Child '+ListOfInvoices);\n// Child records"
},
{
"code": null,
"e": 73917,
"s": 73868,
"text": "You can see the Record values in the Debug logs."
},
{
"code": null,
"e": 74064,
"s": 73917,
"text": "Suppose, you need to fetch the Customer Name of Invoice the creation date of which is today, then you can use the query given below for the same β"
},
{
"code": null,
"e": 74125,
"s": 74064,
"text": "Fetch the Parent record's value along with the child object."
},
{
"code": null,
"e": 74617,
"s": 74125,
"text": "// Fetching Parent Record Field value using SOQL\nList<apex_invoice__c> ListOfInvoicesWithCustomerName = new List<apex_invoice__c>();\nListOfInvoicesWithCustomerName = [SELECT Name, id, APEX_Customer__r.Name \n FROM APEX_Invoice__c LIMIT 10];\n\n// Fetching the Parent record's values\nfor (APEX_Invoice__c objInv: ListOfInvoicesWithCustomerName) {\n System.debug('Invoice Customer Name is '+objInv.APEX_Customer__r.Name);\n // Will print the values, all the Customer Records will be printed\n}"
},
{
"code": null,
"e": 74833,
"s": 74617,
"text": "Here we have used the notation APEX_Customer__r.Name, where APEX_Customer__r is parent relationship name, here you have to append the __r at the end of the Parent field and then you can fetch the parent field value."
},
{
"code": null,
"e": 74996,
"s": 74833,
"text": "SOQL does have aggregate function as we have in SQL. Aggregate functions allow us to roll up and summarize the data. Let us now understand the function in detail."
},
{
"code": null,
"e": 75157,
"s": 74996,
"text": "Suppose, you wanted to know that what is the average revenue we are getting from Customer 'ABC Customer', then you can use this function to take up the average."
},
{
"code": null,
"e": 75523,
"s": 75157,
"text": "// Getting Average of all the invoices for a Perticular Customer\nAggregateResult[] groupedResults = [SELECT\n AVG(APEX_Amount_Paid__c)averageAmount FROM APEX_Invoice__c WHERE\n APEX_Customer__r.Name = 'ABC Customer'];\nObject avgPaidAmount = groupedResults[0].get('averageAmount');\nSystem.debug('Total Average Amount Received From Customer ABC is '+avgPaidAmount);"
},
{
"code": null,
"e": 75809,
"s": 75523,
"text": "Check the output in Debug logs. Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a readonly sObject and is only used for query results. It is useful when we need to generate the Report on Large data."
},
{
"code": null,
"e": 75900,
"s": 75809,
"text": "There are other aggregate functions as well which you can be used to perform data\nsummary."
},
{
"code": null,
"e": 75951,
"s": 75900,
"text": "MIN() β This can be used to find the minimum value"
},
{
"code": null,
"e": 76003,
"s": 75951,
"text": "MAX() β This can be used to find the maximum value."
},
{
"code": null,
"e": 76137,
"s": 76003,
"text": "You can use the Apex variable in SOQL query to fetch the desired results. Apex variables\ncan be referenced by the Colon (:) notation."
},
{
"code": null,
"e": 76406,
"s": 76137,
"text": "// Apex Variable Reference\nString CustomerName = 'ABC Customer';\nList<apex_customer__c> ListCustomer = [SELECT Id, Name FROM APEX_Customer__c\n WHERE Name = :CustomerName];\n\n// Query Using Apex variable\nSystem.debug('ListCustomer Name'+ListCustomer); // Customer Name"
},
{
"code": null,
"e": 76597,
"s": 76406,
"text": "Apex security refers to the process of applying security settings and enforcing the sharing rules on running code. Apex classes have security setting that can be controlled via two keywords."
},
{
"code": null,
"e": 76865,
"s": 76597,
"text": "Apex generally runs in system context, that is, the current user's permissions. Field-level security, and sharing rules are not taken into account during code execution. Only the anonymous block code executes with the permission of the user who is executing the code."
},
{
"code": null,
"e": 77046,
"s": 76865,
"text": "Our Apex code should not expose the sensitive data to User which is hidden via security and sharing settings. Hence, Apex security and enforcing the sharing rule is most important."
},
{
"code": null,
"e": 77238,
"s": 77046,
"text": "If you use this keyword, then the Apex code will enforce the Sharing settings of current user to Apex code. This does not enforce the Profile permission, only the data level sharing settings."
},
{
"code": null,
"e": 77483,
"s": 77238,
"text": "Let us consider an example wherein, our User has access to 5 records, but the total number of records is 10. So when the Apex class will be declared with the \"With Sharing\" Keyword, it will return only 5 records on which the user has access to."
},
{
"code": null,
"e": 77491,
"s": 77483,
"text": "Example"
},
{
"code": null,
"e": 77816,
"s": 77491,
"text": "First, make sure that you have created at least 10 records in the Customer object with 'Name' of 5 records as 'ABC Customer' and rest 5 records as 'XYZ Customer'. Then, create a sharing rule which will share the 'ABC Customer' with all Users. We also need to make sure that we have set the OWD of Customer object as Private."
},
{
"code": null,
"e": 77888,
"s": 77816,
"text": "Paste the code given below to Anonymous block in the Developer Console."
},
{
"code": null,
"e": 78530,
"s": 77888,
"text": "// Class With Sharing\npublic with sharing class MyClassWithSharing {\n // Query To fetch 10 records\n List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10];\n \n public Integer executeQuery () {\n System.debug('List will have only 5 records and the actual records are' \n + CustomerList.size()+' as user has access to'+CustomerList);\n Integer ListSize = CustomerList.size();\n return ListSize;\n }\n}\n\n// Save the above class and then execute as below\n// Execute class using the object of class\nMyClassWithSharing obj = new MyClassWithSharing();\nInteger ListSize = obj.executeQuery();"
},
{
"code": null,
"e": 78699,
"s": 78530,
"text": "As the name suggests, class declared with this keyword executes in System mode, i.e., irrespective of the User's access to the record, query will fetch all the records."
},
{
"code": null,
"e": 79229,
"s": 78699,
"text": "// Class Without Sharing\npublic without sharing class MyClassWithoutSharing {\n List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10];\n \n // Query To fetch 10 records, this will return all the records\n public Integer executeQuery () {\n System.debug('List will have only 5 records and the actula records are'\n + CustomerList.size()+' as user has access to'+CustomerList);\n Integer ListSize = CustomerList.size();\n return ListSize;\n }\n}\n// Output will be 10 records."
},
{
"code": null,
"e": 79400,
"s": 79229,
"text": "You can enable or disable an Apex class for particular profile. The steps for the same are given below. You can determine which profile should have access to which class."
},
{
"code": null,
"e": 79451,
"s": 79400,
"text": "Step 1 β From Setup, click Develop β Apex Classes."
},
{
"code": null,
"e": 79558,
"s": 79451,
"text": "Step 2 β Click the name of the class that you want to restrict. We have clicked on CustomerOperationClass."
},
{
"code": null,
"e": 79586,
"s": 79558,
"text": "Step 3 β Click on Security."
},
{
"code": null,
"e": 79787,
"s": 79586,
"text": "Step 4 β Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click on Remove."
},
{
"code": null,
"e": 79811,
"s": 79787,
"text": "Step 5 β Click on Save."
},
{
"code": null,
"e": 79870,
"s": 79811,
"text": "Step 1 β From Setup, click Manage Users β Permission Sets."
},
{
"code": null,
"e": 79904,
"s": 79870,
"text": "Step 2 β Select a permission set."
},
{
"code": null,
"e": 79941,
"s": 79904,
"text": "Step 3 β Click on Apex Class Access."
},
{
"code": null,
"e": 79965,
"s": 79941,
"text": "Step 4 β Click on Edit."
},
{
"code": null,
"e": 80179,
"s": 79965,
"text": "Step 5 β Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex classes that you want to disable from the Enabled Apex Classes list and click remove."
},
{
"code": null,
"e": 80211,
"s": 80179,
"text": "Step 6 β Click the Save button."
},
{
"code": null,
"e": 80362,
"s": 80211,
"text": "Apex invoking refers to the process of executing the Apex class. Apex class can only be executed when it is invoked via one of the ways listed below β"
},
{
"code": null,
"e": 80391,
"s": 80362,
"text": "Triggers and Anonymous block"
},
{
"code": null,
"e": 80420,
"s": 80391,
"text": "Triggers and Anonymous block"
},
{
"code": null,
"e": 80459,
"s": 80420,
"text": "A trigger invoked for specified events"
},
{
"code": null,
"e": 80498,
"s": 80459,
"text": "A trigger invoked for specified events"
},
{
"code": null,
"e": 80516,
"s": 80498,
"text": "Asynchronous Apex"
},
{
"code": null,
"e": 80534,
"s": 80516,
"text": "Asynchronous Apex"
},
{
"code": null,
"e": 80613,
"s": 80534,
"text": "Scheduling an Apex class to run at specified intervals, or running a batch job"
},
{
"code": null,
"e": 80692,
"s": 80613,
"text": "Scheduling an Apex class to run at specified intervals, or running a batch job"
},
{
"code": null,
"e": 80711,
"s": 80692,
"text": "Web Services class"
},
{
"code": null,
"e": 80730,
"s": 80711,
"text": "Web Services class"
},
{
"code": null,
"e": 80755,
"s": 80730,
"text": "Apex Email Service class"
},
{
"code": null,
"e": 80780,
"s": 80755,
"text": "Apex Email Service class"
},
{
"code": null,
"e": 80864,
"s": 80780,
"text": "Apex Web Services, which allow exposing your methods via SOAP and REST Web services"
},
{
"code": null,
"e": 80948,
"s": 80864,
"text": "Apex Web Services, which allow exposing your methods via SOAP and REST Web services"
},
{
"code": null,
"e": 80972,
"s": 80948,
"text": "Visualforce Controllers"
},
{
"code": null,
"e": 80996,
"s": 80972,
"text": "Visualforce Controllers"
},
{
"code": null,
"e": 81040,
"s": 80996,
"text": "Apex Email Service to process inbound email"
},
{
"code": null,
"e": 81084,
"s": 81040,
"text": "Apex Email Service to process inbound email"
},
{
"code": null,
"e": 81115,
"s": 81084,
"text": "Invoking Apex Using JavaScript"
},
{
"code": null,
"e": 81146,
"s": 81115,
"text": "Invoking Apex Using JavaScript"
},
{
"code": null,
"e": 81213,
"s": 81146,
"text": "The Ajax toolkit to invoke Web service methods implemented in Apex"
},
{
"code": null,
"e": 81280,
"s": 81213,
"text": "The Ajax toolkit to invoke Web service methods implemented in Apex"
},
{
"code": null,
"e": 81337,
"s": 81280,
"text": "We will now understand a few common ways to invoke Apex."
},
{
"code": null,
"e": 81431,
"s": 81337,
"text": "You can invoke the Apex class via execute anonymous in the Developer Console as shown below β"
},
{
"code": null,
"e": 81468,
"s": 81431,
"text": "Step 1 β Open the Developer Console."
},
{
"code": null,
"e": 81493,
"s": 81468,
"text": "Step 2 β Click on Debug."
},
{
"code": null,
"e": 81588,
"s": 81493,
"text": "Step 3 β Execute anonymous window will open as shown below. Now, click on the Execute\nbutton β"
},
{
"code": null,
"e": 81654,
"s": 81588,
"text": "Step 4 β Open the Debug Log when it will appear in the Logs pane."
},
{
"code": null,
"e": 81806,
"s": 81654,
"text": "You can call an Apex class from Trigger as well. Triggers are called when a specified event occurs and triggers can call the Apex class when executing."
},
{
"code": null,
"e": 81898,
"s": 81806,
"text": "Following is the sample code that shows how a class gets executed when a Trigger is called."
},
{
"code": null,
"e": 82643,
"s": 81898,
"text": "// Class which will gets called from trigger\npublic without sharing class MyClassWithSharingTrigger {\n\n public static Integer executeQuery (List<apex_customer__c> CustomerList) {\n // perform some logic and operations here\n Integer ListSize = CustomerList.size();\n return ListSize;\n }\n}\n\n// Trigger Code\ntrigger Customer_After_Insert_Example on APEX_Customer__c (after insert) {\n System.debug('Trigger is Called and it will call Apex Class');\n MyClassWithSharingTrigger.executeQuery(Trigger.new); // Calling Apex class and \n // method of an Apex class\n}\n\n// This example is for reference, no need to execute and will have detail look on \n// triggers later chapters."
},
{
"code": null,
"e": 82803,
"s": 82643,
"text": "Apex class can be called from the Visualforce page as well. We can specify the controller or the controller extension and the specified Apex class gets called."
},
{
"code": null,
"e": 82816,
"s": 82803,
"text": "VF Page Code"
},
{
"code": null,
"e": 82855,
"s": 82816,
"text": "Apex Class Code (Controller Extension)"
},
{
"code": null,
"e": 83005,
"s": 82855,
"text": "Apex triggers are like stored procedures which execute when a particular event occurs. A trigger executes before and after an event occurs on record."
},
{
"code": null,
"e": 83080,
"s": 83005,
"text": "trigger triggerName on ObjectName (trigger_events) { Trigger_code_block }\n"
},
{
"code": null,
"e": 83139,
"s": 83080,
"text": "Following are the events on which we can fir the trigger β"
},
{
"code": null,
"e": 83146,
"s": 83139,
"text": "insert"
},
{
"code": null,
"e": 83153,
"s": 83146,
"text": "update"
},
{
"code": null,
"e": 83160,
"s": 83153,
"text": "delete"
},
{
"code": null,
"e": 83166,
"s": 83160,
"text": "merge"
},
{
"code": null,
"e": 83173,
"s": 83166,
"text": "upsert"
},
{
"code": null,
"e": 83182,
"s": 83173,
"text": "undelete"
},
{
"code": null,
"e": 83428,
"s": 83182,
"text": "Suppose we received a business requirement that we need to create an Invoice Record when Customer's 'Customer Status' field changes to Active from Inactive. For this, we will create a trigger on APEX_Customer__c object by following these steps β"
},
{
"code": null,
"e": 83451,
"s": 83428,
"text": "Step 1 β Go to sObject"
},
{
"code": null,
"e": 83478,
"s": 83451,
"text": "Step 2 β Click on Customer"
},
{
"code": null,
"e": 83577,
"s": 83478,
"text": "Step 3 β Click on 'New' button in the Trigger related list and add the trigger code as give below."
},
{
"code": null,
"e": 84053,
"s": 83577,
"text": "// Trigger Code\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n List InvoiceList = new List();\n \n for (APEX_Customer__c objCustomer: Trigger.new) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active') {\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n \n // DML to insert the Invoice List in SFDC\n insert InvoiceList;\n}"
},
{
"code": null,
"e": 84272,
"s": 84053,
"text": "Trigger.new β This is the context variable which stores the records currently in the trigger context, either being inserted or updated. In this case, this variable has Customer object's records which have been updated."
},
{
"code": null,
"e": 84388,
"s": 84272,
"text": "There are other context variables which are available in the context β trigger.old, trigger.newMap, trigger.OldMap."
},
{
"code": null,
"e": 84744,
"s": 84388,
"text": "The above trigger will execute when there is an update operation on the Customer records. Suppose, the invoice record needs to be inserted only when the Customer Status changes from Inactive to Active and not every time; for this, we can use another context variable trigger.oldMap which will store the key as record id and the value as old record values."
},
{
"code": null,
"e": 85408,
"s": 84744,
"text": "// Modified Trigger Code\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\n \n for (APEX_Customer__c objCustomer: Trigger.new) {\n \n // condition to check the old value and new value\n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n \n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n \n // DML to insert the Invoice List in SFDC\n insert InvoiceList;\n}"
},
{
"code": null,
"e": 85569,
"s": 85408,
"text": "We have used the Trigger.oldMap variable which as explained earlier, is a context variable which stores the Id and old value of records which are being updated."
},
{
"code": null,
"e": 85953,
"s": 85569,
"text": "Design patterns are used to make our code more efficient and to avoid hitting the governor limits. Often developers can write inefficient code that can cause repeated instantiation of objects. This can result in inefficient, poorly performing code, and potentially the breaching of governor limits. This most commonly occurs in triggers, as they can operate against a set of records."
},
{
"code": null,
"e": 86023,
"s": 85953,
"text": "We will see some important design pattern strategies in this chapter."
},
{
"code": null,
"e": 86474,
"s": 86023,
"text": "In real business case, it will be possible that you may need to process thousands of records in one go. If your trigger is not designed to handle such situations, then it may fail while\nprocessing the records. There are some best practices which you need to follow while implementing the triggers. All triggers are bulk triggers by default, and can process multiple records at a time. You should always plan to process more than one record at a time."
},
{
"code": null,
"e": 86737,
"s": 86474,
"text": "Consider a business case, wherein, you need to process large number of records and you have written the trigger as given below. This is the same example which we had taken for inserting the invoice record when the Customer Status changes from Inactive to Active."
},
{
"code": null,
"e": 87302,
"s": 86737,
"text": "// Bad Trigger Example\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n \n for (APEX_Customer__c objCustomer: Trigger.new) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' && \n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n insert objInvoice; //DML to insert the Invoice List in SFDC\n }\n }\n}"
},
{
"code": null,
"e": 87639,
"s": 87302,
"text": "You can now see that the DML Statement has been written in for the loop block which will work when processing only few records but when you are processing some hundreds of records, it will reach the DML Statement limit per transaction which is the governor limit. We will have a detailed look on Governor Limits in a subsequent chapter."
},
{
"code": null,
"e": 87735,
"s": 87639,
"text": "To avoid this, we have to make the trigger efficient for processing multiple records at a time."
},
{
"code": null,
"e": 87793,
"s": 87735,
"text": "The following example will help you understand the same β"
},
{
"code": null,
"e": 88598,
"s": 87793,
"text": "// Modified Trigger Code-Bulk Trigger\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\n \n for (APEX_Customer__c objCustomer: Trigger.new) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n //condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);//Adding records to List\n }\n }\n \n insert InvoiceList;\n // DML to insert the Invoice List in SFDC, this list contains the all records \n // which need to be modified and will fire only one DML\n}"
},
{
"code": null,
"e": 88738,
"s": 88598,
"text": "This trigger will only fire 1 DML statement as it will be operating over a List and the List has all the records which need to be modified."
},
{
"code": null,
"e": 88800,
"s": 88738,
"text": "By this way, you can avoid the DML statement governor limits."
},
{
"code": null,
"e": 89048,
"s": 88800,
"text": "Writing the whole code in trigger is also not a good practice. Hence you should call the Apex class and delegate the processing from Trigger to Apex class as shown below. Trigger Helper class is the class which does all the processing for trigger."
},
{
"code": null,
"e": 89107,
"s": 89048,
"text": "Let us consider our invoice record creation example again."
},
{
"code": null,
"e": 90089,
"s": 89107,
"text": "// Below is the Trigger without Helper class\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\n \n for (APEX_Customer__c objCustomer: Trigger.new) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n \n insert InvoiceList; // DML to insert the Invoice List in SFDC\n}\n\n// Below is the trigger with helper class\n// Trigger with Helper Class\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap);\n // Trigger calls the helper class and does not have any code in Trigger\n}"
},
{
"code": null,
"e": 90904,
"s": 90089,
"text": "public class CustomerTriggerHelper {\n public static void createInvoiceRecords (List<apex_customer__c>\n \n customerList, Map<id, apex_customer__c> oldMapCustomer) {\n List<apex_invoice__c> InvoiceList = new Listvapex_invoice__c>();\n \n for (APEX_Customer__c objCustomer: customerList) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n \n // objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n \n insert InvoiceList; // DML to insert the Invoice List in SFDC\n }\n}"
},
{
"code": null,
"e": 91086,
"s": 90904,
"text": "In this, all the processing has been delegated to the helper class and when we need a new functionality we can simply add the code to the helper class without modifying the trigger."
},
{
"code": null,
"e": 91239,
"s": 91086,
"text": "Always create a single trigger on each object. Multiple triggers on the same object can cause the conflict and errors if it reaches the governor limits."
},
{
"code": null,
"e": 91531,
"s": 91239,
"text": "You can use the context variable to call the different methods from helper class as per the requirement. Consider our previous example. Suppose that our createInvoice method should be called only when the record is updated and on multiple events. Then we can control the execution as below β"
},
{
"code": null,
"e": 92795,
"s": 91531,
"text": "// Trigger with Context variable for controlling the calling flow\ntrigger Customer_After_Insert on APEX_Customer__c (after update, after insert) {\n \n if (trigger.isAfter && trigger.isUpdate) {\n // This condition will check for trigger events using isAfter and isUpdate\n // context variable\n CustomerTriggerHelper.createInvoiceRecords(Trigger.new);\n \n // Trigger calls the helper class and does not have any code in Trigger\n // and this will be called only when trigger ids after update\n }\n}\n\n// Helper Class\npublic class CustomerTriggerHelper {\n \n //Method To Create Invoice Records\n public static void createInvoiceRecords (List<apex_customer__c> customerList) {\n \n for (APEX_Customer__c objCustomer: customerList) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n \n insert InvoiceList; // DML to insert the Invoice List in SFDC\n }\n}"
},
{
"code": null,
"e": 92990,
"s": 92795,
"text": "Governor execution limits ensure the efficient use of resources on the Force.com multitenant platform. It is the limit specified by the Salesforce.com on code execution for efficient processing."
},
{
"code": null,
"e": 93395,
"s": 92990,
"text": "As we know, Apex runs in multi-tenant environment, i.e., a single resource is shared by all the customers and organizations. So, it is necessary to make sure that no one monopolizes the resources and hence Salesforce.com has created the set of limits which governs and limits the code execution. Whenever any of the governor limits are crossed, it will throw error and will halt the execution of program."
},
{
"code": null,
"e": 93517,
"s": 93395,
"text": "From a Developer's perspective, it is important to ensure that our code should be scalable and should not hit the limits."
},
{
"code": null,
"e": 93619,
"s": 93517,
"text": "All these limits are applied on per transaction basis. A single trigger execution is one transaction."
},
{
"code": null,
"e": 93732,
"s": 93619,
"text": "As we have seen, the trigger design pattern helps avoid the limit error. We will now see other important limits."
},
{
"code": null,
"e": 93868,
"s": 93732,
"text": "You can issue only 100 queries per transaction, that is, when your code will issue more than 100 SOQL queries then it will throw error."
},
{
"code": null,
"e": 93925,
"s": 93868,
"text": "This example shows how SOQL query limit can be reached β"
},
{
"code": null,
"e": 94059,
"s": 93925,
"text": "The following trigger iterates over a list of customers and updates the child record's (Invoice) description with string 'Ok to Pay'."
},
{
"code": null,
"e": 95760,
"s": 94059,
"text": "// Helper class:Below code needs o be checked.\npublic class CustomerTriggerHelper {\n \n public static void isAfterUpdateCall(Trigger.new) {\n createInvoiceRecords(trigger.new);//Method call\n updateCustomerDescription(trigger.new);\n }\n \n // Method To Create Invoice Records\n public static void createInvoiceRecords (List<apex_customer__c> customerList) {\n for (APEX_Customer__c objCustomer: customerList) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n insert InvoiceList; // DML to insert the Invoice List in SFDC\n }\n \n // Method to update the invoice records\n public static updateCustomerDescription (List<apex_customer__c> customerList) {\n for (APEX_Customer__c objCust: customerList) {\n List<apex_customer__c> invList = [SELECT Id, Name,\n APEX_Description__c FROM APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id];\n \n // This query will fire for the number of records customer list has and will\n // hit the governor limit when records are more than 100\n for (APEX_Invoice__c objInv: invList) {\n objInv.APEX_Description__c = 'OK To Pay';\n update objInv;\n // Update invoice, this will also hit the governor limit for DML if large\n // number(150) of records are there\n }\n }\n }\n}"
},
{
"code": null,
"e": 96023,
"s": 95760,
"text": "When the 'updateCustomerDescription' method is called and the number of customer records are more than 100, then it will hit the SOQL limit. To avoid this, never write the SOQL query in the For Loop. In this case, the SOQL query has been written in the For loop."
},
{
"code": null,
"e": 96271,
"s": 96023,
"text": "Following is an example which will show how to avoid the DML as well as the SOQL limit. We have used the nested relationship query to fetch the invoice records and used the context variable trigger.newMap to get the map of id and Customer records."
},
{
"code": null,
"e": 98082,
"s": 96271,
"text": "// SOQL-Good Way to Write Query and avoid limit exception\n// Helper Class\npublic class CustomerTriggerHelper {\n public static void isAfterUpdateCall(Trigger.new) {\n createInvoiceRecords(trigger.new); //Method call\n updateCustomerDescription(trigger.new, trigger.newMap);\n }\n \n // Method To Create Invoice Records\n public static void createInvoiceRecords (List<apex_customer__c> customerList) {\n for (APEX_Customer__c objCustomer: customerList) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n insert InvoiceList; // DML to insert the Invoice List in SFDC\n }\n \n // Method to update the invoice records\n public static updateCustomerDescription (List<apex_customer__c>\n customerList, Map<id, apex_customer__c> newMapVariable) {\n List<apex_customer__c> customerListWithInvoice = [SELECT id,\n Name,(SELECT Id, Name, APEX_Description__c FROM APEX_Invoice__r) FROM\n APEX_Customer__c WHERE Id IN :newMapVariable.keySet()];\n \n // Query will be for only one time and fetches all the records\n List<apex_invoice__c> invoiceToUpdate = new\n List<apex_invoice__c>();\n \n for (APEX_Customer__c objCust: customerList) {\n for (APEX_Invoice__c objInv: invList) {\n objInv.APEX_Description__c = 'OK To Pay';\n invoiceToUpdate.add(objInv);\n // Add the modified records to List\n }\n }\n update invoiceToUpdate;\n }\n}"
},
{
"code": null,
"e": 98227,
"s": 98082,
"text": "This example shows the Bulk trigger along with the trigger helper class pattern. You must save the helper class first and then save the trigger."
},
{
"code": null,
"e": 98319,
"s": 98227,
"text": "Note β Paste the below code in 'CustomerTriggerHelper' class which we have created earlier."
},
{
"code": null,
"e": 101701,
"s": 98319,
"text": "// Helper Class\npublic class CustomerTriggerHelper {\n public static void isAfterUpdateCall(List<apex_customer__c> customerList,\n Map<id, apex_customer__c> mapIdToCustomers, Map<id, apex_customer__c>\n mapOldItToCustomers) {\n createInvoiceRecords(customerList, mapOldItToCustomers); //Method call\n updateCustomerDescription(customerList,mapIdToCustomers,\n mapOldItToCustomers);\n }\n \n // Method To Create Invoice Records\n public static void createInvoiceRecords (List<apex_customer__c>\n customerList, Map<id, apex_customer__c> mapOldItToCustomers) {\n List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\n List<apex_customer__c> customerToInvoice = [SELECT id, Name FROM\n APEX_Customer__c LIMIT 1];\n \n for (APEX_Customer__c objCustomer: customerList) {\n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n mapOldItToCustomers.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n //condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n objInvoice.APEX_Customer__c = objCustomer.id;\n InvoiceList.add(objInvoice);\n }\n }\n system.debug('InvoiceList&&&'+InvoiceList);\n insert InvoiceList;\n // DML to insert the Invoice List in SFDC. This also follows the Bulk pattern\n }\n \n // Method to update the invoice records\n public static void updateCustomerDescription (List<apex_customer__c>\n customerList, Map<id, apex_customer__c> newMapVariable, Map<id,\n apex_customer__c> oldCustomerMap) {\n List<apex_customer__c> customerListWithInvoice = [SELECT id,\n Name,(SELECT Id, Name, APEX_Description__c FROM Invoices__r) FROM\n APEX_Customer__c WHERE Id IN :newMapVariable.keySet()];\n \n // Query will be for only one time and fetches all the records\n List<apex_invoice__c> invoiceToUpdate = new List<apex_invoice__c>();\n List<apex_invoice__c> invoiceFetched = new List<apex_invoice__c>();\n invoiceFetched = customerListWithInvoice[0].Invoices__r;\n system.debug('invoiceFetched'+invoiceFetched);\n system.debug('customerListWithInvoice****'+customerListWithInvoice);\n \n for (APEX_Customer__c objCust: customerList) {\n system.debug('objCust.Invoices__r'+objCust.Invoices__r);\n if (objCust.APEX_Active__c == true &&\n oldCustomerMap.get(objCust.id).APEX_Active__c == false) {\n for (APEX_Invoice__c objInv: invoiceFetched) {\n system.debug('I am in For Loop'+objInv);\n objInv.APEX_Description__c = 'OK To Pay';\n invoiceToUpdate.add(objInv);\n // Add the modified records to List\n }\n }\n }\n system.debug('Value of List ***'+invoiceToUpdate);\n update invoiceToUpdate;\n // This statement is Bulk DML which performs the DML on List and avoids\n // the DML Governor limit\n }\n}\n\n// Trigger Code for this class: Paste this code in 'Customer_After_Insert'\n// trigger on Customer Object\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n CustomerTriggerHelper.isAfterUpdateCall(Trigger.new, trigger.newMap,\n trigger.oldMap);\n // Trigger calls the helper class and does not have any code in Trigger\n}"
},
{
"code": null,
"e": 101759,
"s": 101701,
"text": "Following table lists down the important governor limits."
},
{
"code": null,
"e": 101972,
"s": 101759,
"text": "In this chapter, we will understand Batch Processing in Apex. Consider a scenario wherein, we will process large number of records on daily basis, probably the cleaning of data or maybe deleting some unused data."
},
{
"code": null,
"e": 102159,
"s": 101972,
"text": "Batch Apex is asynchronous execution of Apex code, specially designed for processing the large number of records and has greater flexibility in governor limits than the synchronous code."
},
{
"code": null,
"e": 102292,
"s": 102159,
"text": "When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex."
},
{
"code": null,
"e": 102425,
"s": 102292,
"text": "When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex."
},
{
"code": null,
"e": 102809,
"s": 102425,
"text": "Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data."
},
{
"code": null,
"e": 103193,
"s": 102809,
"text": "Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data."
},
{
"code": null,
"e": 103343,
"s": 103193,
"text": "When we are using the Batch Apex, we must implement the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically."
},
{
"code": null,
"e": 103396,
"s": 103343,
"text": "You can monitor the class by following these steps β"
},
{
"code": null,
"e": 103516,
"s": 103396,
"text": "To monitor or stop the execution of the batch Apex Batch job, go to Setup β Monitoring β Apex Jobs or Jobs β Apex Jobs."
},
{
"code": null,
"e": 103607,
"s": 103516,
"text": "Database.Batchable interface has the following three methods that need to be implemented β"
},
{
"code": null,
"e": 103613,
"s": 103607,
"text": "Start"
},
{
"code": null,
"e": 103621,
"s": 103613,
"text": "Execute"
},
{
"code": null,
"e": 103628,
"s": 103621,
"text": "Finish"
},
{
"code": null,
"e": 103673,
"s": 103628,
"text": "Let us now understand each method in detail."
},
{
"code": null,
"e": 103755,
"s": 103673,
"text": "The Start method is one of the three methods of the Database.Batchable interface."
},
{
"code": null,
"e": 103762,
"s": 103755,
"text": "Syntax"
},
{
"code": null,
"e": 103831,
"s": 103762,
"text": "global void execute(Database.BatchableContext BC, list<sobject<) {}\n"
},
{
"code": null,
"e": 103955,
"s": 103831,
"text": "This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating."
},
{
"code": null,
"e": 104012,
"s": 103955,
"text": "Consider the following points to understand the method β"
},
{
"code": null,
"e": 104195,
"s": 104012,
"text": "Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed."
},
{
"code": null,
"e": 104378,
"s": 104195,
"text": "Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed."
},
{
"code": null,
"e": 104538,
"s": 104378,
"text": "Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed."
},
{
"code": null,
"e": 104698,
"s": 104538,
"text": "Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed."
},
{
"code": null,
"e": 104776,
"s": 104698,
"text": "Let us now understand the Execute method of the Database.Batchable interface."
},
{
"code": null,
"e": 104783,
"s": 104776,
"text": "Syntax"
},
{
"code": null,
"e": 104852,
"s": 104783,
"text": "global void execute(Database.BatchableContext BC, list<sobject<) {}\n"
},
{
"code": null,
"e": 104922,
"s": 104852,
"text": "where, list<sObject< is returned by the Database.QueryLocator method."
},
{
"code": null,
"e": 105021,
"s": 104922,
"text": "This method gets called after the Start method and does all the processing required for Batch Job."
},
{
"code": null,
"e": 105096,
"s": 105021,
"text": "We will now discuss the Finish method of the Database.Batchable interface."
},
{
"code": null,
"e": 105103,
"s": 105096,
"text": "Syntax"
},
{
"code": null,
"e": 105156,
"s": 105103,
"text": "global void finish(Database.BatchableContext BC) {}\n"
},
{
"code": null,
"e": 105321,
"s": 105156,
"text": "This method gets called at the end and you can do some finishing activities like sending an email with information about the batch job records processed and status."
},
{
"code": null,
"e": 105779,
"s": 105321,
"text": "Let us consider an example of our existing Chemical Company and assume that we have requirement to update the Customer Status and Customer Description field of Customer Records which have been marked as Active and which have created Date as today. This should be done on daily basis and an email should be sent to a User about the status of the Batch Processing. Update the Customer Status as 'Processed' and Customer Description as 'Updated Via Batch Job'."
},
{
"code": null,
"e": 108490,
"s": 105779,
"text": "// Batch Job for Processing the Records\nglobal class CustomerProessingBatch implements Database.Batchable<sobject> {\n global String [] email = new String[] {'[email protected]'};\n // Add here your email address here\n \n // Start Method\n global Database.Querylocator start (Database.BatchableContext BC) {\n return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,\n APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today\n AND APEX_Active__c = true');\n // Query which will be determine the scope of Records fetching the same\n }\n \n // Execute method\n global void execute (Database.BatchableContext BC, List<sobject> scope) {\n List<apex_customer__c> customerList = new List<apex_customer__c>();\n List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>();\n \n // List to hold updated customer\n for (sObject objScope: scope) {\n APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;\n \n // type casting from generic sOject to APEX_Customer__c\n newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';\n newObjScope.APEX_Customer_Status__c = 'Processed';\n updtaedCustomerList.add(newObjScope); // Add records to the List\n System.debug('Value of UpdatedCustomerList '+updtaedCustomerList);\n }\n \n if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {\n // Check if List is empty or not\n Database.update(updtaedCustomerList); System.debug('List Size '\n + updtaedCustomerList.size());\n // Update the Records\n }\n }\n \n // Finish Method\n global void finish(Database.BatchableContext BC) {\n Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();\n \n // Below code will fetch the job Id\n AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,\n a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,\n a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];\n \n // get the job Id\n System.debug('$$$ Jobid is'+BC.getJobId());\n \n // below code will send an email to User about the status\n mail.setToAddresses(email);\n mail.setReplyTo('[email protected]'); // Add here your email address\n mail.setSenderDisplayName('Apex Batch Processing Module');\n mail.setSubject('Batch Processing '+a.Status);\n mail.setPlainTextBody('The Batch Apex job processed'\n + a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item\n processed are'+a.JobItemsProcessed);\n Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});\n }\n}"
},
{
"code": null,
"e": 108831,
"s": 108490,
"text": "To execute this code, first save it and then paste the following code in Execute anonymous. This will create the object of class and Database.execute method will execute the Batch job. Once the job is completed then an email will be sent to the specified email address. Make sure that you have a customer record which has Active as checked."
},
{
"code": null,
"e": 108959,
"s": 108831,
"text": "// Paste in Developer Console\nCustomerProessingBatch objClass = new CustomerProessingBatch();\nDatabase.executeBatch (objClass);"
},
{
"code": null,
"e": 109187,
"s": 108959,
"text": "Once this class is executed, then check the email address you have provided where you will receive the email with information. Also, you can check the status of the batch job via the Monitoring page and steps as provided above."
},
{
"code": null,
"e": 109302,
"s": 109187,
"text": "If you check the debug logs, then you can find the List size which indicates how many records have been processed."
},
{
"code": null,
"e": 109314,
"s": 109302,
"text": "Limitations"
},
{
"code": null,
"e": 109411,
"s": 109314,
"text": "We can only have 5 batch job processing at a time. This is one of the limitations of Batch Apex."
},
{
"code": null,
"e": 109481,
"s": 109411,
"text": "You can schedule the Apex class via Apex detail page as given below β"
},
{
"code": null,
"e": 109541,
"s": 109481,
"text": "Step 1 β Go to Setup β Apex Classes, Click on Apex Classes."
},
{
"code": null,
"e": 109585,
"s": 109541,
"text": "Step 2 β Click on the Schedule Apex button."
},
{
"code": null,
"e": 109611,
"s": 109585,
"text": "Step 3 β Provide details."
},
{
"code": null,
"e": 109692,
"s": 109611,
"text": "You can schedule the Apex Batch Job using Schedulable Interface as given below β"
},
{
"code": null,
"e": 112721,
"s": 109692,
"text": "// Batch Job for Processing the Records\nglobal class CustomerProessingBatch implements Database.Batchable<sobject> {\n global String [] email = new String[] {'[email protected]'};\n // Add here your email address here\n \n // Start Method\n global Database.Querylocator start (Database.BatchableContext BC) {\n return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,\n APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today\n AND APEX_Active__c = true');\n // Query which will be determine the scope of Records fetching the same\n }\n \n // Execute method\n global void execute (Database.BatchableContext BC, List<sobject> scope) {\n List<apex_customer__c> customerList = new List<apex_customer__c>();\n List<apex_customer__c> updtaedCustomerList = new\n List<apex_customer__c>();//List to hold updated customer\n \n for (sObject objScope: scope) {\n APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;//type\n casting from generic sOject to APEX_Customer__c\n newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';\n newObjScope.APEX_Customer_Status__c = 'Processed';\n updtaedCustomerList.add(newObjScope);//Add records to the List\n System.debug('Value of UpdatedCustomerList '+updtaedCustomerList);\n }\n \n if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {\n // Check if List is empty or not\n Database.update(updtaedCustomerList); System.debug('List Size'\n + updtaedCustomerList.size());\n // Update the Records\n }\n }\n \n // Finish Method\n global void finish(Database.BatchableContext BC) {\n Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();\n \n // Below code will fetch the job Id\n AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,\n a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,\n a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id\n System.debug('$$$ Jobid is'+BC.getJobId());\n \n // below code will send an email to User about the status\n mail.setToAddresses(email);\n mail.setReplyTo('[email protected]');//Add here your email address\n mail.setSenderDisplayName('Apex Batch Processing Module');\n mail.setSubject('Batch Processing '+a.Status);\n mail.setPlainTextBody('The Batch Apex job processed' \n + a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item\n processed are'+a.JobItemsProcessed);\n Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});\n }\n \n // Scheduler Method to scedule the class\n global void execute(SchedulableContext sc) {\n CustomerProessingBatch conInstance = new CustomerProessingBatch();\n database.executebatch(conInstance,100);\n }\n}\n\n// Paste in Developer Console\nCustomerProessingBatch objClass = new CustomerProcessingBatch();\nDatabase.executeBatch (objClass);"
},
{
"code": null,
"e": 112953,
"s": 112721,
"text": "Debugging is an important part in any programming development. In Apex, we have certain tools that can be used for debugging. One of them is the system.debug() method which prints the value and output of variable in the debug logs."
},
{
"code": null,
"e": 113004,
"s": 112953,
"text": "We can use the following two tools for debugging β"
},
{
"code": null,
"e": 113022,
"s": 113004,
"text": "Developer Console"
},
{
"code": null,
"e": 113033,
"s": 113022,
"text": "Debug Logs"
},
{
"code": null,
"e": 113137,
"s": 113033,
"text": "You can use the Developer console and execute anonymous functionality for debugging the Apex as below β"
},
{
"code": null,
"e": 113145,
"s": 113137,
"text": "Example"
},
{
"code": null,
"e": 113355,
"s": 113145,
"text": "Consider our existing example of fetching the customer records which have been created today. We just want to know if the query is returning the results or not and if yes, then we will check the value of List."
},
{
"code": null,
"e": 113488,
"s": 113355,
"text": "Paste the code given below in execute anonymous window and follow the steps which we have done for opening execute anonymous window."
},
{
"code": null,
"e": 113524,
"s": 113488,
"text": "Step 1 β Open the Developer console"
},
{
"code": null,
"e": 113589,
"s": 113524,
"text": "Step 2 β Open the Execute anonymous from 'Debug' as shown below."
},
{
"code": null,
"e": 113683,
"s": 113589,
"text": "Step 3 β Open the Execute Anonymous window and paste the following code and click on execute."
},
{
"code": null,
"e": 114007,
"s": 113683,
"text": "// Debugging The Apex\nList<apex_customer__c> customerList = new List<apex_customer__c>();\ncustomerList = [SELECT Id, Name FROM APEX_Customer__c WHERE CreatedDate =\ntoday];\n// Our Query\nSystem.debug('Records on List are '+customerList+' And Records are '+customerList);\n// Debug statement to check the value of List and Size"
},
{
"code": null,
"e": 114046,
"s": 114007,
"text": "Step 4 β Open the Logs as shown below."
},
{
"code": null,
"e": 114104,
"s": 114046,
"text": "Step 5 β Enter 'USER' in filter condition as shown below."
},
{
"code": null,
"e": 114159,
"s": 114104,
"text": "Step 6 β Open the USER DEBUG Statement as shown below."
},
{
"code": null,
"e": 114370,
"s": 114159,
"text": "You can debug the same class via debug logs as well. Suppose, you have a trigger in Customer object and it needs to be debugged for some variable values, then you can do this via the debug logs as shown below β"
},
{
"code": null,
"e": 114545,
"s": 114370,
"text": "This is the Trigger Code which updates the Description field if the modified customer is active and you want to check the values of variables and records currently in scope β"
},
{
"code": null,
"e": 114988,
"s": 114545,
"text": "trigger CustomerTrigger on APEX_Customer__c (before update) {\n List<apex_customer__c> customerList = new List<apex_customer__c>();\n for (APEX_Customer__c objCust: Trigger.new) {\n System.debug('objCust current value is'+objCust);\n \n if (objCust.APEX_Active__c == true) {\n objCust.APEX_Customer_Description__c = 'updated';\n System.debug('The record which has satisfied the condition '+objCust);\n }\n }\n}"
},
{
"code": null,
"e": 115045,
"s": 114988,
"text": "Follow the steps given below to generate the Debug logs."
},
{
"code": null,
"e": 115168,
"s": 115045,
"text": "Step 1 β Set the Debug logs for your user. Go to Setup and type 'Debug Log' in search\nsetup window and then click on Link."
},
{
"code": null,
"e": 115210,
"s": 115168,
"text": "Step 2 β Set the debug logs as following."
},
{
"code": null,
"e": 115286,
"s": 115210,
"text": "Step 3 β Enter the name of User which requires setup. Enter your name here."
},
{
"code": null,
"e": 115372,
"s": 115286,
"text": "Step 4 β Modify the customer records as event should occur to generate the debug log."
},
{
"code": null,
"e": 115461,
"s": 115372,
"text": "Step 5 β Now go to the debug logs section again. Open the debug logs and click on Reset."
},
{
"code": null,
"e": 115517,
"s": 115461,
"text": "Step 6 β Click on the view link of the first debug log."
},
{
"code": null,
"e": 115599,
"s": 115517,
"text": "Step 7 β Search for the string 'USER' by using the browser search as shown below."
},
{
"code": null,
"e": 115684,
"s": 115599,
"text": "The debug statement will show the value of the field at which we have set the point."
},
{
"code": null,
"e": 115837,
"s": 115684,
"text": "Testing is the integrated part of Apex or any other application development. In Apex, we have separate test classes to develop for all the unit testing."
},
{
"code": null,
"e": 116060,
"s": 115837,
"text": "In SFDC, the code must have 75% code coverage in order to be deployed to Production. This code coverage is performed by the test classes. Test classes are the code snippets which test the functionality of other Apex class."
},
{
"code": null,
"e": 116275,
"s": 116060,
"text": "Let us write a test class for one of our codes which we have written previously. We will write test class to cover our Trigger and Helper class code. Below is the trigger and helper class which needs to be covered."
},
{
"code": null,
"e": 117390,
"s": 116275,
"text": "// Trigger with Helper Class\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap);\n //Trigger calls the helper class and does not have any code in Trigger\n}\n\n// Helper Class:\npublic class CustomerTriggerHelper {\n public static void createInvoiceRecords (List<apex_customer__c>\n \n customerList, Map<id, apex_customer__c> oldMapCustomer) {\n List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\n \n for (APEX_Customer__c objCustomer: customerList) {\n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n objInvoice.APEX_Customer__c = objCustomer.id;\n InvoiceList.add(objInvoice);\n }\n }\n insert InvoiceList; // DML to insert the Invoice List in SFDC\n }\n}"
},
{
"code": null,
"e": 117454,
"s": 117390,
"text": "In this section, we will understand how to create a Test Class."
},
{
"code": null,
"e": 117686,
"s": 117454,
"text": "We need to create data for test class in our test class itself. Test class by default does not have access to organization data but if you set @isTest(seeAllData = true), then it will have the access to organization's data as well."
},
{
"code": null,
"e": 117823,
"s": 117686,
"text": "By using this annotation, you declared that this is a test class and it will not be counted against the organization's total code limit."
},
{
"code": null,
"e": 118122,
"s": 117823,
"text": "Unit test methods are the methods which do not take arguments, commit no data to the database, send no emails, and are declared with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest."
},
{
"code": null,
"e": 118181,
"s": 118122,
"text": "We have used the 'myUnitTest' test method in our examples."
},
{
"code": null,
"e": 118586,
"s": 118181,
"text": "These are the standard test methods which are available for test classes. These methods contain the event or action for which we will be simulating our test. Like in this example, we will test our trigger and helper class to simulate the fire trigger by updating the records as we have done to start and stop block. This also provides separate governor limit to the code which is in start and stop block."
},
{
"code": null,
"e": 118743,
"s": 118586,
"text": "This method checks the desired output with the actual. In this case, we are expecting an Invoice record to be inserted so we added assert to check the same."
},
{
"code": null,
"e": 118751,
"s": 118743,
"text": "Example"
},
{
"code": null,
"e": 120696,
"s": 118751,
"text": "/**\n* This class contains unit tests for validating the behavior of Apex classes\n* and triggers.\n*\n* Unit tests are class methods that verify whether a particular piece\n* of code is working properly. Unit test methods take no arguments,\n* commit no data to the database, and are flagged with the testMethod\n* keyword in the method definition.\n*\n* All test methods in an organization are executed whenever Apex code is deployed\n* to a production organization to confirm correctness, ensure code\n* coverage, and prevent regressions. All Apex classes are\n* required to have at least 75% code coverage in order to be deployed\n* to a production organization. In addition, all triggers must have some code coverage.\n*\n* The @isTest class annotation indicates this class only contains test\n* methods. Classes defined with the @isTest annotation do not count against\n* the organization size limit for all Apex scripts.\n*\n* See the Apex Language Reference for more information about Testing and Code Coverage.\n*/\n\n@isTest\nprivate class CustomerTriggerTestClass {\n static testMethod void myUnitTest() {\n //Create Data for Customer Objet\n APEX_Customer__c objCust = new APEX_Customer__c();\n objCust.Name = 'Test Customer';\n objCust.APEX_Customer_Status__c = 'Inactive';\n insert objCust;\n \n // Now, our trigger will fire on After update event so update the Records\n Test.startTest(); // Starts the scope of test\n objCust.APEX_Customer_Status__c = 'Active';\n update objCust;\n Test.stopTest(); // Ends the scope of test\n \n // Now check if it is giving desired results using system.assert\n // Statement.New invoice should be created\n List<apex_invoice__c> invList = [SELECT Id, APEX_Customer__c FROM\n APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id];\n system.assertEquals(1,invList.size());\n // Check if one record is created in Invoivce sObject\n }\n}"
},
{
"code": null,
"e": 120749,
"s": 120696,
"text": "Follow the steps given below to run the test class β"
},
{
"code": null,
"e": 120831,
"s": 120749,
"text": "Step 1 β Go to Apex classes β click on the class name 'CustomerTriggerTestClass'."
},
{
"code": null,
"e": 120875,
"s": 120831,
"text": "Step 2 β Click on Run Test button as shown."
},
{
"code": null,
"e": 120897,
"s": 120875,
"text": "Step 3 β Check status"
},
{
"code": null,
"e": 120973,
"s": 120897,
"text": "Step 4 β Now check the class and trigger for which we have written the test"
},
{
"code": null,
"e": 121014,
"s": 120973,
"text": "Our testing is successful and completed."
},
{
"code": null,
"e": 121545,
"s": 121014,
"text": "Till now we have developed code in Developer Edition, but in real life scenario, you have to do this development in Sandbox and then you might need to deploy this to another sandbox or production environment and this is called the deployment. In short, this is the movement of metadata from one organization to another. The reason behind this is that you cannot develop Apex in your Salesforce production organization. Live users accessing the system while you are developing can destabilize your data or corrupt your application."
},
{
"code": null,
"e": 121578,
"s": 121545,
"text": "Tools available for deployment β"
},
{
"code": null,
"e": 121592,
"s": 121578,
"text": "Force.com IDE"
},
{
"code": null,
"e": 121604,
"s": 121592,
"text": "Change Sets"
},
{
"code": null,
"e": 121613,
"s": 121604,
"text": "SOAP API"
},
{
"code": null,
"e": 121638,
"s": 121613,
"text": "Force.com Migration Tool"
},
{
"code": null,
"e": 121900,
"s": 121638,
"text": "As we are using the Developer Edition for our development and learning purpose, we cannot use the Change Set or other tools which need the SFDC enterprise or other paid edition. Hence, we will be elaborating the Force.com IDE deployment method in this tutorial."
},
{
"code": null,
"e": 121976,
"s": 121900,
"text": "Step 1 β Open Eclipse and open the class trigger that needs to be deployed."
},
{
"code": null,
"e": 122125,
"s": 121976,
"text": "Step 2 β Once you click on 'Deploy to server', then enter the username and password of the organization wherein, the Component needs to be deployed."
},
{
"code": null,
"e": 122232,
"s": 122125,
"text": "By performing the above mentioned steps, your Apex components will be deployed to the target organization."
},
{
"code": null,
"e": 122432,
"s": 122232,
"text": "You can deploy Validation rules, workflow rules, Apex classes and Trigger from one organization to other by connecting them via the deployment settings. In this case, organizations must be connected."
},
{
"code": null,
"e": 122563,
"s": 122432,
"text": "To open the deployment setup, follow the steps given below. Remember that this feature is not available in the Developer Edition β"
},
{
"code": null,
"e": 122609,
"s": 122563,
"text": "Step 1 β Go to Setup and search for 'Deploy'."
},
{
"code": null,
"e": 122690,
"s": 122609,
"text": "Step 2 β Click on 'Outbound Change Set' in order to create change set to deploy."
},
{
"code": null,
"e": 122786,
"s": 122690,
"text": "Step 3 β Add components to change set using the 'Add' button and then Save and click on Upload."
},
{
"code": null,
"e": 122890,
"s": 122786,
"text": "Step 4 β Go to the Target organization and click on the inbound change set and finally click on deploy."
},
{
"code": null,
"e": 122979,
"s": 122890,
"text": "We will just have a small overview of this method as this is not a commonly-used method."
},
{
"code": null,
"e": 123045,
"s": 122979,
"text": "You can use the method calls given below to deploy your metadata."
},
{
"code": null,
"e": 123062,
"s": 123045,
"text": "compileAndTest()"
},
{
"code": null,
"e": 123079,
"s": 123062,
"text": "compileClasses()"
},
{
"code": null,
"e": 123097,
"s": 123079,
"text": "compileTriggers()"
},
{
"code": null,
"e": 123329,
"s": 123097,
"text": "This tool is used for the scripted deployment. You have to download the Force.com Migration tool and then you can perform the file based deployment. You can download the Force.com migration tool and then do the scripted deployment."
},
{
"code": null,
"e": 123362,
"s": 123329,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 123375,
"s": 123362,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 123407,
"s": 123375,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 123415,
"s": 123407,
"text": " Uplatz"
},
{
"code": null,
"e": 123448,
"s": 123415,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 123473,
"s": 123448,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 123506,
"s": 123473,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 123521,
"s": 123506,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 123554,
"s": 123521,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 123567,
"s": 123554,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 123602,
"s": 123567,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 123614,
"s": 123602,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 123621,
"s": 123614,
"text": " Print"
},
{
"code": null,
"e": 123632,
"s": 123621,
"text": " Add Notes"
}
]
|
Efficiently Reading Input For Competitive Programming using Java 8 - GeeksforGeeks | 08 Oct, 2021
As we all know, while solving any CP problems, the very first step is collecting input or reading input. A common mistake we all make is spending too much time on writing code and compile-time as well. In Java, it is recommended to use BufferedReader over Scanner to accept input from the user. Why? It is discussed in one of our previous articles here. (Also, the issues associated with the java.util.Scanner is available) Yet for a better understanding, we will go through both the implementations in this article.
Ways of Reading Inputs
Using Scanner class
Using BufferedReader class
Using BufferedReader class with help of streams (More optimized)
Now let us discuss ways of reading individually to depth by providing clean java programs and perceiving the output generated from the custom input.
Way 1: Simple Scanner Input Reading
The java.util.Scanner class provides inbuilt methods to read primitive data from the console along with the lines of text. In the below code snippet letβs understand how it is done.
Example
Java
// Java Program Illustrating Reading Input// Using Scanner class // Importing Arrays and Scanner class// from java.util packageimport java.util.Arrays;import java.util.Scanner; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of Scanner class Scanner scan = new Scanner(System.in); // Basic Input Reading int a = scan.nextInt(); float b = scan.nextFloat(); System.out.println("Integer value: " + a); System.out.println("Float value: " + b); // Space Separated Input Reading int[] arr = new int[5]; for (int i = 0; i < arr.length; i++) { arr[i] = scan.nextInt(); } System.out.println(Arrays.toString(arr)); }}
Output:
From the above Linux shell output we can conclude that input is given as is follows:
4
5.6
1 2 3 4 5
The output generated is as follows:
Integer value: 4
Float value: 5.6
[1, 2, 3, 4, 5]
The above example illustrates the most common approach used by the majority of programmers while solving competitive programming problems. But what if we can enhance our code a bit to make it faster and reliable?
Method 2: Simple BufferedReader Input Reading
java.io.BufferedReader class does not provide any method to read primitive data inputs. Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of the sequence of characters. Although it throws a checked exception known as IOException. Let us see how to handle that exception and read input from the user. Consider custom input as below as follows:
Input:
4
5.6
1 2 3 4 5
Example
Java
// Java Program Illustrating Reading Input// Using // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Reading input via BufferedReader class BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // Basic Input Reading int a = Integer.parseInt(br.readLine()); float b = Float.parseFloat(br.readLine()); // Print above input values in console System.out.println("Integer value: " + a); System.out.println("Float value: " + b); // Space Separated Input Reading int[] arr = new int[5]; String[] strArr = br.readLine().split(" "); for (int i = 0; i < arr.length; i++) { arr[i] = Integer.parseInt(strArr[i]); } // Printing the elements in array // using toString() method System.out.println(Arrays.toString(arr)); }}
Output:
Integer value: 4
Float value: 5.6
[1, 2, 3, 4, 5]
The above example illustrates another common approach used to read the data while solving competitive programming problems. So is this enough? What if we can enhance it even more? Yes. It is possible. Stay tuned.
Method 3: Enhanced way for reading separated data using BufferedReader via Streams
In the previous examples, we have seen while reading space-separated data we stored it first in a String array, and then we iterated over elements and then used java typecasting to convert it to the required data type. How about a single line of code making this possible? Yes. Java 8βs stream library provides a variety of functions to make it easy and optimized. Consider custom input as below as follows:
Input:
34 55 78 43 78 43 22
94 67 96 32 79 6 33
Example
Java
// Java Program to Read Separated Data// Using BufferedReader class voa enhanced for loopd // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Reading input separated by space BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // Storing in array int[] arr = Stream.of(br.readLine().split(" ")) .mapToInt(Integer::parseInt) .toArray(); System.out.println(Arrays.toString(arr)); // Using streams concepts to parse map to integer // later on collecting via Collectors via toList() // method and storing it an integer list List<Integer> arrayList = Stream.of(br.readLine().split(" ")) .mapToInt(Integer::parseInt) .boxed() .collect(Collectors.toList()); // Print the above List as created System.out.println(arrayList); }}
Output:
[34, 55, 78, 43, 78, 43, 22]
[94, 67, 96, 32, 79, 6, 33]
The above example illustrates how we can read separated input and store it into the required data structure using a single line of code. Using java8 there might be a possibility that programmers are comfortable with List collection. Thatβs why it is covered. Now, let us understand code word by word.
Storing into int array:
1. java.util.stream.Stream.of() β Creates stream of string array passed
2. br.readLine().split(β β) β Converts input string into string array based on separator value. (Blank Space β β β in example)
3. mapToInt(Integer::parseInt) β Converts String element into the required data type using suitable mapper function (Integerβs parseInt() in example)
4. toArray() β converts the stream of int elements into an array
Storing into the List Collection:
1. java.util.stream.Stream.of() β Creates stream of string array passed
2. br.readLine().split(β β) β Converts input string into string array based on separator value. (Blank Space β β β in example)
3. mapToInt(Integer::parseInt) β Converts String element into the required data type using suitable mapper function (Integerβs parseInt() in example)
4. boxed() β boxes the stream to Integer elements
5. collect(Collectors.toList()) β creates a collection of Integer elements and converts it to the java.util.List Collection.
kashishsoda
varshagumber28
Blogathon-2021
Java 8
Blogathon
Competitive Programming
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
SQL Query to Convert Datetime to Date
SQL Query to Create Table With a Primary Key
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Bits manipulation (Important tactics)
Top 10 Algorithms and Data Structures for Competitive Programming | [
{
"code": null,
"e": 24836,
"s": 24808,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 25353,
"s": 24836,
"text": "As we all know, while solving any CP problems, the very first step is collecting input or reading input. A common mistake we all make is spending too much time on writing code and compile-time as well. In Java, it is recommended to use BufferedReader over Scanner to accept input from the user. Why? It is discussed in one of our previous articles here. (Also, the issues associated with the java.util.Scanner is available) Yet for a better understanding, we will go through both the implementations in this article."
},
{
"code": null,
"e": 25377,
"s": 25353,
"text": "Ways of Reading Inputs "
},
{
"code": null,
"e": 25397,
"s": 25377,
"text": "Using Scanner class"
},
{
"code": null,
"e": 25424,
"s": 25397,
"text": "Using BufferedReader class"
},
{
"code": null,
"e": 25489,
"s": 25424,
"text": "Using BufferedReader class with help of streams (More optimized)"
},
{
"code": null,
"e": 25639,
"s": 25489,
"text": "Now let us discuss ways of reading individually to depth by providing clean java programs and perceiving the output generated from the custom input. "
},
{
"code": null,
"e": 25675,
"s": 25639,
"text": "Way 1: Simple Scanner Input Reading"
},
{
"code": null,
"e": 25857,
"s": 25675,
"text": "The java.util.Scanner class provides inbuilt methods to read primitive data from the console along with the lines of text. In the below code snippet letβs understand how it is done."
},
{
"code": null,
"e": 25865,
"s": 25857,
"text": "Example"
},
{
"code": null,
"e": 25870,
"s": 25865,
"text": "Java"
},
{
"code": "// Java Program Illustrating Reading Input// Using Scanner class // Importing Arrays and Scanner class// from java.util packageimport java.util.Arrays;import java.util.Scanner; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of Scanner class Scanner scan = new Scanner(System.in); // Basic Input Reading int a = scan.nextInt(); float b = scan.nextFloat(); System.out.println(\"Integer value: \" + a); System.out.println(\"Float value: \" + b); // Space Separated Input Reading int[] arr = new int[5]; for (int i = 0; i < arr.length; i++) { arr[i] = scan.nextInt(); } System.out.println(Arrays.toString(arr)); }}",
"e": 26650,
"s": 25870,
"text": null
},
{
"code": null,
"e": 26658,
"s": 26650,
"text": "Output:"
},
{
"code": null,
"e": 26743,
"s": 26658,
"text": "From the above Linux shell output we can conclude that input is given as is follows:"
},
{
"code": null,
"e": 26759,
"s": 26743,
"text": "4\n5.6\n1 2 3 4 5"
},
{
"code": null,
"e": 26795,
"s": 26759,
"text": "The output generated is as follows:"
},
{
"code": null,
"e": 26845,
"s": 26795,
"text": "Integer value: 4\nFloat value: 5.6\n[1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 27059,
"s": 26845,
"text": "The above example illustrates the most common approach used by the majority of programmers while solving competitive programming problems. But what if we can enhance our code a bit to make it faster and reliable? "
},
{
"code": null,
"e": 27105,
"s": 27059,
"text": "Method 2: Simple BufferedReader Input Reading"
},
{
"code": null,
"e": 27533,
"s": 27105,
"text": "java.io.BufferedReader class does not provide any method to read primitive data inputs. Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of the sequence of characters. Although it throws a checked exception known as IOException. Let us see how to handle that exception and read input from the user. Consider custom input as below as follows:"
},
{
"code": null,
"e": 27540,
"s": 27533,
"text": "Input:"
},
{
"code": null,
"e": 27556,
"s": 27540,
"text": "4\n5.6\n1 2 3 4 5"
},
{
"code": null,
"e": 27564,
"s": 27556,
"text": "Example"
},
{
"code": null,
"e": 27569,
"s": 27564,
"text": "Java"
},
{
"code": "// Java Program Illustrating Reading Input// Using // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Reading input via BufferedReader class BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // Basic Input Reading int a = Integer.parseInt(br.readLine()); float b = Float.parseFloat(br.readLine()); // Print above input values in console System.out.println(\"Integer value: \" + a); System.out.println(\"Float value: \" + b); // Space Separated Input Reading int[] arr = new int[5]; String[] strArr = br.readLine().split(\" \"); for (int i = 0; i < arr.length; i++) { arr[i] = Integer.parseInt(strArr[i]); } // Printing the elements in array // using toString() method System.out.println(Arrays.toString(arr)); }}",
"e": 28664,
"s": 27569,
"text": null
},
{
"code": null,
"e": 28672,
"s": 28664,
"text": "Output:"
},
{
"code": null,
"e": 28722,
"s": 28672,
"text": "Integer value: 4\nFloat value: 5.6\n[1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 28935,
"s": 28722,
"text": "The above example illustrates another common approach used to read the data while solving competitive programming problems. So is this enough? What if we can enhance it even more? Yes. It is possible. Stay tuned."
},
{
"code": null,
"e": 29019,
"s": 28935,
"text": "Method 3: Enhanced way for reading separated data using BufferedReader via Streams "
},
{
"code": null,
"e": 29427,
"s": 29019,
"text": "In the previous examples, we have seen while reading space-separated data we stored it first in a String array, and then we iterated over elements and then used java typecasting to convert it to the required data type. How about a single line of code making this possible? Yes. Java 8βs stream library provides a variety of functions to make it easy and optimized. Consider custom input as below as follows:"
},
{
"code": null,
"e": 29434,
"s": 29427,
"text": "Input:"
},
{
"code": null,
"e": 29475,
"s": 29434,
"text": "34 55 78 43 78 43 22\n94 67 96 32 79 6 33"
},
{
"code": null,
"e": 29483,
"s": 29475,
"text": "Example"
},
{
"code": null,
"e": 29488,
"s": 29483,
"text": "Java"
},
{
"code": "// Java Program to Read Separated Data// Using BufferedReader class voa enhanced for loopd // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; // Main classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Reading input separated by space BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // Storing in array int[] arr = Stream.of(br.readLine().split(\" \")) .mapToInt(Integer::parseInt) .toArray(); System.out.println(Arrays.toString(arr)); // Using streams concepts to parse map to integer // later on collecting via Collectors via toList() // method and storing it an integer list List<Integer> arrayList = Stream.of(br.readLine().split(\" \")) .mapToInt(Integer::parseInt) .boxed() .collect(Collectors.toList()); // Print the above List as created System.out.println(arrayList); }}",
"e": 30742,
"s": 29488,
"text": null
},
{
"code": null,
"e": 30750,
"s": 30742,
"text": "Output:"
},
{
"code": null,
"e": 30807,
"s": 30750,
"text": "[34, 55, 78, 43, 78, 43, 22]\n[94, 67, 96, 32, 79, 6, 33]"
},
{
"code": null,
"e": 31109,
"s": 30807,
"text": "The above example illustrates how we can read separated input and store it into the required data structure using a single line of code. Using java8 there might be a possibility that programmers are comfortable with List collection. Thatβs why it is covered. Now, let us understand code word by word. "
},
{
"code": null,
"e": 31133,
"s": 31109,
"text": "Storing into int array:"
},
{
"code": null,
"e": 31206,
"s": 31133,
"text": "1. java.util.stream.Stream.of() β Creates stream of string array passed"
},
{
"code": null,
"e": 31333,
"s": 31206,
"text": "2. br.readLine().split(β β) β Converts input string into string array based on separator value. (Blank Space β β β in example)"
},
{
"code": null,
"e": 31485,
"s": 31333,
"text": "3. mapToInt(Integer::parseInt) β Converts String element into the required data type using suitable mapper function (Integerβs parseInt() in example)"
},
{
"code": null,
"e": 31551,
"s": 31485,
"text": "4. toArray() β converts the stream of int elements into an array"
},
{
"code": null,
"e": 31585,
"s": 31551,
"text": "Storing into the List Collection:"
},
{
"code": null,
"e": 31657,
"s": 31585,
"text": "1. java.util.stream.Stream.of() β Creates stream of string array passed"
},
{
"code": null,
"e": 31784,
"s": 31657,
"text": "2. br.readLine().split(β β) β Converts input string into string array based on separator value. (Blank Space β β β in example)"
},
{
"code": null,
"e": 31936,
"s": 31784,
"text": "3. mapToInt(Integer::parseInt) β Converts String element into the required data type using suitable mapper function (Integerβs parseInt() in example)"
},
{
"code": null,
"e": 31986,
"s": 31936,
"text": "4. boxed() β boxes the stream to Integer elements"
},
{
"code": null,
"e": 32111,
"s": 31986,
"text": "5. collect(Collectors.toList()) β creates a collection of Integer elements and converts it to the java.util.List Collection."
},
{
"code": null,
"e": 32123,
"s": 32111,
"text": "kashishsoda"
},
{
"code": null,
"e": 32138,
"s": 32123,
"text": "varshagumber28"
},
{
"code": null,
"e": 32153,
"s": 32138,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 32160,
"s": 32153,
"text": "Java 8"
},
{
"code": null,
"e": 32170,
"s": 32160,
"text": "Blogathon"
},
{
"code": null,
"e": 32194,
"s": 32170,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32199,
"s": 32194,
"text": "Java"
},
{
"code": null,
"e": 32204,
"s": 32199,
"text": "Java"
},
{
"code": null,
"e": 32302,
"s": 32204,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32343,
"s": 32302,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 32400,
"s": 32343,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 32435,
"s": 32400,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 32473,
"s": 32435,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 32518,
"s": 32473,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 32561,
"s": 32518,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 32604,
"s": 32561,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 32645,
"s": 32604,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 32683,
"s": 32645,
"text": "Bits manipulation (Important tactics)"
}
]
|
Interactive Weather Data Visualizations with Plotly | by Will Norris | Towards Data Science | The Global Surface Summary of the Day (GSOD) is a weather data set from over 9,000 weather stations dating back to 1929. It was created and is maintained by the National Oceanic and Atmospheric Administration (NOAA) and generates a daily summary of hourly surface measurements for 18 climate variables like mean dew point, mean wind speed, and min/max temperate.
This is a great data set to use for practicing visualizing spatial data since it has many stations across the globe with a relatively large time series to play around with. It also is updated daily, which makes it a great candidate for practicing with dashboards.
While Python might not be the first language or tool that comes to mind for visualizing spatial data, there are several libraries that are capable of creating fantastic geographic visualizations. Plotly has become a very well rounded interactive plotting library for Python, and its geographic plotting capabilities have come a long way over the last few years. Because of its excellent documentation and popularity I will focus only on Plotly in this post, but keep in mind that there are other libraries available.
This data set is somewhat large at 4.2 GB so loading it into Python will take a little effort; it is not a massive data set by any means, but it is larger than the average βpracticeβ data set we encounter. We will start by walking through how to access the data and then explore visualizing the processed data on interactive maps with Plotly. Make a cup of coffee, get comfortable, and letβs work with a larger weather data set and visualize our findings with Plotly.
There are multiple ways to obtain this data set. An easy to download version of it is available from Kaggle, but it isnβt updated daily like the NOAA repositories and the Kaggle version is more difficult to format in Python. This is how the NOAA repository is structured:
1929.tar.gz/1930.tar.gz/ 03005099999.csv 03026099999.csv ......
The data is stored in yearly compressed tarballs that contain .csv files for each station active that year. Every .csv file is named after its station ID, which is made up of the stationβs WMO and WBAN numbers.
The World Meteorological Organization (WMO) is an agency of the United Nations responsible for weather, climate, and water resources. The first two digits are the country code, the next three digits are set by the National Meteorological Service (NMS). If the last number is a zero that means the WMO number is, or was in the past, official.
WBAN stands for Weather-Buereau-Army-Navy. The WBAN number is an identifier for digital data storage that started as a way for the US Weather Bureau, Canadaβs Transportation Department, and the three major military branches to share data with each other. It later expanded to include some German and Korean stations.
Note: The important piece to remember is that the WMO and WBAN numbers create a unique station ID that is our primary means of referencing each weather station once loaded into pandas.
The best way to get this data is directly from NOAA where you can download a tarball for each year that contain a csv file for each station active during that year. I have included a simple Python module for downloading and processing all of the data that you can find in the documentation section at the end.
To download the NOAA data I decided to make a simple scraping function using requests. It starts on the home directory of the data set and uses regex to find all of the years available from the text of the base URL page. With each year in a list it is easy to construct the final URLs and download each tarball. Remember that all of this code is available on Github and can be imported as a local module in Python.
The most important question to ask yourself when loading in large datasets is what data you want to have access to once it is loaded into a dataframe. There were over 11,000 stations in 2020, which means ~10 years of daily data would be quite a lot of information to work with. Instead you may want to do some aggregation. For this article I decided to aggregate the data by month and only save the daily data for one day of each year. Aggregating the data by month will greatly reduce the size of our final dataframe and still let us find trends over a decently long time series.
It may seem weird to keep one specific day un-aggregated, and it is! The real reason we want to save a single dayβs data is so that we can load in the most recent day to a live dashboard with Dash in a future post. For now it will still be useful for creating similar plots to what we will explore with Dash later.
Since processing this data is a little more involved than most practice datasets, I have included a GitHub repository with a local module that can be imported locally into your Python environment.
import gsodpy.gsodProcess as gsodimport gsodpy.gsodDownloader as gsodDownimport datetime
In order to import modules locally like this, the βgsodpyβ directory must be in your project directory.
The first thing we need to do is decide how many years to include and which day we will store un-aggregated. We can then use regex to create our desired file list.
num_years = 10target_day = datetime.datetime(2020,3,20)years, files = get_years_files(num_years)
Once we have defined our time series, we are ready to start cracking open tarballs and processing .csv files! Here are the functions I wrote to unpack our data.
To save you some time, here is the basic psuedo-code for this workflow:
- Loop through each tarball (years) - Loop through each csv file stored in tarball (stations) - Open .csv file for current station/year with pandas - Call process_df() to clean the dataframe - Append all data for this station on target_day to df_day - Aggregate data by month - Append monthly aggregate to df- Call add_meta() to create metadata column on df and df_day- Return completed df and df_day
Overall the process is not complex, and Iβm sure I could make this more concise given more time. Remember that with the large number of stations in each year it takes quite a while to load in all of this data.
We can go ahead and call our processing function to get our dataframes:
df, df_day = gsod.process_all_years(files, target_day)
Note: If you notice that your machine is struggling to process all of the data try starting with a short time series (2β3 years). If you want a longer time series you can also select a random sample of stations in the tarball to reduce the number of station files you need to process.
I highly recommend pickling your finished dataframes so that you can load them in much faster later.
import pandas as pd# Save DataFrames to pickle in current directorydf.to_pickle("df_monthly.pkl")df_day.to_pickle("df_daily.pkl")# Read them back in later:df = pd.read_pickle("df_monthly.pkl")df_day = pd.read_pickle("df_daily.pkl")
Now that we have some meaningful data loaded into Python we can get to the fun part and start making visualizations with Plotly!
If you use the free version of Plotly you are limited to uploads of 512kb. This isnβt a problem if you are making your plots locally. However, for me to share interactive plots here I need to use Plotlyβs Chart Studio to upload them to their cloud. This means I am limited to roughly 300 weather stations that I have chosen randomly with this function:
To start off, lets take a look at one month in our time series to see where some of our stations are on the map. This is about as basic of a map we can create with Plotly and this data; considering how little configuration it took, I think it looks pretty good.
Plotlyβs main data structure is the figure , which is an instance of the plotly.graph_objects.Figure class. The figure is rendered via Plotly.js using JavaScript, which is why we are able to access quality looking maps in Python.
I love plotting spatial data with Plotly because of its snappy and responsive interface that can be embedded almost anywhere. Quality base maps have always been difficult for me to find in Python packages, but Plotlyβs are great.
While this plot may be fine, there are absolutely several stylistic changes I would make to it. The coastlines are obtrusive and the color scale could use adjusting. Overall it could be altered to make our data points stand out more. Luckily all of these things are easily accomplished with Plotly!
One reason I chose to keep a single day of the data instead of only taking monthly aggregates was so that we could look at the warmest and coldest places on a given day.
First we need to find our extreme temperatures:
This plot uses the same structure as our first one, but I spend more time customizing the marker and figure properties. You will notice that I am able to pass a dictionary to certain parameters like marker to customize them further. In most cases, these parameters are objects that are being initialized by the information in the dictionary. For example, the marker parameter initializes a plotly.graph_objects.scattergeo.Marker object. While this increases complexity, you can see from the scattergeo.Marker documentation how much control this gives us over the markers on our plot.
I have always been a sucker for Mapbox. It has great base maps and is super responsive. Plotly has limited Mapbox integration that can enhance your geographical plots. Especially when zooming in you will notice a pleasing amount of detail in the base map compared to the base Plotly version. Mapbox has many effects on the way Plotly maps are rendered, so I will be covering Mapbox integration in an entire post.
One feature that I really like about Plotly is how easy it makes adding a slider to view how data changes over time. As an example, lets take a look at the average monthly temperatures in 2012.
You will notice that I am using a slightly different syntax to format this plot. This is technically the βoldβ method of plotting with Plotly. But for more complex plots like this it is nice to be able to format the data separately.
Creating this plot looks more complex than the others. But really the bulk of the code is simply restructuring data into monthly groupings for Plotly to easily send to its JavaScript library. If you have ever worked with json data, you will probably see how a lists of dictionaries can easily be converted to json.
Spatial data is never the easiest to work with in Python. It is multidimensional, often quite large, and normal 2d plotting spaces are not well suited to plotting geographical coordinates. Plotly removes a lot of the headache by providing easy to use functionality with quality base maps that I generally had to use javascript to access a couple years ago. When it comes to spatial plotting in Python, Ploty is generally my first choice.
There is so much more to learn with plotting spatial data with Plotly so donβt be afraid to sift through the documentation and examples online. The same developers also make Dash, which is a great tool for building live dashboards.
Github Repo for Processing GSOD Data
GSOD Data Repository (NOAA)
Kaggle GSOD Data | [
{
"code": null,
"e": 410,
"s": 47,
"text": "The Global Surface Summary of the Day (GSOD) is a weather data set from over 9,000 weather stations dating back to 1929. It was created and is maintained by the National Oceanic and Atmospheric Administration (NOAA) and generates a daily summary of hourly surface measurements for 18 climate variables like mean dew point, mean wind speed, and min/max temperate."
},
{
"code": null,
"e": 674,
"s": 410,
"text": "This is a great data set to use for practicing visualizing spatial data since it has many stations across the globe with a relatively large time series to play around with. It also is updated daily, which makes it a great candidate for practicing with dashboards."
},
{
"code": null,
"e": 1191,
"s": 674,
"text": "While Python might not be the first language or tool that comes to mind for visualizing spatial data, there are several libraries that are capable of creating fantastic geographic visualizations. Plotly has become a very well rounded interactive plotting library for Python, and its geographic plotting capabilities have come a long way over the last few years. Because of its excellent documentation and popularity I will focus only on Plotly in this post, but keep in mind that there are other libraries available."
},
{
"code": null,
"e": 1659,
"s": 1191,
"text": "This data set is somewhat large at 4.2 GB so loading it into Python will take a little effort; it is not a massive data set by any means, but it is larger than the average βpracticeβ data set we encounter. We will start by walking through how to access the data and then explore visualizing the processed data on interactive maps with Plotly. Make a cup of coffee, get comfortable, and letβs work with a larger weather data set and visualize our findings with Plotly."
},
{
"code": null,
"e": 1931,
"s": 1659,
"text": "There are multiple ways to obtain this data set. An easy to download version of it is available from Kaggle, but it isnβt updated daily like the NOAA repositories and the Kaggle version is more difficult to format in Python. This is how the NOAA repository is structured:"
},
{
"code": null,
"e": 2004,
"s": 1931,
"text": "1929.tar.gz/1930.tar.gz/ 03005099999.csv 03026099999.csv ......"
},
{
"code": null,
"e": 2215,
"s": 2004,
"text": "The data is stored in yearly compressed tarballs that contain .csv files for each station active that year. Every .csv file is named after its station ID, which is made up of the stationβs WMO and WBAN numbers."
},
{
"code": null,
"e": 2557,
"s": 2215,
"text": "The World Meteorological Organization (WMO) is an agency of the United Nations responsible for weather, climate, and water resources. The first two digits are the country code, the next three digits are set by the National Meteorological Service (NMS). If the last number is a zero that means the WMO number is, or was in the past, official."
},
{
"code": null,
"e": 2874,
"s": 2557,
"text": "WBAN stands for Weather-Buereau-Army-Navy. The WBAN number is an identifier for digital data storage that started as a way for the US Weather Bureau, Canadaβs Transportation Department, and the three major military branches to share data with each other. It later expanded to include some German and Korean stations."
},
{
"code": null,
"e": 3059,
"s": 2874,
"text": "Note: The important piece to remember is that the WMO and WBAN numbers create a unique station ID that is our primary means of referencing each weather station once loaded into pandas."
},
{
"code": null,
"e": 3369,
"s": 3059,
"text": "The best way to get this data is directly from NOAA where you can download a tarball for each year that contain a csv file for each station active during that year. I have included a simple Python module for downloading and processing all of the data that you can find in the documentation section at the end."
},
{
"code": null,
"e": 3784,
"s": 3369,
"text": "To download the NOAA data I decided to make a simple scraping function using requests. It starts on the home directory of the data set and uses regex to find all of the years available from the text of the base URL page. With each year in a list it is easy to construct the final URLs and download each tarball. Remember that all of this code is available on Github and can be imported as a local module in Python."
},
{
"code": null,
"e": 4365,
"s": 3784,
"text": "The most important question to ask yourself when loading in large datasets is what data you want to have access to once it is loaded into a dataframe. There were over 11,000 stations in 2020, which means ~10 years of daily data would be quite a lot of information to work with. Instead you may want to do some aggregation. For this article I decided to aggregate the data by month and only save the daily data for one day of each year. Aggregating the data by month will greatly reduce the size of our final dataframe and still let us find trends over a decently long time series."
},
{
"code": null,
"e": 4680,
"s": 4365,
"text": "It may seem weird to keep one specific day un-aggregated, and it is! The real reason we want to save a single dayβs data is so that we can load in the most recent day to a live dashboard with Dash in a future post. For now it will still be useful for creating similar plots to what we will explore with Dash later."
},
{
"code": null,
"e": 4877,
"s": 4680,
"text": "Since processing this data is a little more involved than most practice datasets, I have included a GitHub repository with a local module that can be imported locally into your Python environment."
},
{
"code": null,
"e": 4966,
"s": 4877,
"text": "import gsodpy.gsodProcess as gsodimport gsodpy.gsodDownloader as gsodDownimport datetime"
},
{
"code": null,
"e": 5070,
"s": 4966,
"text": "In order to import modules locally like this, the βgsodpyβ directory must be in your project directory."
},
{
"code": null,
"e": 5234,
"s": 5070,
"text": "The first thing we need to do is decide how many years to include and which day we will store un-aggregated. We can then use regex to create our desired file list."
},
{
"code": null,
"e": 5331,
"s": 5234,
"text": "num_years = 10target_day = datetime.datetime(2020,3,20)years, files = get_years_files(num_years)"
},
{
"code": null,
"e": 5492,
"s": 5331,
"text": "Once we have defined our time series, we are ready to start cracking open tarballs and processing .csv files! Here are the functions I wrote to unpack our data."
},
{
"code": null,
"e": 5564,
"s": 5492,
"text": "To save you some time, here is the basic psuedo-code for this workflow:"
},
{
"code": null,
"e": 6005,
"s": 5564,
"text": "- Loop through each tarball (years) - Loop through each csv file stored in tarball (stations) - Open .csv file for current station/year with pandas - Call process_df() to clean the dataframe - Append all data for this station on target_day to df_day - Aggregate data by month - Append monthly aggregate to df- Call add_meta() to create metadata column on df and df_day- Return completed df and df_day "
},
{
"code": null,
"e": 6215,
"s": 6005,
"text": "Overall the process is not complex, and Iβm sure I could make this more concise given more time. Remember that with the large number of stations in each year it takes quite a while to load in all of this data."
},
{
"code": null,
"e": 6287,
"s": 6215,
"text": "We can go ahead and call our processing function to get our dataframes:"
},
{
"code": null,
"e": 6342,
"s": 6287,
"text": "df, df_day = gsod.process_all_years(files, target_day)"
},
{
"code": null,
"e": 6627,
"s": 6342,
"text": "Note: If you notice that your machine is struggling to process all of the data try starting with a short time series (2β3 years). If you want a longer time series you can also select a random sample of stations in the tarball to reduce the number of station files you need to process."
},
{
"code": null,
"e": 6728,
"s": 6627,
"text": "I highly recommend pickling your finished dataframes so that you can load them in much faster later."
},
{
"code": null,
"e": 6960,
"s": 6728,
"text": "import pandas as pd# Save DataFrames to pickle in current directorydf.to_pickle(\"df_monthly.pkl\")df_day.to_pickle(\"df_daily.pkl\")# Read them back in later:df = pd.read_pickle(\"df_monthly.pkl\")df_day = pd.read_pickle(\"df_daily.pkl\")"
},
{
"code": null,
"e": 7089,
"s": 6960,
"text": "Now that we have some meaningful data loaded into Python we can get to the fun part and start making visualizations with Plotly!"
},
{
"code": null,
"e": 7442,
"s": 7089,
"text": "If you use the free version of Plotly you are limited to uploads of 512kb. This isnβt a problem if you are making your plots locally. However, for me to share interactive plots here I need to use Plotlyβs Chart Studio to upload them to their cloud. This means I am limited to roughly 300 weather stations that I have chosen randomly with this function:"
},
{
"code": null,
"e": 7704,
"s": 7442,
"text": "To start off, lets take a look at one month in our time series to see where some of our stations are on the map. This is about as basic of a map we can create with Plotly and this data; considering how little configuration it took, I think it looks pretty good."
},
{
"code": null,
"e": 7934,
"s": 7704,
"text": "Plotlyβs main data structure is the figure , which is an instance of the plotly.graph_objects.Figure class. The figure is rendered via Plotly.js using JavaScript, which is why we are able to access quality looking maps in Python."
},
{
"code": null,
"e": 8164,
"s": 7934,
"text": "I love plotting spatial data with Plotly because of its snappy and responsive interface that can be embedded almost anywhere. Quality base maps have always been difficult for me to find in Python packages, but Plotlyβs are great."
},
{
"code": null,
"e": 8463,
"s": 8164,
"text": "While this plot may be fine, there are absolutely several stylistic changes I would make to it. The coastlines are obtrusive and the color scale could use adjusting. Overall it could be altered to make our data points stand out more. Luckily all of these things are easily accomplished with Plotly!"
},
{
"code": null,
"e": 8633,
"s": 8463,
"text": "One reason I chose to keep a single day of the data instead of only taking monthly aggregates was so that we could look at the warmest and coldest places on a given day."
},
{
"code": null,
"e": 8681,
"s": 8633,
"text": "First we need to find our extreme temperatures:"
},
{
"code": null,
"e": 9265,
"s": 8681,
"text": "This plot uses the same structure as our first one, but I spend more time customizing the marker and figure properties. You will notice that I am able to pass a dictionary to certain parameters like marker to customize them further. In most cases, these parameters are objects that are being initialized by the information in the dictionary. For example, the marker parameter initializes a plotly.graph_objects.scattergeo.Marker object. While this increases complexity, you can see from the scattergeo.Marker documentation how much control this gives us over the markers on our plot."
},
{
"code": null,
"e": 9678,
"s": 9265,
"text": "I have always been a sucker for Mapbox. It has great base maps and is super responsive. Plotly has limited Mapbox integration that can enhance your geographical plots. Especially when zooming in you will notice a pleasing amount of detail in the base map compared to the base Plotly version. Mapbox has many effects on the way Plotly maps are rendered, so I will be covering Mapbox integration in an entire post."
},
{
"code": null,
"e": 9872,
"s": 9678,
"text": "One feature that I really like about Plotly is how easy it makes adding a slider to view how data changes over time. As an example, lets take a look at the average monthly temperatures in 2012."
},
{
"code": null,
"e": 10105,
"s": 9872,
"text": "You will notice that I am using a slightly different syntax to format this plot. This is technically the βoldβ method of plotting with Plotly. But for more complex plots like this it is nice to be able to format the data separately."
},
{
"code": null,
"e": 10420,
"s": 10105,
"text": "Creating this plot looks more complex than the others. But really the bulk of the code is simply restructuring data into monthly groupings for Plotly to easily send to its JavaScript library. If you have ever worked with json data, you will probably see how a lists of dictionaries can easily be converted to json."
},
{
"code": null,
"e": 10858,
"s": 10420,
"text": "Spatial data is never the easiest to work with in Python. It is multidimensional, often quite large, and normal 2d plotting spaces are not well suited to plotting geographical coordinates. Plotly removes a lot of the headache by providing easy to use functionality with quality base maps that I generally had to use javascript to access a couple years ago. When it comes to spatial plotting in Python, Ploty is generally my first choice."
},
{
"code": null,
"e": 11090,
"s": 10858,
"text": "There is so much more to learn with plotting spatial data with Plotly so donβt be afraid to sift through the documentation and examples online. The same developers also make Dash, which is a great tool for building live dashboards."
},
{
"code": null,
"e": 11127,
"s": 11090,
"text": "Github Repo for Processing GSOD Data"
},
{
"code": null,
"e": 11155,
"s": 11127,
"text": "GSOD Data Repository (NOAA)"
}
]
|
Django ModelFormSets - GeeksforGeeks | 09 Jan, 2020
ModelFormsets in a Django is an advanced way of handling multiple forms created using a model and use them to create model instances. In other words, ModelFormsets are a group of forms in Django. One might want to initialize multiple forms on a single page all of which may involve multiple POST requests, for example
class GeeksModel(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
Now if one wants to create a modelformset for this model, modelformset_factory needs to be used. A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid.
from django.forms import formset_factory
GeeksFormSet = modelformset_factory(GeeksModel)
Illustration of Rendering Django ModelFormsets manually using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
In your geeks app make a new file called models.py where you would be making all your models. To create a Django model you need to use Django Models. Letβs demonstrate how,In your models.py Enter the following,
# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title
Letβs explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A fieldβs syntax is denoted asSyntax :
Field_name = models.FieldType(attributes)
Now to create a simple formset of this form, move to views.py and create a formset_view as below.
from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset GeeksFormSet = modelformset_factory(GeeksForm) formset = GeeksFormSet() # Add the formset to context dictionary context['formset']= formset return render(request, "home.html", context)
To render the formset through HTML, create a html file βhome.htmlβ. Now letβs edit templates > home.html
<form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formset.as_p }} <input type="submit" value="Submit"></form>
All set to check if our formset is working or not letβs visit http://localhost:8000/.
Our modelformset is working completely. Letβs learn how to modify this formset to use extra features of this formset.
Django formsets are used to handle multiple instances of a form. One can create multiple forms easily using extra attribute of Django Formsets. In geeks/views.py,
from django.shortcuts import render # relative import of formsfrom .models import GeeksModel # importing formset_factoryfrom django.forms import modelformset_factory def modelformset_view(request): context ={} # creating a formset and 5 instances of GeeksForm GeeksFormSet = modelformset_factory(GeeksModel, fields =['title', 'description'], extra = 3) formset = GeeksFormSet() # Add the formset to context dictionary context['formset']= formset return render(request, "home.html", context)
The keyword argument extra makes multiple copies of same form. If one wants to create 5 forms enter extra = 5 and similarly for others. Visit http://localhost:8000/ to check if 5 forms are created.
Creating a form is much easier than handling the data entered into those fields at the back end. Letβs try to demonstrate how one can easily use the data of a model formset in a view. When trying to handle formset, Django formsets required one extra argument {{ formset.management_data }}. To know more about Management data, Understanding the ManagementForm.In templates/home.html,
<form method="POST" enctype="multipart/form-data"> <!-- Management data of formset --> {{ formset.management_data }} <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ formset.as_p }} <input type="submit" value="Submit"></form>
Now to check how and what type of data is being rendered edit formset_view to print the data. In geeks/view.py,
from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset and 5 instances of GeeksForm GeeksFormSet = formset_factory(GeeksForm, extra = 3) formset = GeeksFormSet(request.POST or None) # print formset data if it is valid if formset.is_valid(): for form in formset: print(form.cleaned_data) # Add the formset to context dictionary context['formset']= formset return render(request, "home.html", context)
Now letβs try to enter data in the formset through http://localhost:8000/
Hit submit and data will be saved in GeeksModel where server is running. One can use this data in any manner conveniently now.
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace() | [
{
"code": null,
"e": 41553,
"s": 41525,
"text": "\n09 Jan, 2020"
},
{
"code": null,
"e": 41871,
"s": 41553,
"text": "ModelFormsets in a Django is an advanced way of handling multiple forms created using a model and use them to create model instances. In other words, ModelFormsets are a group of forms in Django. One might want to initialize multiple forms on a single page all of which may involve multiple POST requests, for example"
},
{
"code": null,
"e": 41988,
"s": 41871,
"text": "class GeeksModel(models.Model):\n title = models.CharField(max_length = 200)\n description = models.TextField()\n"
},
{
"code": null,
"e": 42207,
"s": 41988,
"text": "Now if one wants to create a modelformset for this model, modelformset_factory needs to be used. A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid."
},
{
"code": null,
"e": 42297,
"s": 42207,
"text": "from django.forms import formset_factory\nGeeksFormSet = modelformset_factory(GeeksModel)\n"
},
{
"code": null,
"e": 42437,
"s": 42297,
"text": "Illustration of Rendering Django ModelFormsets manually using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 42524,
"s": 42437,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 42575,
"s": 42524,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 42608,
"s": 42575,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 42819,
"s": 42608,
"text": "In your geeks app make a new file called models.py where you would be making all your models. To create a Django model you need to use Django Models. Letβs demonstrate how,In your models.py Enter the following,"
},
{
"code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title",
"e": 43210,
"s": 42819,
"text": null
},
{
"code": null,
"e": 43420,
"s": 43210,
"text": "Letβs explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A fieldβs syntax is denoted asSyntax :"
},
{
"code": null,
"e": 43462,
"s": 43420,
"text": "Field_name = models.FieldType(attributes)"
},
{
"code": null,
"e": 43560,
"s": 43462,
"text": "Now to create a simple formset of this form, move to views.py and create a formset_view as below."
},
{
"code": "from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset GeeksFormSet = modelformset_factory(GeeksForm) formset = GeeksFormSet() # Add the formset to context dictionary context['formset']= formset return render(request, \"home.html\", context)",
"e": 43996,
"s": 43560,
"text": null
},
{
"code": null,
"e": 44101,
"s": 43996,
"text": "To render the formset through HTML, create a html file βhome.htmlβ. Now letβs edit templates > home.html"
},
{
"code": "<form method=\"POST\" enctype=\"multipart/form-data\"> {% csrf_token %} {{ formset.as_p }} <input type=\"submit\" value=\"Submit\"></form>",
"e": 44241,
"s": 44101,
"text": null
},
{
"code": null,
"e": 44327,
"s": 44241,
"text": "All set to check if our formset is working or not letβs visit http://localhost:8000/."
},
{
"code": null,
"e": 44445,
"s": 44327,
"text": "Our modelformset is working completely. Letβs learn how to modify this formset to use extra features of this formset."
},
{
"code": null,
"e": 44608,
"s": 44445,
"text": "Django formsets are used to handle multiple instances of a form. One can create multiple forms easily using extra attribute of Django Formsets. In geeks/views.py,"
},
{
"code": "from django.shortcuts import render # relative import of formsfrom .models import GeeksModel # importing formset_factoryfrom django.forms import modelformset_factory def modelformset_view(request): context ={} # creating a formset and 5 instances of GeeksForm GeeksFormSet = modelformset_factory(GeeksModel, fields =['title', 'description'], extra = 3) formset = GeeksFormSet() # Add the formset to context dictionary context['formset']= formset return render(request, \"home.html\", context)",
"e": 45141,
"s": 44608,
"text": null
},
{
"code": null,
"e": 45339,
"s": 45141,
"text": "The keyword argument extra makes multiple copies of same form. If one wants to create 5 forms enter extra = 5 and similarly for others. Visit http://localhost:8000/ to check if 5 forms are created."
},
{
"code": null,
"e": 45722,
"s": 45339,
"text": "Creating a form is much easier than handling the data entered into those fields at the back end. Letβs try to demonstrate how one can easily use the data of a model formset in a view. When trying to handle formset, Django formsets required one extra argument {{ formset.management_data }}. To know more about Management data, Understanding the ManagementForm.In templates/home.html,"
},
{
"code": "<form method=\"POST\" enctype=\"multipart/form-data\"> <!-- Management data of formset --> {{ formset.management_data }} <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ formset.as_p }} <input type=\"submit\" value=\"Submit\"></form>",
"e": 46007,
"s": 45722,
"text": null
},
{
"code": null,
"e": 46119,
"s": 46007,
"text": "Now to check how and what type of data is being rendered edit formset_view to print the data. In geeks/view.py,"
},
{
"code": "from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset and 5 instances of GeeksForm GeeksFormSet = formset_factory(GeeksForm, extra = 3) formset = GeeksFormSet(request.POST or None) # print formset data if it is valid if formset.is_valid(): for form in formset: print(form.cleaned_data) # Add the formset to context dictionary context['formset']= formset return render(request, \"home.html\", context)",
"e": 46753,
"s": 46119,
"text": null
},
{
"code": null,
"e": 46827,
"s": 46753,
"text": "Now letβs try to enter data in the formset through http://localhost:8000/"
},
{
"code": null,
"e": 46954,
"s": 46827,
"text": "Hit submit and data will be saved in GeeksModel where server is running. One can use this data in any manner conveniently now."
},
{
"code": null,
"e": 46967,
"s": 46954,
"text": "Django-forms"
},
{
"code": null,
"e": 46981,
"s": 46967,
"text": "Python Django"
},
{
"code": null,
"e": 46988,
"s": 46981,
"text": "Python"
},
{
"code": null,
"e": 47086,
"s": 46988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47114,
"s": 47086,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 47164,
"s": 47114,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 47186,
"s": 47164,
"text": "Python map() function"
},
{
"code": null,
"e": 47230,
"s": 47186,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 47265,
"s": 47230,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 47287,
"s": 47265,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 47319,
"s": 47287,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 47349,
"s": 47319,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 47391,
"s": 47349,
"text": "Different ways to create Pandas Dataframe"
}
]
|
Convert an integer to a hex string in C++ | In this program we will see how to convert an integer to hex string. To convert an integer into hexadecimal string we can follow mathematical steps. But in this case we have solved this problem using simple trick.
In C / C++ there is a format specifier %X. It prints the value of some variable into hexadecimal form. We have used this format specifier to convert number into a string by using sprintf() function.
Input: An integer number 255
Output: FF
Step 1:Take a number from the user
Step 2: Make a string after converting number using %X format specifier
Step 3: Print the result.
Step 4: End
Live Demo
#include<iostream>
using namespace std;
main() {
int n;
char hex_string[20];
cout << "Enter a number: ";
cin >> n;
sprintf(hex_string, "%X", n); //convert number to hex
cout << hex_string;
}
Enter a number: 250
FA | [
{
"code": null,
"e": 1276,
"s": 1062,
"text": "In this program we will see how to convert an integer to hex string. To convert an integer into hexadecimal string we can follow mathematical steps. But in this case we have solved this problem using simple trick."
},
{
"code": null,
"e": 1475,
"s": 1276,
"text": "In C / C++ there is a format specifier %X. It prints the value of some variable into hexadecimal form. We have used this format specifier to convert number into a string by using sprintf() function."
},
{
"code": null,
"e": 1515,
"s": 1475,
"text": "Input: An integer number 255\nOutput: FF"
},
{
"code": null,
"e": 1660,
"s": 1515,
"text": "Step 1:Take a number from the user\nStep 2: Make a string after converting number using %X format specifier\nStep 3: Print the result.\nStep 4: End"
},
{
"code": null,
"e": 1671,
"s": 1660,
"text": " Live Demo"
},
{
"code": null,
"e": 1880,
"s": 1671,
"text": "#include<iostream>\nusing namespace std;\nmain() {\n int n;\n char hex_string[20];\n cout << \"Enter a number: \";\n cin >> n;\n sprintf(hex_string, \"%X\", n); //convert number to hex\n cout << hex_string;\n}"
},
{
"code": null,
"e": 1903,
"s": 1880,
"text": "Enter a number: 250\nFA"
}
]
|
How to restart a remote system using PowerShell? | To restart the remote computer, you need to use the Restart-Computer command provided by the computer name. For example,
Restart-Computer -ComputerName Test1-Win2k12
The above command will restart computer Test1-Win2k12 automatically and if you have multiple remote computers to restart then you can provide multiple computers separated with comma (,).For example,
Restart-Computer -ComputerName Test1-Win2k12, Test2-Win2k12
Restart signal will be sent to both the computers at a time in the above example.
You can also use the Pipeline to restart remote computers. For example,
"Test1-Win2k12","Test2-Win2k12" | Restart-Computer -Verbose
OR
(Get-Content C:\Servers.txt) | Restart-Computer -Verbose
Few servers have dependencies on the other servers so main servers need to restart first. For
example, AD and Exchange servers. If you are giving both the servers in the same command line then
both servers will reboot at the same time and this is what we don't need it. To overcome this solution, you need to pass each server one at a time, write a few steps for server post-reboot checklist, and then move on to the next server. You can add servers to the array or text file and then pass a single value through foreach loop and the steps for the post-reboot checklist and move on to
the next server.
People often confuse with the - Wait parameter in the Restart-Computer cmdlet that - Wait parameter will reboot one server at a time after the server post-reboot checklist completes but - Wait parameter only performs the three major checklists like WinRM, WMI and PowerShell connectivity check on the remote computer for each computer specified in the cmdlet after server comes up but it can't hold the execution of servers reboot.
Restart-Computer shoots reboot command on all the computers and - Wait parameter does the checks on each computer the specified tests and even if the remote computer failed in checks, servers will reboot.
When anyone is logged on to the remote server(s), PowerShell failed to restart the remote server
and throws the below error message.
PS C:\Users\Administrator> Restart-Computer test1-win2k12 βVerbose
VERBOSE: Performing the operation "Enable the Remote shutdown access rights
and restart the computer." on target "test1-win2k12".
Restart-Computer : Failed to restart the computer test1-win2k12 with the
following error message:
The system shutdown cannot be initiated because there are other users logged
on to thecomputer.
At line:1 char:1+ Restart-Computer test1-win2k12 -Verbose+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (test1-win2k12:String) [Restart-
Computer], InvalidOperationException
+ FullyQualifiedErrorId :
RestartcomputerFailed,Microsoft.PowerShell.Commands.RestartComputerCommand
To restart the computer forcefully, you need to use -Force parameter.
Restart-Computer Test1-Win2k12 -Force | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "To restart the remote computer, you need to use the Restart-Computer command provided by the computer name. For example,"
},
{
"code": null,
"e": 1228,
"s": 1183,
"text": "Restart-Computer -ComputerName Test1-Win2k12"
},
{
"code": null,
"e": 1427,
"s": 1228,
"text": "The above command will restart computer Test1-Win2k12 automatically and if you have multiple remote computers to restart then you can provide multiple computers separated with comma (,).For example,"
},
{
"code": null,
"e": 1487,
"s": 1427,
"text": "Restart-Computer -ComputerName Test1-Win2k12, Test2-Win2k12"
},
{
"code": null,
"e": 1569,
"s": 1487,
"text": "Restart signal will be sent to both the computers at a time in the above example."
},
{
"code": null,
"e": 1641,
"s": 1569,
"text": "You can also use the Pipeline to restart remote computers. For example,"
},
{
"code": null,
"e": 1701,
"s": 1641,
"text": "\"Test1-Win2k12\",\"Test2-Win2k12\" | Restart-Computer -Verbose"
},
{
"code": null,
"e": 1704,
"s": 1701,
"text": "OR"
},
{
"code": null,
"e": 1762,
"s": 1704,
"text": "(Get-Content C:\\Servers.txt) | Restart-Computer -Verbose\n"
},
{
"code": null,
"e": 2364,
"s": 1762,
"text": "Few servers have dependencies on the other servers so main servers need to restart first. For\nexample, AD and Exchange servers. If you are giving both the servers in the same command line then\nboth servers will reboot at the same time and this is what we don't need it. To overcome this solution, you need to pass each server one at a time, write a few steps for server post-reboot checklist, and then move on to the next server. You can add servers to the array or text file and then pass a single value through foreach loop and the steps for the post-reboot checklist and move on to\nthe next server."
},
{
"code": null,
"e": 2796,
"s": 2364,
"text": "People often confuse with the - Wait parameter in the Restart-Computer cmdlet that - Wait parameter will reboot one server at a time after the server post-reboot checklist completes but - Wait parameter only performs the three major checklists like WinRM, WMI and PowerShell connectivity check on the remote computer for each computer specified in the cmdlet after server comes up but it can't hold the execution of servers reboot."
},
{
"code": null,
"e": 3001,
"s": 2796,
"text": "Restart-Computer shoots reboot command on all the computers and - Wait parameter does the checks on each computer the specified tests and even if the remote computer failed in checks, servers will reboot."
},
{
"code": null,
"e": 3134,
"s": 3001,
"text": "When anyone is logged on to the remote server(s), PowerShell failed to restart the remote server\nand throws the below error message."
},
{
"code": null,
"e": 3201,
"s": 3134,
"text": "PS C:\\Users\\Administrator> Restart-Computer test1-win2k12 βVerbose"
},
{
"code": null,
"e": 3830,
"s": 3201,
"text": "VERBOSE: Performing the operation \"Enable the Remote shutdown access rights\nand restart the computer.\" on target \"test1-win2k12\".\nRestart-Computer : Failed to restart the computer test1-win2k12 with the\nfollowing error message:\nThe system shutdown cannot be initiated because there are other users logged\non to thecomputer.\nAt line:1 char:1+ Restart-Computer test1-win2k12 -Verbose+\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+ CategoryInfo : OperationStopped: (test1-win2k12:String) [Restart-\nComputer], InvalidOperationException\n+ FullyQualifiedErrorId :\nRestartcomputerFailed,Microsoft.PowerShell.Commands.RestartComputerCommand"
},
{
"code": null,
"e": 3900,
"s": 3830,
"text": "To restart the computer forcefully, you need to use -Force parameter."
},
{
"code": null,
"e": 3938,
"s": 3900,
"text": "Restart-Computer Test1-Win2k12 -Force"
}
]
|
Android - Notifications | A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.
Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persistent which means alert flashes on the screen for a few seconds and then disappears.
To see the details of the notification, you will have to select the icon which will display notification drawer having detail about the notification. While working with emulator with virtual device, you will have to click and drag down the status bar to expand it which will give you detail as follows. This will be just 64 dp tall and called normal view.
Above expanded form can have a Big View which will have additional detail about the notification. You can add upto six additional lines in the notification. The following screen shot shows such notification.
You have simple way to create a notification. Follow the following steps in your application to create a notification β
As a first step is to create a notification builder using NotificationCompat.Builder.build(). You will use Notification Builder to set various Notification properties like its small and large icons, title, priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following β
A small icon, set by setSmallIcon()
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
A title, set by setContentTitle()
Detail text, set by setContentText()
Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
You have plenty of optional properties which you can set for your notification. To learn more about them, see the reference documentation for NotificationCompat.Builder.
This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to an Activity in your application, where they can look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method of NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().
A PendingIntent object helps you to perform an action on your applications behalf, often at a later time, without caring of whether or not your application is running.
We take help of stack builder object which will contain an artificial back stack for the started Activity. This ensures that navigating backward from the Activity leads out of your application to the Home screen.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());
The NotificationCompat.Builder class allows easier control over all the flags, as well as help constructing the typical notification layouts. Following are few important and most frequently used methods available as a part of NotificationCompat.Builder class.
Notification build()
Combine all of the options that have been set and return a new Notification object.
NotificationCompat.Builder setAutoCancel (boolean autoCancel)
Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel.
NotificationCompat.Builder setContent (RemoteViews views)
Supply a custom RemoteViews to use instead of the standard one.
NotificationCompat.Builder setContentInfo (CharSequence info)
Set the large text at the right-hand side of the notification.
NotificationCompat.Builder setContentIntent (PendingIntent intent)
Supply a PendingIntent to send when the notification is clicked.
NotificationCompat.Builder setContentText (CharSequence text)
Set the text (second row) of the notification, in a standard notification.
NotificationCompat.Builder setContentTitle (CharSequence title)
Set the text (first row) of the notification, in a standard notification.
NotificationCompat.Builder setDefaults (int defaults)
Set the default notification options that will be used.
NotificationCompat.Builder setLargeIcon (Bitmap icon)
Set the large icon that is shown in the ticker and notification.
NotificationCompat.Builder setNumber (int number)
Set the large number at the right-hand side of the notification.
NotificationCompat.Builder setOngoing (boolean ongoing)
Set whether this is an ongoing notification.
NotificationCompat.Builder setSmallIcon (int icon)
Set the small icon to use in the notification layouts.
NotificationCompat.Builder setStyle (NotificationCompat.Style style)
Add a rich notification style to be applied at build time.
NotificationCompat.Builder setTicker (CharSequence tickerText)
Set the text that is displayed in the status bar when the notification first arrives.
NotificationCompat.Builder setVibrate (long[] pattern)
Set the vibration pattern to use.
NotificationCompat.Builder setWhen (long when)
Set the time that the event occurred. Notifications in the panel are sorted by this time.
Following example shows the functionality of a Android notification using a NotificationCompat.Builder Class which has been introduced in Android 4.1.
Following is the content of the modified main activity file src/com.example.notificationdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.notificationdemo;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}
private void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
Following will be the content of res/layout/notification.xml file β
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="400dp"
android:text="Hi, Your Detailed notification view goes here...." />
</LinearLayout>
Following is the content of the modified main activity file src/com.example.notificationdemo/NotificationView.java.
package com.example.notificationdemo;
import android.os.Bundle;
import android.app.Activity;
public class NotificationView extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
}
}
Following will be the content of res/layout/activity_main.xml file β
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/button"
android:layout_marginTop="62dp"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants β
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="action_settings">Settings</string>
<string name="app_name">tutorialspoint </string>
</resources>
Following is the default content of AndroidManifest.xml β
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notificationdemo" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.notificationdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NotificationView"
android:label="Details of notification"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
</application>
</manifest>
Let's try to run your tutorialspoint application. I assume you had created your AVD while doing environment set-up. To run the APP from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window β
Now click button, you will see at the top a message "New Message Alert!" will display momentarily and after that you will have following screen having a small icon at the top left corner.
Now lets expand the view, long click on the small icon, after a second it will display date information and this is the time when you should drag status bar down without releasing mouse. You will see status bar will expand and you will get following screen β
The following code snippet demonstrates how to alter the notification created in the previous snippet to use the Inbox big view style. I'm going to update displayNotification() modification method to show this functionality β
protected void displayNotification() {
Log.i("Start", "notification");
/* Invoking the default notification service */
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.drawable.woman);
/* Increase notification number every time a new notification arrives */
mBuilder.setNumber(++numMessages);
/* Add Big View Specific Configuration */
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String[] events = new String[6];
events[0] = new String("This is first line....");
events[1] = new String("This is second line...");
events[2] = new String("This is third line...");
events[3] = new String("This is 4th line...");
events[4] = new String("This is 5th line...");
events[5] = new String("This is 6th line...");
// Sets a title for the Inbox style big view
inboxStyle.setBigContentTitle("Big Title Details:");
// Moves events into the big view
for (int i=0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}
mBuilder.setStyle(inboxStyle);
/* Creates an explicit intent for an Activity in your app */
Intent resultIntent = new Intent(this, NotificationView.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationView.class);
/* Adds the Intent that starts the Activity to the top of the stack */
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* notificationID allows you to update the notification later on. */
mNotificationManager.notify(notificationID, mBuilder.build());
}
Now if you will try to run your application then you will find following result in expanded form of the view β
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 4007,
"s": 3607,
"text": "A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time."
},
{
"code": null,
"e": 4201,
"s": 4007,
"text": "Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persistent which means alert flashes on the screen for a few seconds and then disappears."
},
{
"code": null,
"e": 4557,
"s": 4201,
"text": "To see the details of the notification, you will have to select the icon which will display notification drawer having detail about the notification. While working with emulator with virtual device, you will have to click and drag down the status bar to expand it which will give you detail as follows. This will be just 64 dp tall and called normal view."
},
{
"code": null,
"e": 4765,
"s": 4557,
"text": "Above expanded form can have a Big View which will have additional detail about the notification. You can add upto six additional lines in the notification. The following screen shot shows such notification."
},
{
"code": null,
"e": 4885,
"s": 4765,
"text": "You have simple way to create a notification. Follow the following steps in your application to create a notification β"
},
{
"code": null,
"e": 5105,
"s": 4885,
"text": "As a first step is to create a notification builder using NotificationCompat.Builder.build(). You will use Notification Builder to set various Notification properties like its small and large icons, title, priority etc."
},
{
"code": null,
"e": 5180,
"s": 5105,
"text": "NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)"
},
{
"code": null,
"e": 5346,
"s": 5180,
"text": "Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following β"
},
{
"code": null,
"e": 5382,
"s": 5346,
"text": "A small icon, set by setSmallIcon()"
},
{
"code": null,
"e": 5418,
"s": 5382,
"text": "A small icon, set by setSmallIcon()"
},
{
"code": null,
"e": 5452,
"s": 5418,
"text": "A title, set by setContentTitle()"
},
{
"code": null,
"e": 5486,
"s": 5452,
"text": "A title, set by setContentTitle()"
},
{
"code": null,
"e": 5523,
"s": 5486,
"text": "Detail text, set by setContentText()"
},
{
"code": null,
"e": 5560,
"s": 5523,
"text": "Detail text, set by setContentText()"
},
{
"code": null,
"e": 5741,
"s": 5560,
"text": "mBuilder.setSmallIcon(R.drawable.notification_icon);\nmBuilder.setContentTitle(\"Notification Alert, Click Me!\");\nmBuilder.setContentText(\"Hi, This is Android Notification Detail!\");"
},
{
"code": null,
"e": 5911,
"s": 5741,
"text": "You have plenty of optional properties which you can set for your notification. To learn more about them, see the reference documentation for NotificationCompat.Builder."
},
{
"code": null,
"e": 6162,
"s": 5911,
"text": "This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to an Activity in your application, where they can look at one or more events or do further work."
},
{
"code": null,
"e": 6546,
"s": 6162,
"text": "The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method of NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent()."
},
{
"code": null,
"e": 6714,
"s": 6546,
"text": "A PendingIntent object helps you to perform an action on your applications behalf, often at a later time, without caring of whether or not your application is running."
},
{
"code": null,
"e": 6927,
"s": 6714,
"text": "We take help of stack builder object which will contain an artificial back stack for the started Activity. This ensures that navigating backward from the Activity leads out of your application to the Home screen."
},
{
"code": null,
"e": 7367,
"s": 6927,
"text": "Intent resultIntent = new Intent(this, ResultActivity.class);\nTaskStackBuilder stackBuilder = TaskStackBuilder.create(this);\nstackBuilder.addParentStack(ResultActivity.class);\n\n// Adds the Intent that starts the Activity to the top of the stack\nstackBuilder.addNextIntent(resultIntent);\nPendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);\nmBuilder.setContentIntent(resultPendingIntent);\n"
},
{
"code": null,
"e": 7687,
"s": 7367,
"text": "Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object."
},
{
"code": null,
"e": 7934,
"s": 7687,
"text": "NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n \n// notificationID allows you to update the notification later on.\nmNotificationManager.notify(notificationID, mBuilder.build());"
},
{
"code": null,
"e": 8194,
"s": 7934,
"text": "The NotificationCompat.Builder class allows easier control over all the flags, as well as help constructing the typical notification layouts. Following are few important and most frequently used methods available as a part of NotificationCompat.Builder class."
},
{
"code": null,
"e": 8215,
"s": 8194,
"text": "Notification build()"
},
{
"code": null,
"e": 8299,
"s": 8215,
"text": "Combine all of the options that have been set and return a new Notification object."
},
{
"code": null,
"e": 8361,
"s": 8299,
"text": "NotificationCompat.Builder setAutoCancel (boolean autoCancel)"
},
{
"code": null,
"e": 8476,
"s": 8361,
"text": "Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel."
},
{
"code": null,
"e": 8534,
"s": 8476,
"text": "NotificationCompat.Builder setContent (RemoteViews views)"
},
{
"code": null,
"e": 8598,
"s": 8534,
"text": "Supply a custom RemoteViews to use instead of the standard one."
},
{
"code": null,
"e": 8660,
"s": 8598,
"text": "NotificationCompat.Builder setContentInfo (CharSequence info)"
},
{
"code": null,
"e": 8723,
"s": 8660,
"text": "Set the large text at the right-hand side of the notification."
},
{
"code": null,
"e": 8790,
"s": 8723,
"text": "NotificationCompat.Builder setContentIntent (PendingIntent intent)"
},
{
"code": null,
"e": 8855,
"s": 8790,
"text": "Supply a PendingIntent to send when the notification is clicked."
},
{
"code": null,
"e": 8917,
"s": 8855,
"text": "NotificationCompat.Builder setContentText (CharSequence text)"
},
{
"code": null,
"e": 8992,
"s": 8917,
"text": "Set the text (second row) of the notification, in a standard notification."
},
{
"code": null,
"e": 9056,
"s": 8992,
"text": "NotificationCompat.Builder setContentTitle (CharSequence title)"
},
{
"code": null,
"e": 9130,
"s": 9056,
"text": "Set the text (first row) of the notification, in a standard notification."
},
{
"code": null,
"e": 9184,
"s": 9130,
"text": "NotificationCompat.Builder setDefaults (int defaults)"
},
{
"code": null,
"e": 9240,
"s": 9184,
"text": "Set the default notification options that will be used."
},
{
"code": null,
"e": 9294,
"s": 9240,
"text": "NotificationCompat.Builder setLargeIcon (Bitmap icon)"
},
{
"code": null,
"e": 9359,
"s": 9294,
"text": "Set the large icon that is shown in the ticker and notification."
},
{
"code": null,
"e": 9409,
"s": 9359,
"text": "NotificationCompat.Builder setNumber (int number)"
},
{
"code": null,
"e": 9474,
"s": 9409,
"text": "Set the large number at the right-hand side of the notification."
},
{
"code": null,
"e": 9530,
"s": 9474,
"text": "NotificationCompat.Builder setOngoing (boolean ongoing)"
},
{
"code": null,
"e": 9575,
"s": 9530,
"text": "Set whether this is an ongoing notification."
},
{
"code": null,
"e": 9626,
"s": 9575,
"text": "NotificationCompat.Builder setSmallIcon (int icon)"
},
{
"code": null,
"e": 9681,
"s": 9626,
"text": "Set the small icon to use in the notification layouts."
},
{
"code": null,
"e": 9750,
"s": 9681,
"text": "NotificationCompat.Builder setStyle (NotificationCompat.Style style)"
},
{
"code": null,
"e": 9809,
"s": 9750,
"text": "Add a rich notification style to be applied at build time."
},
{
"code": null,
"e": 9872,
"s": 9809,
"text": "NotificationCompat.Builder setTicker (CharSequence tickerText)"
},
{
"code": null,
"e": 9958,
"s": 9872,
"text": "Set the text that is displayed in the status bar when the notification first arrives."
},
{
"code": null,
"e": 10013,
"s": 9958,
"text": "NotificationCompat.Builder setVibrate (long[] pattern)"
},
{
"code": null,
"e": 10047,
"s": 10013,
"text": "Set the vibration pattern to use."
},
{
"code": null,
"e": 10094,
"s": 10047,
"text": "NotificationCompat.Builder setWhen (long when)"
},
{
"code": null,
"e": 10184,
"s": 10094,
"text": "Set the time that the event occurred. Notifications in the panel are sorted by this time."
},
{
"code": null,
"e": 10335,
"s": 10184,
"text": "Following example shows the functionality of a Android notification using a NotificationCompat.Builder Class which has been introduced in Android 4.1."
},
{
"code": null,
"e": 10512,
"s": 10335,
"text": "Following is the content of the modified main activity file src/com.example.notificationdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods."
},
{
"code": null,
"e": 11999,
"s": 10512,
"text": "package com.example.notificationdemo;\n\nimport android.app.Activity;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.v4.app.NotificationCompat;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\n\npublic class MainActivity extends Activity {\n Button b1;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n b1 = (Button)findViewById(R.id.button);\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n addNotification();\n }\n });\n }\n\n private void addNotification() {\n NotificationCompat.Builder builder =\n new NotificationCompat.Builder(this)\n .setSmallIcon(R.drawable.abc)\n .setContentTitle(\"Notifications Example\")\n .setContentText(\"This is a test notification\");\n\n Intent notificationIntent = new Intent(this, MainActivity.class);\n PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,\n PendingIntent.FLAG_UPDATE_CURRENT);\n builder.setContentIntent(contentIntent);\n\n // Add as notification\n NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n manager.notify(0, builder.build());\n }\n}"
},
{
"code": null,
"e": 12067,
"s": 11999,
"text": "Following will be the content of res/layout/notification.xml file β"
},
{
"code": null,
"e": 12476,
"s": 12067,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\" >\n \n <TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"400dp\"\n android:text=\"Hi, Your Detailed notification view goes here....\" />\n</LinearLayout>"
},
{
"code": null,
"e": 12592,
"s": 12476,
"text": "Following is the content of the modified main activity file src/com.example.notificationdemo/NotificationView.java."
},
{
"code": null,
"e": 12894,
"s": 12592,
"text": "package com.example.notificationdemo;\n\nimport android.os.Bundle;\nimport android.app.Activity;\n\npublic class NotificationView extends Activity{\n @Override\n public void onCreate(Bundle savedInstanceState){\n super.onCreate(savedInstanceState);\n setContentView(R.layout.notification);\n }\n}"
},
{
"code": null,
"e": 12963,
"s": 12894,
"text": "Following will be the content of res/layout/activity_main.xml file β"
},
{
"code": null,
"e": 14739,
"s": 12963,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n tools:context=\"MainActivity\">\n \n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Notification Example\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\" />\n \n <TextView\n android:id=\"@+id/textView2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point \"\n android:textColor=\"#ff87ff09\"\n android:textSize=\"30dp\"\n android:layout_below=\"@+id/textView1\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"48dp\" />\n \n <ImageButton\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageButton\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView2\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"42dp\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Notification\"\n android:id=\"@+id/button\"\n android:layout_marginTop=\"62dp\"\n android:layout_below=\"@+id/imageButton\"\n android:layout_centerHorizontal=\"true\" />\n \n</RelativeLayout>"
},
{
"code": null,
"e": 14826,
"s": 14739,
"text": "Following will be the content of res/values/strings.xml to define two new constants β"
},
{
"code": null,
"e": 14996,
"s": 14826,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"action_settings\">Settings</string>\n <string name=\"app_name\">tutorialspoint </string> \n</resources>"
},
{
"code": null,
"e": 15055,
"s": 14996,
"text": "Following is the default content of AndroidManifest.xml β"
},
{
"code": null,
"e": 16075,
"s": 15055,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.notificationdemo\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.notificationdemo.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n <activity android:name=\".NotificationView\"\n android:label=\"Details of notification\"\n android:parentActivityName=\".MainActivity\">\n <meta-data\n android:name=\"android.support.PARENT_ACTIVITY\"\n android:value=\".MainActivity\"/>\n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 16468,
"s": 16075,
"text": "Let's try to run your tutorialspoint application. I assume you had created your AVD while doing environment set-up. To run the APP from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window β"
},
{
"code": null,
"e": 16656,
"s": 16468,
"text": "Now click button, you will see at the top a message \"New Message Alert!\" will display momentarily and after that you will have following screen having a small icon at the top left corner."
},
{
"code": null,
"e": 16915,
"s": 16656,
"text": "Now lets expand the view, long click on the small icon, after a second it will display date information and this is the time when you should drag status bar down without releasing mouse. You will see status bar will expand and you will get following screen β"
},
{
"code": null,
"e": 17141,
"s": 16915,
"text": "The following code snippet demonstrates how to alter the notification created in the previous snippet to use the Inbox big view style. I'm going to update displayNotification() modification method to show this functionality β"
},
{
"code": null,
"e": 19196,
"s": 17141,
"text": "protected void displayNotification() {\n Log.i(\"Start\", \"notification\");\n\n /* Invoking the default notification service */\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);\n \n mBuilder.setContentTitle(\"New Message\");\n mBuilder.setContentText(\"You've received new message.\");\n mBuilder.setTicker(\"New Message Alert!\");\n mBuilder.setSmallIcon(R.drawable.woman);\n \n /* Increase notification number every time a new notification arrives */\n mBuilder.setNumber(++numMessages);\n \n /* Add Big View Specific Configuration */\n NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();\n \n String[] events = new String[6];\n events[0] = new String(\"This is first line....\");\n events[1] = new String(\"This is second line...\");\n events[2] = new String(\"This is third line...\");\n events[3] = new String(\"This is 4th line...\");\n events[4] = new String(\"This is 5th line...\");\n events[5] = new String(\"This is 6th line...\");\n \n // Sets a title for the Inbox style big view\n inboxStyle.setBigContentTitle(\"Big Title Details:\");\n \n // Moves events into the big view\n for (int i=0; i < events.length; i++) {\n inboxStyle.addLine(events[i]);\n }\n \n mBuilder.setStyle(inboxStyle);\n \n /* Creates an explicit intent for an Activity in your app */\n Intent resultIntent = new Intent(this, NotificationView.class);\n \n TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);\n stackBuilder.addParentStack(NotificationView.class);\n\n /* Adds the Intent that starts the Activity to the top of the stack */\n stackBuilder.addNextIntent(resultIntent);\n PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);\n \n mBuilder.setContentIntent(resultPendingIntent);\n mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n \n /* notificationID allows you to update the notification later on. */\n mNotificationManager.notify(notificationID, mBuilder.build());\n}"
},
{
"code": null,
"e": 19307,
"s": 19196,
"text": "Now if you will try to run your application then you will find following result in expanded form of the view β"
},
{
"code": null,
"e": 19342,
"s": 19307,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 19354,
"s": 19342,
"text": " Aditya Dua"
},
{
"code": null,
"e": 19389,
"s": 19354,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 19403,
"s": 19389,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 19435,
"s": 19403,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 19452,
"s": 19435,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 19487,
"s": 19452,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 19504,
"s": 19487,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 19539,
"s": 19504,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 19556,
"s": 19539,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 19589,
"s": 19556,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 19606,
"s": 19589,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 19613,
"s": 19606,
"text": " Print"
},
{
"code": null,
"e": 19624,
"s": 19613,
"text": " Add Notes"
}
]
|
How to change the order of bars in bar chart in R? | This can be done by setting the levels of the variable in the order we want.
> data <- data.frame(Class=c("Highschool","Highschool","Graduate","Graduate",
"Graduate","Graduate","Masters","Masters","Masters","PhD"))
Setting the levels in decreasing order
> data <- within(data,
Class <- factor(Class,
levels=names(sort(table(Class),
decreasing=TRUE))))
> library(ggplot2)
> ggplot(data, aes(x = Class)) + geom_bar()
Setting the levels in increasing order
> data <- within(data,
Class <- factor(Class,
levels=names(sort(table(Class),
decreasing=TRUE))))
> ggplot(data, aes(x = Class)) + geom_bar() | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "This can be done by setting the levels of the variable in the order we want."
},
{
"code": null,
"e": 1277,
"s": 1139,
"text": "> data <- data.frame(Class=c(\"Highschool\",\"Highschool\",\"Graduate\",\"Graduate\",\n\"Graduate\",\"Graduate\",\"Masters\",\"Masters\",\"Masters\",\"PhD\"))"
},
{
"code": null,
"e": 1316,
"s": 1277,
"text": "Setting the levels in decreasing order"
},
{
"code": null,
"e": 1477,
"s": 1316,
"text": "> data <- within(data,\nClass <- factor(Class,\nlevels=names(sort(table(Class),\ndecreasing=TRUE))))\n> library(ggplot2)\n> ggplot(data, aes(x = Class)) + geom_bar()"
},
{
"code": null,
"e": 1516,
"s": 1477,
"text": "Setting the levels in increasing order"
},
{
"code": null,
"e": 1658,
"s": 1516,
"text": "> data <- within(data,\nClass <- factor(Class,\nlevels=names(sort(table(Class),\ndecreasing=TRUE))))\n> ggplot(data, aes(x = Class)) + geom_bar()"
}
]
|
String slicing in C# to rotate a string | Letβs say our string is β
var str = "welcome";
Use the substring() method and the following, if you want to rotate only some characters. Here, we are rotating only 2 characters β
var res = str.Substring(1, str.Length - 1) + str.Substring(0, 2);
The following is the complete code β
Live Demo
using System;
public class Program {
public static void Main() {
var str = "welcome";
Console.WriteLine("Original String = "+str);
var res = str.Substring(1, str.Length - 1) + str.Substring(0, 2);
Console.WriteLine("Rotating two characters in the String: "+res);
}
}
Original String = welcome
Rotating two characters in the String: elcomewe | [
{
"code": null,
"e": 1088,
"s": 1062,
"text": "Letβs say our string is β"
},
{
"code": null,
"e": 1109,
"s": 1088,
"text": "var str = \"welcome\";"
},
{
"code": null,
"e": 1241,
"s": 1109,
"text": "Use the substring() method and the following, if you want to rotate only some characters. Here, we are rotating only 2 characters β"
},
{
"code": null,
"e": 1307,
"s": 1241,
"text": "var res = str.Substring(1, str.Length - 1) + str.Substring(0, 2);"
},
{
"code": null,
"e": 1344,
"s": 1307,
"text": "The following is the complete code β"
},
{
"code": null,
"e": 1355,
"s": 1344,
"text": " Live Demo"
},
{
"code": null,
"e": 1655,
"s": 1355,
"text": "using System;\n\npublic class Program {\n public static void Main() {\n var str = \"welcome\";\n\n Console.WriteLine(\"Original String = \"+str);\n var res = str.Substring(1, str.Length - 1) + str.Substring(0, 2);\n\n Console.WriteLine(\"Rotating two characters in the String: \"+res);\n }\n}"
},
{
"code": null,
"e": 1729,
"s": 1655,
"text": "Original String = welcome\nRotating two characters in the String: elcomewe"
}
]
|
Ball tracking in volleyball with OpenCV and Tensorflow | by Constantin Toporov | Towards Data Science | After the first experience of applying AI in sport, I was inspired to continue. Home exercises are looked like an insignificant goal and I targeted team plays.
AI in sports is a pretty new thing. There are a few interesting works:
Basketball
Tennis
Volleyball
I am a big fan of playing volleyball, so letβs talk about the last reference. This a site of one Austrian institute who analyzes games of a local amateur league. There are some documents to read and even more important β open video dataset.
Volleyball is a complex game with many different aspects. So I started with a small but very important piece β the ball.
Ball tracking is a pretty famous task. Google gives a lot of links but many of them are just a demo. Obviously, recognize and track a big ball of distinguished color in front of a camera cannot be compared with real game ball detection, where the ball is tiny, moving fast and blended into the background.
And finally, we want to get something like that:
Before start letβs notice some detail about the video dataset:
the camera is static and located behind the court
skill level allows to see the ball freely (Professionals hit so hard that it is almost impossible to see the ball without TV replay)
The ball color, blue and yellow, does not contrast much with the floor, unfortunately. That makes all color-based approaches meaningless
So far most obvious approach β with colors β does not work, I used a fact the ball is moving.Then letβs find moving objects and pick the ball, sounds easy.
OpenCV contains tools to detect moving object with background removal:
mask = backSub.apply(frame) mask = cv.dilate(mask, None) mask = cv.GaussianBlur(mask, (15, 15),0) ret,mask = cv.threshold(mask,0,255,cv.THRESH_BINARY | cv.THRESH_OTSU)
And such picture:
Transformed into:
In this example, the ball is on top and human brain and eye can easily detect it. How did we decide? Some rules could be deduced from the picture:
the ball is a blob
it is the highest blob on the picture
The second rule does not work well. In this picture, for example, the highest blob is the refereeβs shoulder.
But highest-blob approach gives an initial data for further steps.
We can collect these blobs and train a classifier to distinguish the ball.
This dataset looks like that:
In terms of AI β it is a binary classification of color images, very similar to Cats-vs-Dogs challenge.
There are many ways to implement, but the most popular approach is with VGG neural network.
A problem β ball pictures are very small and multiple convolution layers do not fit there. So I had to cut VGG to a very simple architecture:
model = Sequential([Convolution2D(32,(3,3), activation='relu', input_shape=input_shape), MaxPooling2D(), Convolution2D(64,(3,3), activation='relu'), MaxPooling2D(), Flatten(), Dense(64, activation='relu'), Dropout(0.1), Dense(2, activation='softmax') ]) model.compile(loss="categorical_crossentropy", optimizer=SGD(lr=0.01), metrics=["accuracy"])
The model is simple and produces mediocre results: about 20% of false-positives and about 30% of false-negatives.That is better than nothing but, of course, not enough.
The model applied to the game generates many false balls:
There are actually two kinds of false balls:
they appear in random places in random time
the model consistently makes a mistake, recognizing something else as a ball
As the next step, there is an idea, the ball does not move randomly, but follows parabolic or linear trajectories.
Validation of blob movements on this geometry will cut off random and consistent mistakes.
There is an example of recorded trajectories during one ball play:
Where directed paths are in blue, static β in green, and random are grey.
Only blue trajectories are interesting. They consist of at least 3 points and have a direction. The direction is very important because the next point could be forecasted in case if it is missed in the real stream and no new paths detected.
This logic applied to the clip generates a pretty realistic tracking:
Github repo
Video source
Improved Sport Activity Recognition using Spatio-temporal ContextGeorg Waltner, Thomas Mauthner and Horst BischofIn Proc. DVS-Conference on Computer Science in Sport (DVS/GSSS), 2014
Indoor Activity Detection and Recognition for Automated Sport Games AnalysisGeorg Waltner, Thomas Mauthner and Horst BischofIn Proc. Workshop of the Austrian Association for Pattern Recognition (AAPR/OAGM), 2014 | [
{
"code": null,
"e": 332,
"s": 172,
"text": "After the first experience of applying AI in sport, I was inspired to continue. Home exercises are looked like an insignificant goal and I targeted team plays."
},
{
"code": null,
"e": 403,
"s": 332,
"text": "AI in sports is a pretty new thing. There are a few interesting works:"
},
{
"code": null,
"e": 414,
"s": 403,
"text": "Basketball"
},
{
"code": null,
"e": 421,
"s": 414,
"text": "Tennis"
},
{
"code": null,
"e": 432,
"s": 421,
"text": "Volleyball"
},
{
"code": null,
"e": 673,
"s": 432,
"text": "I am a big fan of playing volleyball, so letβs talk about the last reference. This a site of one Austrian institute who analyzes games of a local amateur league. There are some documents to read and even more important β open video dataset."
},
{
"code": null,
"e": 794,
"s": 673,
"text": "Volleyball is a complex game with many different aspects. So I started with a small but very important piece β the ball."
},
{
"code": null,
"e": 1100,
"s": 794,
"text": "Ball tracking is a pretty famous task. Google gives a lot of links but many of them are just a demo. Obviously, recognize and track a big ball of distinguished color in front of a camera cannot be compared with real game ball detection, where the ball is tiny, moving fast and blended into the background."
},
{
"code": null,
"e": 1149,
"s": 1100,
"text": "And finally, we want to get something like that:"
},
{
"code": null,
"e": 1212,
"s": 1149,
"text": "Before start letβs notice some detail about the video dataset:"
},
{
"code": null,
"e": 1262,
"s": 1212,
"text": "the camera is static and located behind the court"
},
{
"code": null,
"e": 1395,
"s": 1262,
"text": "skill level allows to see the ball freely (Professionals hit so hard that it is almost impossible to see the ball without TV replay)"
},
{
"code": null,
"e": 1532,
"s": 1395,
"text": "The ball color, blue and yellow, does not contrast much with the floor, unfortunately. That makes all color-based approaches meaningless"
},
{
"code": null,
"e": 1688,
"s": 1532,
"text": "So far most obvious approach β with colors β does not work, I used a fact the ball is moving.Then letβs find moving objects and pick the ball, sounds easy."
},
{
"code": null,
"e": 1759,
"s": 1688,
"text": "OpenCV contains tools to detect moving object with background removal:"
},
{
"code": null,
"e": 1939,
"s": 1759,
"text": "mask = backSub.apply(frame) mask = cv.dilate(mask, None) mask = cv.GaussianBlur(mask, (15, 15),0) ret,mask = cv.threshold(mask,0,255,cv.THRESH_BINARY | cv.THRESH_OTSU)"
},
{
"code": null,
"e": 1957,
"s": 1939,
"text": "And such picture:"
},
{
"code": null,
"e": 1975,
"s": 1957,
"text": "Transformed into:"
},
{
"code": null,
"e": 2122,
"s": 1975,
"text": "In this example, the ball is on top and human brain and eye can easily detect it. How did we decide? Some rules could be deduced from the picture:"
},
{
"code": null,
"e": 2141,
"s": 2122,
"text": "the ball is a blob"
},
{
"code": null,
"e": 2179,
"s": 2141,
"text": "it is the highest blob on the picture"
},
{
"code": null,
"e": 2289,
"s": 2179,
"text": "The second rule does not work well. In this picture, for example, the highest blob is the refereeβs shoulder."
},
{
"code": null,
"e": 2356,
"s": 2289,
"text": "But highest-blob approach gives an initial data for further steps."
},
{
"code": null,
"e": 2431,
"s": 2356,
"text": "We can collect these blobs and train a classifier to distinguish the ball."
},
{
"code": null,
"e": 2461,
"s": 2431,
"text": "This dataset looks like that:"
},
{
"code": null,
"e": 2565,
"s": 2461,
"text": "In terms of AI β it is a binary classification of color images, very similar to Cats-vs-Dogs challenge."
},
{
"code": null,
"e": 2657,
"s": 2565,
"text": "There are many ways to implement, but the most popular approach is with VGG neural network."
},
{
"code": null,
"e": 2799,
"s": 2657,
"text": "A problem β ball pictures are very small and multiple convolution layers do not fit there. So I had to cut VGG to a very simple architecture:"
},
{
"code": null,
"e": 3224,
"s": 2799,
"text": "model = Sequential([Convolution2D(32,(3,3), activation='relu', input_shape=input_shape), MaxPooling2D(), Convolution2D(64,(3,3), activation='relu'), MaxPooling2D(), Flatten(), Dense(64, activation='relu'), Dropout(0.1), Dense(2, activation='softmax') ]) model.compile(loss=\"categorical_crossentropy\", optimizer=SGD(lr=0.01), metrics=[\"accuracy\"])"
},
{
"code": null,
"e": 3393,
"s": 3224,
"text": "The model is simple and produces mediocre results: about 20% of false-positives and about 30% of false-negatives.That is better than nothing but, of course, not enough."
},
{
"code": null,
"e": 3451,
"s": 3393,
"text": "The model applied to the game generates many false balls:"
},
{
"code": null,
"e": 3496,
"s": 3451,
"text": "There are actually two kinds of false balls:"
},
{
"code": null,
"e": 3540,
"s": 3496,
"text": "they appear in random places in random time"
},
{
"code": null,
"e": 3617,
"s": 3540,
"text": "the model consistently makes a mistake, recognizing something else as a ball"
},
{
"code": null,
"e": 3732,
"s": 3617,
"text": "As the next step, there is an idea, the ball does not move randomly, but follows parabolic or linear trajectories."
},
{
"code": null,
"e": 3823,
"s": 3732,
"text": "Validation of blob movements on this geometry will cut off random and consistent mistakes."
},
{
"code": null,
"e": 3890,
"s": 3823,
"text": "There is an example of recorded trajectories during one ball play:"
},
{
"code": null,
"e": 3964,
"s": 3890,
"text": "Where directed paths are in blue, static β in green, and random are grey."
},
{
"code": null,
"e": 4205,
"s": 3964,
"text": "Only blue trajectories are interesting. They consist of at least 3 points and have a direction. The direction is very important because the next point could be forecasted in case if it is missed in the real stream and no new paths detected."
},
{
"code": null,
"e": 4275,
"s": 4205,
"text": "This logic applied to the clip generates a pretty realistic tracking:"
},
{
"code": null,
"e": 4287,
"s": 4275,
"text": "Github repo"
},
{
"code": null,
"e": 4300,
"s": 4287,
"text": "Video source"
},
{
"code": null,
"e": 4483,
"s": 4300,
"text": "Improved Sport Activity Recognition using Spatio-temporal ContextGeorg Waltner, Thomas Mauthner and Horst BischofIn Proc. DVS-Conference on Computer Science in Sport (DVS/GSSS), 2014"
}
]
|
Error Bar plots from a Data Frame using Matplotlib in Python | by Kalyan Keesara | Towards Data Science | I recently had to compare the performance of a few approaches/algorithms for a report and I chose error bars to summarize the results. If you have a similar task at hand, save yourself some time with this article.
Error bar charts are a great way to represent the variability in your data. In simpler words, they give an intuitive idea of how far the data could be from the reported value (or mean in most cases).
This could typically be done by using:
Standard Deviation
Confidence Interval (preferably 95)
If your report needs to make a comment on the precision (or reproducibility) of the displayed result, error bar charts are a must in my personal opinion. I have also come across a few reports using it to present tolerances in suitable cases.
But of course, be sure that you have the right audience that can interpret your fancy visualizations.
For the sake of simplicity, I have created a sample data using a random number generator on Excel. You can use mean() and std() functions to quickly calculate the mean and standard deviation of your data.
Import Matplotlib and use the errorbar() function from Matplotlib. It offers a fairly decent level of customization for the plot.
import pandas as pd ## for handling the dataframeimport matplotlib.pyplot as plt ## for visualizationdf = pd.read_excel("Sample_error_charts.xlsx")## read the Dataframe##Plotplt.errorbar( df['Model'], df['Mean'], yerr=df['SD'], fmt='o', color='Black', elinewidth=3,capthick=3,errorevery=1, alpha=1, ms=4, capsize = 5)plt.bar(df['Model'], df['Mean'],tick_label = df['Model'])##Bar plotplt.xlabel('Model') ## Label on X axisplt.ylabel('Average Performance') ##Label on Y axis
Make sure to tweak the capsize and thickness to suit your graph.
I have picked Standard deviation here in the example but you can use confidence Intervals or standard error as well, depending on what suits your overall narrative. Get yourself thoroughly acquainted with basic descriptive statistics and it would all make more sense immediately on what to pick. | [
{
"code": null,
"e": 386,
"s": 172,
"text": "I recently had to compare the performance of a few approaches/algorithms for a report and I chose error bars to summarize the results. If you have a similar task at hand, save yourself some time with this article."
},
{
"code": null,
"e": 586,
"s": 386,
"text": "Error bar charts are a great way to represent the variability in your data. In simpler words, they give an intuitive idea of how far the data could be from the reported value (or mean in most cases)."
},
{
"code": null,
"e": 625,
"s": 586,
"text": "This could typically be done by using:"
},
{
"code": null,
"e": 644,
"s": 625,
"text": "Standard Deviation"
},
{
"code": null,
"e": 680,
"s": 644,
"text": "Confidence Interval (preferably 95)"
},
{
"code": null,
"e": 922,
"s": 680,
"text": "If your report needs to make a comment on the precision (or reproducibility) of the displayed result, error bar charts are a must in my personal opinion. I have also come across a few reports using it to present tolerances in suitable cases."
},
{
"code": null,
"e": 1024,
"s": 922,
"text": "But of course, be sure that you have the right audience that can interpret your fancy visualizations."
},
{
"code": null,
"e": 1229,
"s": 1024,
"text": "For the sake of simplicity, I have created a sample data using a random number generator on Excel. You can use mean() and std() functions to quickly calculate the mean and standard deviation of your data."
},
{
"code": null,
"e": 1359,
"s": 1229,
"text": "Import Matplotlib and use the errorbar() function from Matplotlib. It offers a fairly decent level of customization for the plot."
},
{
"code": null,
"e": 1833,
"s": 1359,
"text": "import pandas as pd ## for handling the dataframeimport matplotlib.pyplot as plt ## for visualizationdf = pd.read_excel(\"Sample_error_charts.xlsx\")## read the Dataframe##Plotplt.errorbar( df['Model'], df['Mean'], yerr=df['SD'], fmt='o', color='Black', elinewidth=3,capthick=3,errorevery=1, alpha=1, ms=4, capsize = 5)plt.bar(df['Model'], df['Mean'],tick_label = df['Model'])##Bar plotplt.xlabel('Model') ## Label on X axisplt.ylabel('Average Performance') ##Label on Y axis"
},
{
"code": null,
"e": 1898,
"s": 1833,
"text": "Make sure to tweak the capsize and thickness to suit your graph."
}
]
|
How to write a function in JavaScript ? - GeeksforGeeks | 29 Sep, 2021
Introduction: A function is a collection of reusable code that may be invoked from anywhere in your application. This avoids the need to write the same code again and over. It aids programmers in the creation of modular code. Functions enable a programmer to break down a large program into several smaller and more manageable functions.
Functions are one of JavaScriptβs core building elements. In JavaScript, a function is comparable to a procedureβa series of words that performs a task or calculates a valueβbut for a process to qualify as a function, it must accept some input and produce an output with a clear link between the input and the result. To utilize a function, it must be defined in some place within the scope from which it will be called.
Function Definition: A function definition or function statement starts with the function keyword and continues with the following.
Functionβs name.
A list of function arguments contained in parenthesis and separated by commas.
Statements are enclosed in curly brackets.
Syntax:
function name(arguments)
{
javascript statements
}
Function Calling: To call a function at a later point in the script, simply type the functionβs name. By default, all JavaScript functions can utilize arguments objects. Each parameterβs value is stored in an arguments object. The arguments object is similar to an array. Its values may be accessed using an index, much like an array. It does not, however, provide array methods.
Javascript
<script type = "text/javascript"> function welcome() { console.log("welcome to GfG"); } // Function calling welcome();</script>
Output:
welcome to GFG
Function Arguments: A function can contain one or more arguments that are sent by the calling code and can be utilized within the function. Because JavaScript is a dynamically typed programming language, a function argument can have any data type as a value.
Javascript
<script type = "text/javascript"> function welcome(name) { console.log("Hey "+""+name+" "+"welcome to GfG"); } // Passing arguments welcome("Rohan");</script>
Output:
Hey Rohan welcome to GFG
Return Value: A return statement is an optional part of a JavaScript function. If you wish to return a value from a function, you must do this. This should be the final statement of a function.
Javascript
<script type = "text/javascript"> function welcome() { // Return statement return "Welcome to GfG"; } welcome();</script>
Output:
Welcome to GFG
Function Expression: We may assign a function to a variable and then utilize that variable as a function in JavaScript. It is known as a function expression.
Javascript
<script type = "text/javascript"> var welcome = function(){ return "Welcome to GfG"; } var gfg = welcome(); console.log(gfg);</script>
Output:
Welcome to GFG
Types of functions in JavaScript:
1. Named function: A named function is one that we write in code and then use whenever we need it by referencing its name and providing it some parameters. Named functions come in handy when we need to call a function several times to give various values to it or run it multiple times.
Javascript
<script type = "text/javascript"> function add(a, b){ return a+b ; } add(5, 4);</script>
Output:
9
2. Anonymous function: We can define a function in JavaScript without giving it a name. This nameless function is referred to as the anonymous function. A variable must be assigned to an anonymous function.
Javascript
<script type = "text/javascript"> var add = function(a, b){ return a + b; } add(5, 4);</script>
Output:
9
3. Nested Functions: A function in JavaScript can contain one or more inner functions. These nested functions fall within the purview of the outer function. The inner function has access to the variables and arguments of the outer function. However, variables declared within inner functions cannot be accessed by outer functions.
Javascript
<script type = "text/javascript"> function msg(firstName) { function hey() { console.log("Hey " + firstName); } return hey(); } msg("Ravi");</script>
Output:
Hey Ravi
4. Immediately invoked function expression: The browser executes the invoked function expression as soon as it detects it. This function has the advantage of running instantly where it is situated in the code and producing direct output. That is, it is unaffected by code that occurs later in the script and can be beneficial.
Javascript
<script type = "text/javascript"> let msg = (function() { return "Welcome to GfG" ; })(); msg;</script>
Output:
Welcome to GFG
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 25247,
"s": 24909,
"text": "Introduction: A function is a collection of reusable code that may be invoked from anywhere in your application. This avoids the need to write the same code again and over. It aids programmers in the creation of modular code. Functions enable a programmer to break down a large program into several smaller and more manageable functions."
},
{
"code": null,
"e": 25668,
"s": 25247,
"text": "Functions are one of JavaScriptβs core building elements. In JavaScript, a function is comparable to a procedureβa series of words that performs a task or calculates a valueβbut for a process to qualify as a function, it must accept some input and produce an output with a clear link between the input and the result. To utilize a function, it must be defined in some place within the scope from which it will be called."
},
{
"code": null,
"e": 25800,
"s": 25668,
"text": "Function Definition: A function definition or function statement starts with the function keyword and continues with the following."
},
{
"code": null,
"e": 25817,
"s": 25800,
"text": "Functionβs name."
},
{
"code": null,
"e": 25896,
"s": 25817,
"text": "A list of function arguments contained in parenthesis and separated by commas."
},
{
"code": null,
"e": 25939,
"s": 25896,
"text": "Statements are enclosed in curly brackets."
},
{
"code": null,
"e": 25947,
"s": 25939,
"text": "Syntax:"
},
{
"code": null,
"e": 26001,
"s": 25947,
"text": "function name(arguments)\n{\n javascript statements\n}"
},
{
"code": null,
"e": 26383,
"s": 26001,
"text": "Function Calling: To call a function at a later point in the script, simply type the functionβs name. By default, all JavaScript functions can utilize arguments objects. Each parameterβs value is stored in an arguments object. The arguments object is similar to an array. Its values may be accessed using an index, much like an array. It does not, however, provide array methods. "
},
{
"code": null,
"e": 26394,
"s": 26383,
"text": "Javascript"
},
{
"code": "<script type = \"text/javascript\"> function welcome() { console.log(\"welcome to GfG\"); } // Function calling welcome();</script>",
"e": 26531,
"s": 26394,
"text": null
},
{
"code": null,
"e": 26539,
"s": 26531,
"text": "Output:"
},
{
"code": null,
"e": 26554,
"s": 26539,
"text": "welcome to GFG"
},
{
"code": null,
"e": 26813,
"s": 26554,
"text": "Function Arguments: A function can contain one or more arguments that are sent by the calling code and can be utilized within the function. Because JavaScript is a dynamically typed programming language, a function argument can have any data type as a value."
},
{
"code": null,
"e": 26824,
"s": 26813,
"text": "Javascript"
},
{
"code": "<script type = \"text/javascript\"> function welcome(name) { console.log(\"Hey \"+\"\"+name+\" \"+\"welcome to GfG\"); } // Passing arguments welcome(\"Rohan\");</script>",
"e": 26993,
"s": 26824,
"text": null
},
{
"code": null,
"e": 27001,
"s": 26993,
"text": "Output:"
},
{
"code": null,
"e": 27026,
"s": 27001,
"text": "Hey Rohan welcome to GFG"
},
{
"code": null,
"e": 27220,
"s": 27026,
"text": "Return Value: A return statement is an optional part of a JavaScript function. If you wish to return a value from a function, you must do this. This should be the final statement of a function."
},
{
"code": null,
"e": 27231,
"s": 27220,
"text": "Javascript"
},
{
"code": "<script type = \"text/javascript\"> function welcome() { // Return statement return \"Welcome to GfG\"; } welcome();</script>",
"e": 27370,
"s": 27231,
"text": null
},
{
"code": null,
"e": 27378,
"s": 27370,
"text": "Output:"
},
{
"code": null,
"e": 27393,
"s": 27378,
"text": "Welcome to GFG"
},
{
"code": null,
"e": 27551,
"s": 27393,
"text": "Function Expression: We may assign a function to a variable and then utilize that variable as a function in JavaScript. It is known as a function expression."
},
{
"code": null,
"e": 27562,
"s": 27551,
"text": "Javascript"
},
{
"code": "<script type = \"text/javascript\"> var welcome = function(){ return \"Welcome to GfG\"; } var gfg = welcome(); console.log(gfg);</script>",
"e": 27708,
"s": 27562,
"text": null
},
{
"code": null,
"e": 27716,
"s": 27708,
"text": "Output:"
},
{
"code": null,
"e": 27731,
"s": 27716,
"text": "Welcome to GFG"
},
{
"code": null,
"e": 27765,
"s": 27731,
"text": "Types of functions in JavaScript:"
},
{
"code": null,
"e": 28052,
"s": 27765,
"text": "1. Named function: A named function is one that we write in code and then use whenever we need it by referencing its name and providing it some parameters. Named functions come in handy when we need to call a function several times to give various values to it or run it multiple times."
},
{
"code": null,
"e": 28063,
"s": 28052,
"text": "Javascript"
},
{
"code": "<script type = \"text/javascript\"> function add(a, b){ return a+b ; } add(5, 4);</script>",
"e": 28158,
"s": 28063,
"text": null
},
{
"code": null,
"e": 28166,
"s": 28158,
"text": "Output:"
},
{
"code": null,
"e": 28168,
"s": 28166,
"text": "9"
},
{
"code": null,
"e": 28375,
"s": 28168,
"text": "2. Anonymous function: We can define a function in JavaScript without giving it a name. This nameless function is referred to as the anonymous function. A variable must be assigned to an anonymous function."
},
{
"code": null,
"e": 28386,
"s": 28375,
"text": "Javascript"
},
{
"code": "<script type = \"text/javascript\"> var add = function(a, b){ return a + b; } add(5, 4);</script>",
"e": 28488,
"s": 28386,
"text": null
},
{
"code": null,
"e": 28496,
"s": 28488,
"text": "Output:"
},
{
"code": null,
"e": 28498,
"s": 28496,
"text": "9"
},
{
"code": null,
"e": 28829,
"s": 28498,
"text": "3. Nested Functions: A function in JavaScript can contain one or more inner functions. These nested functions fall within the purview of the outer function. The inner function has access to the variables and arguments of the outer function. However, variables declared within inner functions cannot be accessed by outer functions."
},
{
"code": null,
"e": 28840,
"s": 28829,
"text": "Javascript"
},
{
"code": "<script type = \"text/javascript\"> function msg(firstName) { function hey() { console.log(\"Hey \" + firstName); } return hey(); } msg(\"Ravi\");</script>",
"e": 29011,
"s": 28840,
"text": null
},
{
"code": null,
"e": 29019,
"s": 29011,
"text": "Output:"
},
{
"code": null,
"e": 29028,
"s": 29019,
"text": "Hey Ravi"
},
{
"code": null,
"e": 29355,
"s": 29028,
"text": "4. Immediately invoked function expression: The browser executes the invoked function expression as soon as it detects it. This function has the advantage of running instantly where it is situated in the code and producing direct output. That is, it is unaffected by code that occurs later in the script and can be beneficial."
},
{
"code": null,
"e": 29366,
"s": 29355,
"text": "Javascript"
},
{
"code": "<script type = \"text/javascript\"> let msg = (function() { return \"Welcome to GfG\" ; })(); msg;</script>",
"e": 29476,
"s": 29366,
"text": null
},
{
"code": null,
"e": 29484,
"s": 29476,
"text": "Output:"
},
{
"code": null,
"e": 29499,
"s": 29484,
"text": "Welcome to GFG"
},
{
"code": null,
"e": 29520,
"s": 29499,
"text": "javascript-functions"
},
{
"code": null,
"e": 29541,
"s": 29520,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 29548,
"s": 29541,
"text": "Picked"
},
{
"code": null,
"e": 29559,
"s": 29548,
"text": "JavaScript"
},
{
"code": null,
"e": 29576,
"s": 29559,
"text": "Web Technologies"
},
{
"code": null,
"e": 29674,
"s": 29576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29683,
"s": 29674,
"text": "Comments"
},
{
"code": null,
"e": 29696,
"s": 29683,
"text": "Old Comments"
},
{
"code": null,
"e": 29757,
"s": 29696,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29798,
"s": 29757,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29838,
"s": 29798,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29892,
"s": 29838,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29954,
"s": 29892,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 30010,
"s": 29954,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 30043,
"s": 30010,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30105,
"s": 30043,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30148,
"s": 30105,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
CSS - Inclusion | There are four ways to associate styles with your HTML document. Most commonly used methods are inline CSS and External CSS.
You can put your CSS rules into an HTML document using the <style> element. This tag is placed inside the <head>...</head> tags. Rules defined using this syntax will be applied to all the elements available in the document. Here is the generic syntax β
<!DOCTYPE html>
<html>
<head>
<style type = "text/css" media = "all">
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
It will produce the following result β
This is a paragraph.
Attributes associated with <style> elements are β
screen
tty
tv
projection
handheld
print
braille
aural
all
You can use style attribute of any HTML element to define style rules. These rules will be applied to that element only. Here is the generic syntax β
<element style = "...style rules....">
Following is the example of inline CSS based on the above syntax β
<html>
<head>
</head>
<body>
<h1 style = "color:#36C;">
This is inline CSS
</h1>
</body>
</html>
It will produce the following result β
The <link> element can be used to include an external stylesheet file in your HTML document.
An external style sheet is a separate text file with .css extension. You define all the Style rules within this text file and then you can include this file in any HTML document using <link> element.
Here is the generic syntax of including external CSS file β
<head>
<link type = "text/css" href = "..." media = "..." />
</head>
Attributes associated with <style> elements are β
screen
tty
tv
projection
handheld
print
braille
aural
all
Consider a simple style sheet file with a name mystyle.css having the following rules β
h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
Now you can include this file mystyle.css in any HTML document as follows β
<head>
<link type = "text/css" href = "mystyle.css" media = " all" />
</head>
@import is used to import an external stylesheet in a manner similar to the <link> element. Here is the generic syntax of @import rule.
<head>
@import "URL";
</head>
Here URL is the URL of the style sheet file having style rules. You can use another syntax as well β
<head>
@import url("URL");
</head>
Following is the example showing you how to import a style sheet file into HTML document β
<head>
@import "mystyle.css";
</head>
We have discussed four ways to include style sheet rules in a an HTML document. Here is the rule to override any Style Sheet Rule.
Any inline style sheet takes highest priority. So, it will override any rule defined in <style>...</style> tags or rules defined in any external style sheet file.
Any inline style sheet takes highest priority. So, it will override any rule defined in <style>...</style> tags or rules defined in any external style sheet file.
Any rule defined in <style>...</style> tags will override rules defined in any external style sheet file.
Any rule defined in <style>...</style> tags will override rules defined in any external style sheet file.
Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable.
Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable.
There are still many old browsers who do not support CSS. So, we should take care while writing our Embedded CSS in an HTML document. The following snippet shows how you can use comment tags to hide CSS from older browsers β
<style type = "text/css">
<!--
body, td {
color: blue;
}
-->
</style>
Many times, you may need to put additional comments in your style sheet blocks. So, it is very easy to comment any part in style sheet. You can simple put your comments inside /*.....this is a comment in style sheet.....*/.
You can use /* ....*/ to comment multi-line blocks in similar way you do in C and C++ programming languages.
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red;
/* This is a single-line comment */
text-align: center;
}
/* This is a multi-line comment */
</style>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
It will produce the following result β
Hello World!
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2751,
"s": 2626,
"text": "There are four ways to associate styles with your HTML document. Most commonly used methods are inline CSS and External CSS."
},
{
"code": null,
"e": 3004,
"s": 2751,
"text": "You can put your CSS rules into an HTML document using the <style> element. This tag is placed inside the <head>...</head> tags. Rules defined using this syntax will be applied to all the elements available in the document. Here is the generic syntax β"
},
{
"code": null,
"e": 3355,
"s": 3004,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style type = \"text/css\" media = \"all\">\n body {\n background-color: linen;\n }\n h1 {\n color: maroon;\n margin-left: 40px;\n }\n </style>\n </head> \n <body>\n <h1>This is a heading</h1>\n <p>This is a paragraph.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 3394,
"s": 3355,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 3415,
"s": 3394,
"text": "This is a paragraph."
},
{
"code": null,
"e": 3465,
"s": 3415,
"text": "Attributes associated with <style> elements are β"
},
{
"code": null,
"e": 3472,
"s": 3465,
"text": "screen"
},
{
"code": null,
"e": 3476,
"s": 3472,
"text": "tty"
},
{
"code": null,
"e": 3479,
"s": 3476,
"text": "tv"
},
{
"code": null,
"e": 3490,
"s": 3479,
"text": "projection"
},
{
"code": null,
"e": 3499,
"s": 3490,
"text": "handheld"
},
{
"code": null,
"e": 3505,
"s": 3499,
"text": "print"
},
{
"code": null,
"e": 3513,
"s": 3505,
"text": "braille"
},
{
"code": null,
"e": 3519,
"s": 3513,
"text": "aural"
},
{
"code": null,
"e": 3523,
"s": 3519,
"text": "all"
},
{
"code": null,
"e": 3673,
"s": 3523,
"text": "You can use style attribute of any HTML element to define style rules. These rules will be applied to that element only. Here is the generic syntax β"
},
{
"code": null,
"e": 3713,
"s": 3673,
"text": "<element style = \"...style rules....\">\n"
},
{
"code": null,
"e": 3780,
"s": 3713,
"text": "Following is the example of inline CSS based on the above syntax β"
},
{
"code": null,
"e": 3913,
"s": 3780,
"text": "<html>\n <head>\n </head>\n\n <body>\n <h1 style = \"color:#36C;\"> \n This is inline CSS \n </h1>\n </body>\n</html>"
},
{
"code": null,
"e": 3952,
"s": 3913,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 4045,
"s": 3952,
"text": "The <link> element can be used to include an external stylesheet file in your HTML document."
},
{
"code": null,
"e": 4245,
"s": 4045,
"text": "An external style sheet is a separate text file with .css extension. You define all the Style rules within this text file and then you can include this file in any HTML document using <link> element."
},
{
"code": null,
"e": 4305,
"s": 4245,
"text": "Here is the generic syntax of including external CSS file β"
},
{
"code": null,
"e": 4378,
"s": 4305,
"text": "<head>\n <link type = \"text/css\" href = \"...\" media = \"...\" />\n</head>\n"
},
{
"code": null,
"e": 4428,
"s": 4378,
"text": "Attributes associated with <style> elements are β"
},
{
"code": null,
"e": 4435,
"s": 4428,
"text": "screen"
},
{
"code": null,
"e": 4439,
"s": 4435,
"text": "tty"
},
{
"code": null,
"e": 4442,
"s": 4439,
"text": "tv"
},
{
"code": null,
"e": 4453,
"s": 4442,
"text": "projection"
},
{
"code": null,
"e": 4462,
"s": 4453,
"text": "handheld"
},
{
"code": null,
"e": 4468,
"s": 4462,
"text": "print"
},
{
"code": null,
"e": 4476,
"s": 4468,
"text": "braille"
},
{
"code": null,
"e": 4482,
"s": 4476,
"text": "aural"
},
{
"code": null,
"e": 4486,
"s": 4482,
"text": "all"
},
{
"code": null,
"e": 4574,
"s": 4486,
"text": "Consider a simple style sheet file with a name mystyle.css having the following rules β"
},
{
"code": null,
"e": 4707,
"s": 4574,
"text": "h1, h2, h3 {\n color: #36C;\n font-weight: normal;\n letter-spacing: .4em;\n margin-bottom: 1em;\n text-transform: lowercase;\n}"
},
{
"code": null,
"e": 4783,
"s": 4707,
"text": "Now you can include this file mystyle.css in any HTML document as follows β"
},
{
"code": null,
"e": 4864,
"s": 4783,
"text": "<head>\n <link type = \"text/css\" href = \"mystyle.css\" media = \" all\" />\n</head>"
},
{
"code": null,
"e": 5000,
"s": 4864,
"text": "@import is used to import an external stylesheet in a manner similar to the <link> element. Here is the generic syntax of @import rule."
},
{
"code": null,
"e": 5033,
"s": 5000,
"text": "<head>\n @import \"URL\";\n</head>"
},
{
"code": null,
"e": 5134,
"s": 5033,
"text": "Here URL is the URL of the style sheet file having style rules. You can use another syntax as well β"
},
{
"code": null,
"e": 5172,
"s": 5134,
"text": "<head>\n @import url(\"URL\");\n</head>"
},
{
"code": null,
"e": 5263,
"s": 5172,
"text": "Following is the example showing you how to import a style sheet file into HTML document β"
},
{
"code": null,
"e": 5305,
"s": 5263,
"text": "<head>\n @import \"mystyle.css\";\n</head>\n"
},
{
"code": null,
"e": 5436,
"s": 5305,
"text": "We have discussed four ways to include style sheet rules in a an HTML document. Here is the rule to override any Style Sheet Rule."
},
{
"code": null,
"e": 5599,
"s": 5436,
"text": "Any inline style sheet takes highest priority. So, it will override any rule defined in <style>...</style> tags or rules defined in any external style sheet file."
},
{
"code": null,
"e": 5762,
"s": 5599,
"text": "Any inline style sheet takes highest priority. So, it will override any rule defined in <style>...</style> tags or rules defined in any external style sheet file."
},
{
"code": null,
"e": 5868,
"s": 5762,
"text": "Any rule defined in <style>...</style> tags will override rules defined in any external style sheet file."
},
{
"code": null,
"e": 5974,
"s": 5868,
"text": "Any rule defined in <style>...</style> tags will override rules defined in any external style sheet file."
},
{
"code": null,
"e": 6136,
"s": 5974,
"text": "Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable."
},
{
"code": null,
"e": 6298,
"s": 6136,
"text": "Any rule defined in external style sheet file takes lowest priority, and rules defined in this file will be applied only when above two rules are not applicable."
},
{
"code": null,
"e": 6523,
"s": 6298,
"text": "There are still many old browsers who do not support CSS. So, we should take care while writing our Embedded CSS in an HTML document. The following snippet shows how you can use comment tags to hide CSS from older browsers β"
},
{
"code": null,
"e": 6620,
"s": 6523,
"text": "<style type = \"text/css\">\n <!--\n body, td {\n color: blue;\n }\n -->\n</style>"
},
{
"code": null,
"e": 6844,
"s": 6620,
"text": "Many times, you may need to put additional comments in your style sheet blocks. So, it is very easy to comment any part in style sheet. You can simple put your comments inside /*.....this is a comment in style sheet.....*/."
},
{
"code": null,
"e": 6953,
"s": 6844,
"text": "You can use /* ....*/ to comment multi-line blocks in similar way you do in C and C++ programming languages."
},
{
"code": null,
"e": 7254,
"s": 6953,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n p {\n color: red;\n /* This is a single-line comment */\n text-align: center;\n }\n /* This is a multi-line comment */\n </style>\n </head>\n\n <body>\n <p>Hello World!</p>\n </body>\n</html>"
},
{
"code": null,
"e": 7293,
"s": 7254,
"text": "It will produce the following result β"
},
{
"code": null,
"e": 7306,
"s": 7293,
"text": "Hello World!"
},
{
"code": null,
"e": 7341,
"s": 7306,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7355,
"s": 7341,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7390,
"s": 7355,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7407,
"s": 7390,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7442,
"s": 7407,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7473,
"s": 7442,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7508,
"s": 7473,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7539,
"s": 7508,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7574,
"s": 7539,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7605,
"s": 7574,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7638,
"s": 7605,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7669,
"s": 7638,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7676,
"s": 7669,
"text": " Print"
},
{
"code": null,
"e": 7687,
"s": 7676,
"text": " Add Notes"
}
]
|
How to get the first key name of a JavaScript object ? - GeeksforGeeks | 26 Jul, 2021
Given an object and the task is to get the first key of a JavaScript Object. Since JavaScript object does not contains numbered index so we use the following approaches to get the first key name of the object.
Approach 1:
First take the JavaScript Object in a variable.
Use object.keys(objectName) method to get access to all the keys of object.
Now, we can use indexing like Object.keys(objectName)[0] to get the key of first element of object.
Example: This example illustrate the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to get the first key name of a JavaScript object ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP1" style = "font-size: 15px; font-weight: bold;"> </p> <p id = "GFG_UP2" style = "font-size: 15px; font-weight: bold; color: green;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up1 = document.getElementById('GFG_UP1'); var up2 = document.getElementById('GFG_UP2'); var down = document.getElementById('GFG_DOWN'); var obj = { "Prop_1": ["Val_11", "Val_12", "Val_13"], "Prop_2": ["Val_21", "Val_22", "Val_23"], "Prop_3": ["Val_31", "Val_32", "Val_33"] }; up1.innerHTML = "Click on the button to get the "+ "first key of Object."; up2.innerHTML = JSON.stringify(obj); function GFG_Fun() { down.innerHTML = "The first key = '" + Object.keys(obj)[0] + "' <br> Value = '" + obj[Object.keys(obj)[0]] + "'"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
First take the JavaScript Object into a variable.
With the help of loop, start accessing the all keys of JavaScript Object.
After running it one time, break it. Then we will get the first key of Object.
Example: This example illustrate the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to get the first key name of a JavaScript object ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP1" style = "font-size: 15px; font-weight: bold;"> </p> <p id = "GFG_UP2" style = "font-size: 15px; font-weight: bold; color: green;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up1 = document.getElementById('GFG_UP1'); var up2 = document.getElementById('GFG_UP2'); var down = document.getElementById('GFG_DOWN'); var obj = { "Prop_1": ["Val_11", "Val_12", "Val_13"], "Prop_2": ["Val_21", "Val_22", "Val_23"], "Prop_3": ["Val_31", "Val_32", "Val_33"] }; up1.innerHTML = "Click on the button to get " + "the first key of Object."; up2.innerHTML = JSON.stringify(obj); function GFG_Fun() { var key; for (var k in obj) { key = k; break; } down.innerHTML = "The first key = '" + key + "' <br> Value = '" + obj[key] + "'"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
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?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 24722,
"s": 24694,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24932,
"s": 24722,
"text": "Given an object and the task is to get the first key of a JavaScript Object. Since JavaScript object does not contains numbered index so we use the following approaches to get the first key name of the object."
},
{
"code": null,
"e": 24944,
"s": 24932,
"text": "Approach 1:"
},
{
"code": null,
"e": 24992,
"s": 24944,
"text": "First take the JavaScript Object in a variable."
},
{
"code": null,
"e": 25068,
"s": 24992,
"text": "Use object.keys(objectName) method to get access to all the keys of object."
},
{
"code": null,
"e": 25168,
"s": 25068,
"text": "Now, we can use indexing like Object.keys(objectName)[0] to get the key of first element of object."
},
{
"code": null,
"e": 25221,
"s": 25168,
"text": "Example: This example illustrate the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to get the first key name of a JavaScript object ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP1\" style = \"font-size: 15px; font-weight: bold;\"> </p> <p id = \"GFG_UP2\" style = \"font-size: 15px; font-weight: bold; color: green;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up1 = document.getElementById('GFG_UP1'); var up2 = document.getElementById('GFG_UP2'); var down = document.getElementById('GFG_DOWN'); var obj = { \"Prop_1\": [\"Val_11\", \"Val_12\", \"Val_13\"], \"Prop_2\": [\"Val_21\", \"Val_22\", \"Val_23\"], \"Prop_3\": [\"Val_31\", \"Val_32\", \"Val_33\"] }; up1.innerHTML = \"Click on the button to get the \"+ \"first key of Object.\"; up2.innerHTML = JSON.stringify(obj); function GFG_Fun() { down.innerHTML = \"The first key = '\" + Object.keys(obj)[0] + \"' <br> Value = '\" + obj[Object.keys(obj)[0]] + \"'\"; } </script> </body> </html> ",
"e": 26635,
"s": 25221,
"text": null
},
{
"code": null,
"e": 26643,
"s": 26635,
"text": "Output:"
},
{
"code": null,
"e": 26674,
"s": 26643,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26704,
"s": 26674,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26716,
"s": 26704,
"text": "Approach 2:"
},
{
"code": null,
"e": 26766,
"s": 26716,
"text": "First take the JavaScript Object into a variable."
},
{
"code": null,
"e": 26840,
"s": 26766,
"text": "With the help of loop, start accessing the all keys of JavaScript Object."
},
{
"code": null,
"e": 26919,
"s": 26840,
"text": "After running it one time, break it. Then we will get the first key of Object."
},
{
"code": null,
"e": 26972,
"s": 26919,
"text": "Example: This example illustrate the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to get the first key name of a JavaScript object ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP1\" style = \"font-size: 15px; font-weight: bold;\"> </p> <p id = \"GFG_UP2\" style = \"font-size: 15px; font-weight: bold; color: green;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up1 = document.getElementById('GFG_UP1'); var up2 = document.getElementById('GFG_UP2'); var down = document.getElementById('GFG_DOWN'); var obj = { \"Prop_1\": [\"Val_11\", \"Val_12\", \"Val_13\"], \"Prop_2\": [\"Val_21\", \"Val_22\", \"Val_23\"], \"Prop_3\": [\"Val_31\", \"Val_32\", \"Val_33\"] }; up1.innerHTML = \"Click on the button to get \" + \"the first key of Object.\"; up2.innerHTML = JSON.stringify(obj); function GFG_Fun() { var key; for (var k in obj) { key = k; break; } down.innerHTML = \"The first key = '\" + key + \"' <br> Value = '\" + obj[key] + \"'\"; } </script> </body> </html>",
"e": 28478,
"s": 26972,
"text": null
},
{
"code": null,
"e": 28486,
"s": 28478,
"text": "Output:"
},
{
"code": null,
"e": 28517,
"s": 28486,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28547,
"s": 28517,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28766,
"s": 28547,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 28782,
"s": 28766,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28793,
"s": 28782,
"text": "JavaScript"
},
{
"code": null,
"e": 28810,
"s": 28793,
"text": "Web Technologies"
},
{
"code": null,
"e": 28837,
"s": 28810,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28935,
"s": 28837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28980,
"s": 28935,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29041,
"s": 28980,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29113,
"s": 29041,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29165,
"s": 29113,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29211,
"s": 29165,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29253,
"s": 29211,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29286,
"s": 29253,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29329,
"s": 29286,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29379,
"s": 29329,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
How to sort an ArrayList in Descending Order in Java | To sort an ArrayList, you need to use the Collections.sort() method. This sorts in ascending order, but if you want to sort the ArrayList in descending order, use the Collections.reverseOrder() method as well. This gets included as a parameter β
Collections.sort(myList, Collections.reverseOrder());
Following is the code to sort an ArrayList in descending order in Java β
Live Demo
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
public static void main(String args[]) {
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(30);
myList.add(99);
myList.add(12);
myList.add(23);
myList.add(8);
myList.add(94);
myList.add(78);
myList.add(87);
System.out.println("Points\n"+ myList);
Collections.sort(myList,Collections.reverseOrder());
System.out.println("Points (descending order)\n"+ myList);
}
}
Points
[30, 99, 12, 23, 8, 94, 78, 87]
Points (descending order)
[99, 94, 87, 78, 30, 23, 12, 8]
Let us see another example wherein we will sort string values in descending order β
Live Demo
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
public static void main(String args[]) {
ArrayList<String> myList = new ArrayList<String>();
myList.add("Jack");
myList.add("Katie");
myList.add("Amy");
myList.add("Tom");
myList.add("David");
myList.add("Arnold");
myList.add("Steve");
myList.add("Tim");
System.out.println("Names\n"+ myList);
Collections.sort(myList,Collections.reverseOrder());
System.out.println("Names (descending order)\n"+ myList);
}
}
Names
[Jack, Katie, Amy, Tom, David, Arnold, Steve, Tim]
Names (descending order)
[Tom, Tim, Steve, Katie, Jack, David, Arnold, Amy] | [
{
"code": null,
"e": 1308,
"s": 1062,
"text": "To sort an ArrayList, you need to use the Collections.sort() method. This sorts in ascending order, but if you want to sort the ArrayList in descending order, use the Collections.reverseOrder() method as well. This gets included as a parameter β"
},
{
"code": null,
"e": 1362,
"s": 1308,
"text": "Collections.sort(myList, Collections.reverseOrder());"
},
{
"code": null,
"e": 1435,
"s": 1362,
"text": "Following is the code to sort an ArrayList in descending order in Java β"
},
{
"code": null,
"e": 1446,
"s": 1435,
"text": " Live Demo"
},
{
"code": null,
"e": 1980,
"s": 1446,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\npublic class Demo {\n public static void main(String args[]) {\n ArrayList<Integer> myList = new ArrayList<Integer>();\n myList.add(30);\n myList.add(99);\n myList.add(12);\n myList.add(23);\n myList.add(8);\n myList.add(94);\n myList.add(78);\n myList.add(87);\n System.out.println(\"Points\\n\"+ myList);\n Collections.sort(myList,Collections.reverseOrder());\n System.out.println(\"Points (descending order)\\n\"+ myList);\n }\n}"
},
{
"code": null,
"e": 2077,
"s": 1980,
"text": "Points\n[30, 99, 12, 23, 8, 94, 78, 87]\nPoints (descending order)\n[99, 94, 87, 78, 30, 23, 12, 8]"
},
{
"code": null,
"e": 2161,
"s": 2077,
"text": "Let us see another example wherein we will sort string values in descending order β"
},
{
"code": null,
"e": 2172,
"s": 2161,
"text": " Live Demo"
},
{
"code": null,
"e": 2737,
"s": 2172,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\npublic class Demo {\n public static void main(String args[]) {\n ArrayList<String> myList = new ArrayList<String>();\n myList.add(\"Jack\");\n myList.add(\"Katie\");\n myList.add(\"Amy\");\n myList.add(\"Tom\");\n myList.add(\"David\");\n myList.add(\"Arnold\");\n myList.add(\"Steve\");\n myList.add(\"Tim\");\n System.out.println(\"Names\\n\"+ myList);\n Collections.sort(myList,Collections.reverseOrder());\n System.out.println(\"Names (descending order)\\n\"+ myList);\n }\n}"
},
{
"code": null,
"e": 2870,
"s": 2737,
"text": "Names\n[Jack, Katie, Amy, Tom, David, Arnold, Steve, Tim]\nNames (descending order)\n[Tom, Tim, Steve, Katie, Jack, David, Arnold, Amy]"
}
]
|
Andrew Ngβs Machine Learning Course in Python (Logistic Regression) | by Benjamin Lau | Towards Data Science | Continuing from the series, this will be python implementation of Andrew Ngβs Machine Learning Course on Logistic Regression.
Logistic regression is used in classification problems where the labels are a discrete number of classes as compared to linear regression, where labels are continuous variables.
Same as usual, we start with importing of libraries and the dataset. This dataset contains 2 different test score of students and their status of admission into the university. We are asked to predict if a student gets admitted into a university based on their test scores.
import numpy as npimport matplotlib.pyplot as pltimport pandas as pddf=pd.read_csv("ex2data1.txt",header=None)
Making sense of the data
df.head()df.describe()
Plotting of the data
pos , neg = (y==1).reshape(100,1) , (y==0).reshape(100,1)plt.scatter(X[pos[:,0],0],X[pos[:,0],1],c="r",marker="+")plt.scatter(X[neg[:,0],0],X[neg[:,0],1],marker="o",s=10)plt.xlabel("Exam 1 score")plt.ylabel("Exam 2 score")plt.legend(["Admitted","Not admitted"],loc=0)
As this is not the standard scatter or line plot, I will break down the code step by step for easy understanding. For classification problem, we plot the independent variables against each other and identify the different classes to observe their relationship. As such, we need to differentiate the combination of x1 and x2 that led to an university admission and the combination that donβt. The variables pos and neg did just that. By plotting combination of x1 and x2 that was admitted into university with different color and marker as those that donβt get admitted, we successfully visualize the relationship.
Students with higher test score for both exam were admitted into the university as expected.
Now the sigmoid function that differentiates logistic regression from linear regression
def sigmoid(z): """ return the sigmoid of z """ return 1/ (1 + np.exp(-z))# testing the sigmoid functionsigmoid(0)
Running the sigmoid(0) function return 0.5
To compute the cost function J(Ξ) and gradient (partial derivative of J(Ξ) with respect to each Ξ)
def costFunction(theta, X, y): """ Takes in numpy array theta, x and y and return the logistic regression cost function and gradient """ m=len(y) predictions = sigmoid(np.dot(X,theta)) error = (-y * np.log(predictions)) - ((1-y)*np.log(1-predictions))cost = 1/m * sum(error) grad = 1/m * np.dot(X.transpose(),(predictions - y)) return cost[0] , grad
Setting the initial_theta and test the cost function
m , n = X.shape[0], X.shape[1]X= np.append(np.ones((m,1)),X,axis=1)y=y.reshape(m,1)initial_theta = np.zeros((n+1,1))cost, grad= costFunction(initial_theta,X,y)print("Cost of initial theta is",cost)print("Gradient at initial theta (zeros):",grad)
The print statement will print: Cost of initial theta is 0.693147180559946 Gradient at initial theta (zeros): [-0.1],[-12.00921659],[-11.26284221]
Now for the optimizing algorithm. In the assignment itself, we were told to make use of the fminunc function in Octave to finds the minimum of an unconstrained function. As for python implementation, a library is available that serves similar purpose. You can find the official documentation here. There are various optimization method to choose from and many others before me had used these methods for their python implementation. Here, I decided to use gradient descent to do the optimization and compare the result with fminunc in Octave.
Before doing gradient descent, never forget to do feature scaling for a multivariate problem.
def featureNormalization(X): """ Take in numpy array of X values and return normalize X values, the mean and standard deviation of each feature """ mean=np.mean(X,axis=0) std=np.std(X,axis=0) X_norm = (X - mean)/std return X_norm , mean , std
As mentioned in the lecture, the gradient descent algorithm is very similar to linear regression. The only difference is that the hypothesis h(x) is now g(Ξ^Tx) where g is the sigmoid function.
def gradientDescent(X,y,theta,alpha,num_iters): """ Take in numpy array X, y and theta and update theta by taking num_iters gradient steps with learning rate of alpha return theta and the list of the cost of theta during each iteration """ m=len(y) J_history =[] for i in range(num_iters): cost, grad = costFunction(theta,X,y) theta = theta - (alpha * grad) J_history.append(cost) return theta , J_history
I always like the saying of DRY (Donβt Repeat Yourself) in coding. Since we already have a function for computing the gradient previously, letβs not repeat the calculation and add on an alpha term here to update Ξ.
As the assignment did not implement gradient descent, I had to test a few alpha and num_iters values to find the optimal values.
Using alpha=0.01, num_iters=400 ,
The gradient descent works in reducing the cost function at every iteration, but we can do better. With alpha = 0.1, num_iters =400 ,
Much better, but I will try another value just to make sure. With alpha=1, num_iters=400 ,
The drop is sharper and cost function plateau around the 150 iterations. Using this alpha and num_iters values, the optimized theta is [1.65947664],[3.8670477],[3.60347302] and the resulting cost is 0.20360044248226664 . A significant improvement from the initial 0.693147180559946 . When compared to the optimized cost function using fminunc in Octave, it is not that far off from 0.203498 obtained in the assignment.
Next is the plotting of the decision boundary using the optimized theta. There is a step by step explanation within the courseβs resource on how to plot the decision boundary. The link can be found here.
plt.scatter(X[pos[:,0],1],X[pos[:,0],2],c="r",marker="+",label="Admitted")plt.scatter(X[neg[:,0],1],X[neg[:,0],2],c="b",marker="x",label="Not admitted")x_value= np.array([np.min(X[:,1]),np.max(X[:,1])])y_value=-(theta[0] +theta[1]*x_value)/theta[2]plt.plot(x_value,y_value, "r")plt.xlabel("Exam 1 score")plt.ylabel("Exam 2 score")plt.legend(loc=0)
Making predictions using optimized theta
x_test = np.array([45,85])x_test = (x_test - X_mean)/X_stdx_test = np.append(np.ones(1),x_test)prob = sigmoid(x_test.dot(theta))print("For a student with scores 45 and 85, we predict an admission probability of",prob[0])
The print statement will print: For a student with scores 45 and 85, we predict an admission probability of 0.7677628875792492 . A close approximation to 0.776291 using fminunc .
To find the accuracy of the classifier, we compute the percentage of correct classification on our training set.
def classifierPredict(theta,X): """ take in numpy array of theta and X and predict the class """ predictions = X.dot(theta) return predictions>0p=classifierPredict(theta,X)print("Train Accuracy:", sum(p==y)[0],"%")
The classifierPredict function returns a boolean array with True if the probability of admission into university is more than 0.5 and False otherwise. Taking the sum(p==y) adds up all instances where it correctly predicts the y values.
The print statement print: Train Accuracy: 89 %, indicating our classifier predict 89% of the training set correctly.
This is all for Logistic Regression. As usual, the Jupyter notebook is uploaded to my GitHub at (https://github.com/Benlau93/Machine-Learning-by-Andrew-Ng-in-Python).
For other python implementation in the series,
Linear Regression
Regularized Logistic Regression
Neural Networks
Support Vector Machines
Unsupervised Learning
Anomaly Detection
Thank you for reading. | [
{
"code": null,
"e": 173,
"s": 47,
"text": "Continuing from the series, this will be python implementation of Andrew Ngβs Machine Learning Course on Logistic Regression."
},
{
"code": null,
"e": 351,
"s": 173,
"text": "Logistic regression is used in classification problems where the labels are a discrete number of classes as compared to linear regression, where labels are continuous variables."
},
{
"code": null,
"e": 625,
"s": 351,
"text": "Same as usual, we start with importing of libraries and the dataset. This dataset contains 2 different test score of students and their status of admission into the university. We are asked to predict if a student gets admitted into a university based on their test scores."
},
{
"code": null,
"e": 736,
"s": 625,
"text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pddf=pd.read_csv(\"ex2data1.txt\",header=None)"
},
{
"code": null,
"e": 761,
"s": 736,
"text": "Making sense of the data"
},
{
"code": null,
"e": 784,
"s": 761,
"text": "df.head()df.describe()"
},
{
"code": null,
"e": 805,
"s": 784,
"text": "Plotting of the data"
},
{
"code": null,
"e": 1073,
"s": 805,
"text": "pos , neg = (y==1).reshape(100,1) , (y==0).reshape(100,1)plt.scatter(X[pos[:,0],0],X[pos[:,0],1],c=\"r\",marker=\"+\")plt.scatter(X[neg[:,0],0],X[neg[:,0],1],marker=\"o\",s=10)plt.xlabel(\"Exam 1 score\")plt.ylabel(\"Exam 2 score\")plt.legend([\"Admitted\",\"Not admitted\"],loc=0)"
},
{
"code": null,
"e": 1687,
"s": 1073,
"text": "As this is not the standard scatter or line plot, I will break down the code step by step for easy understanding. For classification problem, we plot the independent variables against each other and identify the different classes to observe their relationship. As such, we need to differentiate the combination of x1 and x2 that led to an university admission and the combination that donβt. The variables pos and neg did just that. By plotting combination of x1 and x2 that was admitted into university with different color and marker as those that donβt get admitted, we successfully visualize the relationship."
},
{
"code": null,
"e": 1780,
"s": 1687,
"text": "Students with higher test score for both exam were admitted into the university as expected."
},
{
"code": null,
"e": 1868,
"s": 1780,
"text": "Now the sigmoid function that differentiates logistic regression from linear regression"
},
{
"code": null,
"e": 1999,
"s": 1868,
"text": "def sigmoid(z): \"\"\" return the sigmoid of z \"\"\" return 1/ (1 + np.exp(-z))# testing the sigmoid functionsigmoid(0)"
},
{
"code": null,
"e": 2042,
"s": 1999,
"text": "Running the sigmoid(0) function return 0.5"
},
{
"code": null,
"e": 2141,
"s": 2042,
"text": "To compute the cost function J(Ξ) and gradient (partial derivative of J(Ξ) with respect to each Ξ)"
},
{
"code": null,
"e": 2531,
"s": 2141,
"text": "def costFunction(theta, X, y): \"\"\" Takes in numpy array theta, x and y and return the logistic regression cost function and gradient \"\"\" m=len(y) predictions = sigmoid(np.dot(X,theta)) error = (-y * np.log(predictions)) - ((1-y)*np.log(1-predictions))cost = 1/m * sum(error) grad = 1/m * np.dot(X.transpose(),(predictions - y)) return cost[0] , grad"
},
{
"code": null,
"e": 2584,
"s": 2531,
"text": "Setting the initial_theta and test the cost function"
},
{
"code": null,
"e": 2830,
"s": 2584,
"text": "m , n = X.shape[0], X.shape[1]X= np.append(np.ones((m,1)),X,axis=1)y=y.reshape(m,1)initial_theta = np.zeros((n+1,1))cost, grad= costFunction(initial_theta,X,y)print(\"Cost of initial theta is\",cost)print(\"Gradient at initial theta (zeros):\",grad)"
},
{
"code": null,
"e": 2977,
"s": 2830,
"text": "The print statement will print: Cost of initial theta is 0.693147180559946 Gradient at initial theta (zeros): [-0.1],[-12.00921659],[-11.26284221]"
},
{
"code": null,
"e": 3520,
"s": 2977,
"text": "Now for the optimizing algorithm. In the assignment itself, we were told to make use of the fminunc function in Octave to finds the minimum of an unconstrained function. As for python implementation, a library is available that serves similar purpose. You can find the official documentation here. There are various optimization method to choose from and many others before me had used these methods for their python implementation. Here, I decided to use gradient descent to do the optimization and compare the result with fminunc in Octave."
},
{
"code": null,
"e": 3614,
"s": 3520,
"text": "Before doing gradient descent, never forget to do feature scaling for a multivariate problem."
},
{
"code": null,
"e": 3889,
"s": 3614,
"text": "def featureNormalization(X): \"\"\" Take in numpy array of X values and return normalize X values, the mean and standard deviation of each feature \"\"\" mean=np.mean(X,axis=0) std=np.std(X,axis=0) X_norm = (X - mean)/std return X_norm , mean , std"
},
{
"code": null,
"e": 4083,
"s": 3889,
"text": "As mentioned in the lecture, the gradient descent algorithm is very similar to linear regression. The only difference is that the hypothesis h(x) is now g(Ξ^Tx) where g is the sigmoid function."
},
{
"code": null,
"e": 4553,
"s": 4083,
"text": "def gradientDescent(X,y,theta,alpha,num_iters): \"\"\" Take in numpy array X, y and theta and update theta by taking num_iters gradient steps with learning rate of alpha return theta and the list of the cost of theta during each iteration \"\"\" m=len(y) J_history =[] for i in range(num_iters): cost, grad = costFunction(theta,X,y) theta = theta - (alpha * grad) J_history.append(cost) return theta , J_history"
},
{
"code": null,
"e": 4768,
"s": 4553,
"text": "I always like the saying of DRY (Donβt Repeat Yourself) in coding. Since we already have a function for computing the gradient previously, letβs not repeat the calculation and add on an alpha term here to update Ξ."
},
{
"code": null,
"e": 4897,
"s": 4768,
"text": "As the assignment did not implement gradient descent, I had to test a few alpha and num_iters values to find the optimal values."
},
{
"code": null,
"e": 4931,
"s": 4897,
"text": "Using alpha=0.01, num_iters=400 ,"
},
{
"code": null,
"e": 5065,
"s": 4931,
"text": "The gradient descent works in reducing the cost function at every iteration, but we can do better. With alpha = 0.1, num_iters =400 ,"
},
{
"code": null,
"e": 5156,
"s": 5065,
"text": "Much better, but I will try another value just to make sure. With alpha=1, num_iters=400 ,"
},
{
"code": null,
"e": 5575,
"s": 5156,
"text": "The drop is sharper and cost function plateau around the 150 iterations. Using this alpha and num_iters values, the optimized theta is [1.65947664],[3.8670477],[3.60347302] and the resulting cost is 0.20360044248226664 . A significant improvement from the initial 0.693147180559946 . When compared to the optimized cost function using fminunc in Octave, it is not that far off from 0.203498 obtained in the assignment."
},
{
"code": null,
"e": 5779,
"s": 5575,
"text": "Next is the plotting of the decision boundary using the optimized theta. There is a step by step explanation within the courseβs resource on how to plot the decision boundary. The link can be found here."
},
{
"code": null,
"e": 6127,
"s": 5779,
"text": "plt.scatter(X[pos[:,0],1],X[pos[:,0],2],c=\"r\",marker=\"+\",label=\"Admitted\")plt.scatter(X[neg[:,0],1],X[neg[:,0],2],c=\"b\",marker=\"x\",label=\"Not admitted\")x_value= np.array([np.min(X[:,1]),np.max(X[:,1])])y_value=-(theta[0] +theta[1]*x_value)/theta[2]plt.plot(x_value,y_value, \"r\")plt.xlabel(\"Exam 1 score\")plt.ylabel(\"Exam 2 score\")plt.legend(loc=0)"
},
{
"code": null,
"e": 6168,
"s": 6127,
"text": "Making predictions using optimized theta"
},
{
"code": null,
"e": 6389,
"s": 6168,
"text": "x_test = np.array([45,85])x_test = (x_test - X_mean)/X_stdx_test = np.append(np.ones(1),x_test)prob = sigmoid(x_test.dot(theta))print(\"For a student with scores 45 and 85, we predict an admission probability of\",prob[0])"
},
{
"code": null,
"e": 6568,
"s": 6389,
"text": "The print statement will print: For a student with scores 45 and 85, we predict an admission probability of 0.7677628875792492 . A close approximation to 0.776291 using fminunc ."
},
{
"code": null,
"e": 6681,
"s": 6568,
"text": "To find the accuracy of the classifier, we compute the percentage of correct classification on our training set."
},
{
"code": null,
"e": 6916,
"s": 6681,
"text": "def classifierPredict(theta,X): \"\"\" take in numpy array of theta and X and predict the class \"\"\" predictions = X.dot(theta) return predictions>0p=classifierPredict(theta,X)print(\"Train Accuracy:\", sum(p==y)[0],\"%\")"
},
{
"code": null,
"e": 7152,
"s": 6916,
"text": "The classifierPredict function returns a boolean array with True if the probability of admission into university is more than 0.5 and False otherwise. Taking the sum(p==y) adds up all instances where it correctly predicts the y values."
},
{
"code": null,
"e": 7270,
"s": 7152,
"text": "The print statement print: Train Accuracy: 89 %, indicating our classifier predict 89% of the training set correctly."
},
{
"code": null,
"e": 7437,
"s": 7270,
"text": "This is all for Logistic Regression. As usual, the Jupyter notebook is uploaded to my GitHub at (https://github.com/Benlau93/Machine-Learning-by-Andrew-Ng-in-Python)."
},
{
"code": null,
"e": 7484,
"s": 7437,
"text": "For other python implementation in the series,"
},
{
"code": null,
"e": 7502,
"s": 7484,
"text": "Linear Regression"
},
{
"code": null,
"e": 7534,
"s": 7502,
"text": "Regularized Logistic Regression"
},
{
"code": null,
"e": 7550,
"s": 7534,
"text": "Neural Networks"
},
{
"code": null,
"e": 7574,
"s": 7550,
"text": "Support Vector Machines"
},
{
"code": null,
"e": 7596,
"s": 7574,
"text": "Unsupervised Learning"
},
{
"code": null,
"e": 7614,
"s": 7596,
"text": "Anomaly Detection"
}
]
|
Highcharts - VU Meter Chart | We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter.
An example of a Gauge with dual axes is given below.
Let us now see the additional configurations/steps taken.
Configure the chart type to be gauge based. Set the type as 'gauge'.
var chart = {
type: 'guage'
};
Applies only to polar charts and angular gauges. This configuration object holds general options for the combined X and Y axes set. Each xAxis or yAxis can reference the pane by index.
var pane = {
startAngle: -150,
endAngle: 150
};
highcharts_vumeter.htm
<html>
<head>
<title>Highcharts Tutorial</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src = "https://code.highcharts.com/highcharts.js"></script>
<script src = "https://code.highcharts.com/highcharts-more.js"></script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div>
<script language = "JavaScript">
$(document).ready(function() {
var chart = {
type: 'gauge',
plotBorderWidth: 1,
plotBackgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#FFF4C6'],
[0.3, '#FFFFFF'],
[1, '#FFF4C6']
]
},
plotBackgroundImage: null,
height: 200
};
var credits = {
enabled: false
};
var title = {
text: 'VU meter'
};
var pane = [
{
startAngle: -45,
endAngle: 45,
background: null,
center: ['25%', '145%'],
size: 300
},
{
startAngle: -45,
endAngle: 45,
background: null,
center: ['75%', '145%'],
size: 300
}
];
var yAxis = [
{
min: -20,
max: 6,
minorTickPosition: 'outside',
tickPosition: 'outside',
labels: {
rotation: 'auto',
distance: 20
},
plotBands: [{
from: 0,
to: 6,
color: '#C02316',
innerRadius: '100%',
outerRadius: '105%'
}],
pane: 0,
title: {
text: 'VU<br/><span style = "font-size:8px">Channel A</span>',
y: -40
}
},
{
min: -20,
max: 6,
minorTickPosition: 'outside',
tickPosition: 'outside',
labels: {
rotation: 'auto',
distance: 20
},
plotBands: [{
from: 0,
to: 6,
color: '#C02316',
innerRadius: '100%',
outerRadius: '105%'
}],
pane: 1,
title: {
text: 'VU<br/><span style = "font-size:8px">Channel B</span>',
y: -40
}
}
];
var plotOptions = {
gauge: {
dataLabels: {
enabled: false
},
dial: {
radius: '100%'
}
}
};
var series = [
{
data: [-20],
yAxis: 0
},
{
data: [-20],
yAxis: 1
}
];
var json = {};
json.chart = chart;
json.credits = credits;
json.title = title;
json.pane = pane;
json.yAxis = yAxis;
json.plotOptions = plotOptions;
json.series = series;
// Add some life
var chartFunction = function (chart) {
setInterval(function () {
if (chart.series) { // the chart may be destroyed
var left = chart.series[0].points[0],
right = chart.series[1].points[0],
leftVal,
rightVal,
inc = (Math.random() - 0.5) * 3;
leftVal = left.y + inc;
rightVal = leftVal + inc / 3;
if (leftVal < -20 || leftVal > 6) {
leftVal = left.y - inc;
}
if (rightVal < -20 || rightVal > 6) {
rightVal = leftVal;
}
left.update(leftVal, false);
right.update(rightVal, false);
chart.redraw();
}
}, 500);
};
$('#container').highcharts(json, chartFunction);
});
</script>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2121,
"s": 2017,
"text": "We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter."
},
{
"code": null,
"e": 2174,
"s": 2121,
"text": "An example of a Gauge with dual axes is given below."
},
{
"code": null,
"e": 2232,
"s": 2174,
"text": "Let us now see the additional configurations/steps taken."
},
{
"code": null,
"e": 2301,
"s": 2232,
"text": "Configure the chart type to be gauge based. Set the type as 'gauge'."
},
{
"code": null,
"e": 2335,
"s": 2301,
"text": "var chart = {\n type: 'guage'\n};"
},
{
"code": null,
"e": 2520,
"s": 2335,
"text": "Applies only to polar charts and angular gauges. This configuration object holds general options for the combined X and Y axes set. Each xAxis or yAxis can reference the pane by index."
},
{
"code": null,
"e": 2574,
"s": 2520,
"text": "var pane = {\n startAngle: -150,\n endAngle: 150\n};"
},
{
"code": null,
"e": 2597,
"s": 2574,
"text": "highcharts_vumeter.htm"
},
{
"code": null,
"e": 7569,
"s": 2597,
"text": "<html>\n <head>\n <title>Highcharts Tutorial</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"https://code.highcharts.com/highcharts.js\"></script> \n <script src = \"https://code.highcharts.com/highcharts-more.js\"></script> \n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\"></div>\n <script language = \"JavaScript\">\n $(document).ready(function() { \n var chart = {\n type: 'gauge',\n plotBorderWidth: 1,\n plotBackgroundColor: {\n linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },\n stops: [\n [0, '#FFF4C6'],\n [0.3, '#FFFFFF'],\n [1, '#FFF4C6']\n ]\n },\n plotBackgroundImage: null,\n height: 200\n };\n var credits = {\n enabled: false\n };\n var title = {\n text: 'VU meter'\n };\n var pane = [\n {\n startAngle: -45,\n endAngle: 45,\n background: null,\n center: ['25%', '145%'],\n size: 300\n }, \n {\n startAngle: -45,\n endAngle: 45,\n background: null,\n center: ['75%', '145%'],\n size: 300\n }\n ];\n var yAxis = [\n {\n min: -20,\n max: 6,\n minorTickPosition: 'outside',\n tickPosition: 'outside',\n labels: {\n rotation: 'auto',\n distance: 20\n },\n plotBands: [{\n from: 0,\n to: 6,\n color: '#C02316',\n innerRadius: '100%',\n outerRadius: '105%'\n }],\n pane: 0,\n title: {\n text: 'VU<br/><span style = \"font-size:8px\">Channel A</span>',\n y: -40\n }\n }, \n {\n min: -20,\n max: 6,\n minorTickPosition: 'outside',\n tickPosition: 'outside',\n labels: {\n rotation: 'auto',\n distance: 20\n },\n plotBands: [{\n from: 0,\n to: 6,\n color: '#C02316',\n innerRadius: '100%',\n outerRadius: '105%'\n }],\n pane: 1,\n title: {\n text: 'VU<br/><span style = \"font-size:8px\">Channel B</span>',\n y: -40\n }\n }\n ];\n var plotOptions = {\n gauge: {\n dataLabels: {\n enabled: false\n },\n dial: {\n radius: '100%'\n }\n }\n };\n var series = [\n {\n data: [-20],\n yAxis: 0\n }, \n {\n data: [-20],\n yAxis: 1\n }\n ]; \n \n var json = {}; \n json.chart = chart; \n json.credits = credits;\n json.title = title; \n json.pane = pane; \n json.yAxis = yAxis; \n json.plotOptions = plotOptions; \n json.series = series; \n \n // Add some life\n var chartFunction = function (chart) {\n setInterval(function () {\n if (chart.series) { // the chart may be destroyed\n var left = chart.series[0].points[0],\n right = chart.series[1].points[0],\n leftVal,\n rightVal,\n inc = (Math.random() - 0.5) * 3;\n leftVal = left.y + inc;\n rightVal = leftVal + inc / 3;\n \n if (leftVal < -20 || leftVal > 6) {\n leftVal = left.y - inc;\n }\n if (rightVal < -20 || rightVal > 6) {\n rightVal = leftVal;\n }\n left.update(leftVal, false);\n right.update(rightVal, false);\n chart.redraw();\n }\n }, 500);\n };\n $('#container').highcharts(json, chartFunction); \n });\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 7588,
"s": 7569,
"text": "Verify the result."
},
{
"code": null,
"e": 7595,
"s": 7588,
"text": " Print"
},
{
"code": null,
"e": 7606,
"s": 7595,
"text": " Add Notes"
}
]
|
How to create a responsive "timeline" with CSS? | To create a responsive timeline with CSS, the code is as follows β
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" event="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}
body {
background-color: #9037f5;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif
}
h2{
text-align: center;
}
.timeline {
position: relative;
max-width: 1200px;
margin: 0 auto;
}
.timeline::after {
content: " ";
position: absolute;
width: 6px;
background-color: rgb(253, 203, 255);
top: 0;
bottom: 0;
left: 50%;
margin-left: -3px;
}
/* eventsContainer around event */
.eventsContainer {
padding: 10px 40px;
position: relative;
background-color: inherit;
width: 50%;
}
.eventsContainer::after {
content: " ";
position: absolute;
width: 25px;
height: 25px;
right: -17px;
background-color: rgb(219, 255, 12);
border: 4px dashed rgb(255, 0, 0);
background-clip: content-box;
top: 15px;
z-index: 1;
}
.displayLeft {
left: 0;
}
.displayRight {
left: 50%;
}
.displayLeft::before {
content: " ";
height: 0;
position: absolute;
top: 22px;
width: 0;
z-index: 1;
right: 30px;
border: medium solid rgb(225, 246, 255);
border-width: 10px 0 10px 10px;
border-color: transparent transparent transparent white;
}
.displayRight::before {
content: " ";
height: 0;
position: absolute;
top: 22px;
width: 0;
z-index: 1;
left: 30px;
border: medium solid white;
border-width: 10px 10px 10px 0;
border-color: transparent white transparent transparent;
}
.displayRight::after {
left: -16px;
}
.event {
padding: 20px 30px;
background-color: white;
position: relative;
border-radius: 6px;
}
@media screen and (max-width: 600px) {
.timeline::after {
left: 31px;
}
.eventsContainer {
width: 100%;
padding-left: 70px;
padding-right: 25px;
}
.eventsContainer::before {
left: 60px;
border: medium solid white;
border-width: 10px 10px 10px 0;
border-color: transparent white transparent transparent;
}
.displayLeft::after, .displayRight::after {
left: 15px;
}
.displayRight {
left: 0%;
}
}
</style>
</head>
<body>
<div class="timeline">
<div class="eventsContainer displayLeft">
<div class="event">
<h2>2017</h2>
<h3>Donald Trump became the 45th president of US</h3>
</div>
</div>
<div class="eventsContainer displayRight">
<div class="event">
<h2>2016</h2>
<h3>Summer Olympics are held in rio de Janerio</h3>
</div>
</div>
<div class="eventsContainer displayLeft">
<div class="event">
<h2>2015</h2>
<h3>7.8 Magnitude Earthquake strikes nepal</h3>
</div>
</div>
</div>
</body>
</html>
The above code will produce the following output β
On resizing the screen β | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "To create a responsive timeline with CSS, the code is as follows β"
},
{
"code": null,
"e": 1140,
"s": 1129,
"text": " Live Demo"
},
{
"code": null,
"e": 4115,
"s": 1140,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" event=\"width=device-width, initial-scale=1.0\">\n<style>\n * {\n box-sizing: border-box;\n }\n body {\n background-color: #9037f5;\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif\n }\n h2{\n text-align: center;\n }\n .timeline {\n position: relative;\n max-width: 1200px;\n margin: 0 auto;\n }\n .timeline::after {\n content: \" \";\n position: absolute;\n width: 6px;\n background-color: rgb(253, 203, 255);\n top: 0;\n bottom: 0;\n left: 50%;\n margin-left: -3px;\n }\n /* eventsContainer around event */\n .eventsContainer {\n padding: 10px 40px;\n position: relative;\n background-color: inherit;\n width: 50%;\n }\n .eventsContainer::after {\n content: \" \";\n position: absolute;\n width: 25px;\n height: 25px;\n right: -17px;\n background-color: rgb(219, 255, 12);\n border: 4px dashed rgb(255, 0, 0);\n background-clip: content-box;\n top: 15px;\n z-index: 1;\n }\n .displayLeft {\n left: 0;\n }\n .displayRight {\n left: 50%;\n }\n .displayLeft::before {\n content: \" \";\n height: 0;\n position: absolute;\n top: 22px;\n width: 0;\n z-index: 1;\n right: 30px;\n border: medium solid rgb(225, 246, 255);\n border-width: 10px 0 10px 10px;\n border-color: transparent transparent transparent white;\n }\n .displayRight::before {\n content: \" \";\n height: 0;\n position: absolute;\n top: 22px;\n width: 0;\n z-index: 1;\n left: 30px;\n border: medium solid white;\n border-width: 10px 10px 10px 0;\n border-color: transparent white transparent transparent;\n }\n .displayRight::after {\n left: -16px;\n }\n .event {\n padding: 20px 30px;\n background-color: white;\n position: relative;\n border-radius: 6px;\n }\n @media screen and (max-width: 600px) {\n .timeline::after {\n left: 31px;\n }\n .eventsContainer {\n width: 100%;\n padding-left: 70px;\n padding-right: 25px;\n }\n .eventsContainer::before {\n left: 60px;\n border: medium solid white;\n border-width: 10px 10px 10px 0;\n border-color: transparent white transparent transparent;\n }\n .displayLeft::after, .displayRight::after {\n left: 15px;\n }\n .displayRight {\n left: 0%;\n }\n }\n</style>\n</head>\n<body>\n<div class=\"timeline\">\n<div class=\"eventsContainer displayLeft\">\n<div class=\"event\">\n<h2>2017</h2>\n<h3>Donald Trump became the 45th president of US</h3>\n</div>\n</div>\n<div class=\"eventsContainer displayRight\">\n<div class=\"event\">\n<h2>2016</h2>\n<h3>Summer Olympics are held in rio de Janerio</h3>\n</div>\n</div>\n<div class=\"eventsContainer displayLeft\">\n<div class=\"event\">\n<h2>2015</h2>\n<h3>7.8 Magnitude Earthquake strikes nepal</h3>\n</div>\n</div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 4166,
"s": 4115,
"text": "The above code will produce the following output β"
},
{
"code": null,
"e": 4191,
"s": 4166,
"text": "On resizing the screen β"
}
]
|
I Implemented a Face Detection Model. Hereβs How I Did It. | by Chi-Feng Wang | Towards Data Science | Last week, I started an internship at Augentix Inc., aiming to learn more about neural networks. There, I came across a model for facial detection which achieved high accuracy while keeping real time performance (link here). This model uses Multi-task Cascaded Convolutional Networks (MTCNN), which is essentially several convolutional networks strung together that give out several pieces of information.
After downloading the model from github (link here), I opened up and ran example.py, which produced this image:
As seen in the image above, the neural network detects individual faces, locates facial landmarks (i.e. two eyes, nose, and endpoints of the mouth), and draws a bounding box around the face. The code from example.py supports this.
First, they import OpenCV (to open, read, write, and show images) and MTCNN. Checking ./mtcnn/mtcnn.py showed the MTCNN class, which performed the facial detection.
#!/usr/bin/env python3# -*- coding: utf-8 -*-import cv2from mtcnn.mtcnn import MTCNN
Then, a detector of the MTCNN class was created, and the image read in with cv2.imread. The detect_faces function within the MTCNN class is called, to βdetect facesβ within the image we passed in and output the faces in βresultβ.
detector = MTCNN()image = cv2.imread("ivan.jpg")result = detector.detect_faces(image)
To check what was in βresultβ, I printed it out to get:
[{'box': [277, 90, 48, 63], 'confidence': 0.9985162615776062, 'keypoints': {'left_eye': (291, 117), 'right_eye': (314, 114), 'nose': (303, 131), 'mouth_left': (296, 143), 'mouth_right': (313, 141)}}]
Result seems to be a dictionary that included the coordinates of the bounding box and facial landmarks, as well as the networkβs confidence in classifying that area as a face.
We can now separate the coordinates, passing in the bounding box coordinates to bounding_box and the facial landmark coordinates to keypoints.
bounding_box = result[0]['box']keypoints = result[0]['keypoints']
Now we draw the rectangle of the bounding box by passing in the coordinates, the color (RGB), and the thickness of the box outline. Here, bounding_box[0] and bounding_box[1] represent the x and y coordinates of the top left corner, and bounding_box[2] and bounding_box[3] represent the width and the height of the box, respectively.
Similarly, we can draw the points of the facial landmarks by passing in their coordinates, the radius of the circle, and the thickness of the line.
cv2.rectangle(image, (bounding_box[0], bounding_box[1]), (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]), (0,155,255), 2)cv2.circle(image,(keypoints['left_eye']), 2, (0,155,255), 2)cv2.circle(image,(keypoints['right_eye']), 2, (0,155,255), 2)cv2.circle(image,(keypoints['nose']), 2, (0,155,255), 2)cv2.circle(image,(keypoints['mouth_left']), 2, (0,155,255), 2)cv2.circle(image,(keypoints['mouth_right']), 2, (0,155,255), 2)
Finally, we create another file named βivan_drawn.jpgβ and show the image.
cv2.imwrite("ivan_drawn.jpg", image)cv2.namedWindow("image")cv2.imshow("image",image)cv2.waitKey(0)
This was good, but facial detection is a big useless if we could only pass in images. I wanted to modify it so I could use it with my webcam. In doing so, I can also test the paperβs claim that it would be able to locate faces in real time.
Once again, I imported OpenCV and MTCNN, then created a detector:
import cv2from mtcnn.mtcnn import MTCNNdetector = MTCNN()
To use my webcam, I created a VideoCapture object. Since I only have 1 camera, I passed in 0.
cap.read() returns a boolean (True/False) that states whether or not a frame is read in correctly. If an error occurs and a frame is not read it, it will return False and the while loop will be broken.
Then, similar to example.py, I called detect_faces on each frame. Since sometimes a face may not be in the frame (and result will be empty), I added βif result != []β for the program to continue running even when there are no faces in the frame.
In addition, there may be more than one face in the frame. In that case, result will return back multiple sets of coordinates, one for each face. Hence, I ran a for loop in result to iterate through every individual face. For each face, I drew out the bounding box frame and dotted the 5 facial landmarks.
Finally, I displayed each individual frame. Each frame will wait for 1 millisecond for the key βqβ, then move on to the next frame. To close the window, all I have to do is press βqβ. Once I do that, I release the video capture and close the window.
cap = cv2.VideoCapture(0)while True: #Capture frame-by-frame __, frame = cap.read() #Use MTCNN to detect faces result = detector.detect_faces(frame) if result != []: for person in result: bounding_box = person['box'] keypoints = person['keypoints'] cv2.rectangle(frame, (bounding_box[0], bounding_box[1]), (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]), (0,155,255), 2) cv2.circle(frame,(keypoints['left_eye']), 2, (0,155,255), 2) cv2.circle(frame,(keypoints['right_eye']), 2, (0,155,255), 2) cv2.circle(frame,(keypoints['nose']), 2, (0,155,255), 2) cv2.circle(frame,(keypoints['mouth_left']), 2, (0,155,255), 2) cv2.circle(frame,(keypoints['mouth_right']), 2, (0,155,255), 2) #display resulting frame cv2.imshow('frame',frame) if cv2.waitKey(1) &0xFF == ord('q'): break#When everything's done, release capturecap.release()cv2.destroyAllWindows()
Running this new file, I see that the MTCNN network can indeed run in real time. boxing my face and marking out my features. If I move my face out of the frame, the webcam continues running as well.
Click here to read about the structure of the MTCNN model!
Click here to read about how MTCNN does face detection!
Download the MTCNN paper and resources here:
Github download: https://github.com/ipazc/mtcnn
Research article: http://arxiv.org/abs/1604.02878 | [
{
"code": null,
"e": 578,
"s": 172,
"text": "Last week, I started an internship at Augentix Inc., aiming to learn more about neural networks. There, I came across a model for facial detection which achieved high accuracy while keeping real time performance (link here). This model uses Multi-task Cascaded Convolutional Networks (MTCNN), which is essentially several convolutional networks strung together that give out several pieces of information."
},
{
"code": null,
"e": 690,
"s": 578,
"text": "After downloading the model from github (link here), I opened up and ran example.py, which produced this image:"
},
{
"code": null,
"e": 921,
"s": 690,
"text": "As seen in the image above, the neural network detects individual faces, locates facial landmarks (i.e. two eyes, nose, and endpoints of the mouth), and draws a bounding box around the face. The code from example.py supports this."
},
{
"code": null,
"e": 1086,
"s": 921,
"text": "First, they import OpenCV (to open, read, write, and show images) and MTCNN. Checking ./mtcnn/mtcnn.py showed the MTCNN class, which performed the facial detection."
},
{
"code": null,
"e": 1171,
"s": 1086,
"text": "#!/usr/bin/env python3# -*- coding: utf-8 -*-import cv2from mtcnn.mtcnn import MTCNN"
},
{
"code": null,
"e": 1401,
"s": 1171,
"text": "Then, a detector of the MTCNN class was created, and the image read in with cv2.imread. The detect_faces function within the MTCNN class is called, to βdetect facesβ within the image we passed in and output the faces in βresultβ."
},
{
"code": null,
"e": 1487,
"s": 1401,
"text": "detector = MTCNN()image = cv2.imread(\"ivan.jpg\")result = detector.detect_faces(image)"
},
{
"code": null,
"e": 1543,
"s": 1487,
"text": "To check what was in βresultβ, I printed it out to get:"
},
{
"code": null,
"e": 1743,
"s": 1543,
"text": "[{'box': [277, 90, 48, 63], 'confidence': 0.9985162615776062, 'keypoints': {'left_eye': (291, 117), 'right_eye': (314, 114), 'nose': (303, 131), 'mouth_left': (296, 143), 'mouth_right': (313, 141)}}]"
},
{
"code": null,
"e": 1919,
"s": 1743,
"text": "Result seems to be a dictionary that included the coordinates of the bounding box and facial landmarks, as well as the networkβs confidence in classifying that area as a face."
},
{
"code": null,
"e": 2062,
"s": 1919,
"text": "We can now separate the coordinates, passing in the bounding box coordinates to bounding_box and the facial landmark coordinates to keypoints."
},
{
"code": null,
"e": 2128,
"s": 2062,
"text": "bounding_box = result[0]['box']keypoints = result[0]['keypoints']"
},
{
"code": null,
"e": 2461,
"s": 2128,
"text": "Now we draw the rectangle of the bounding box by passing in the coordinates, the color (RGB), and the thickness of the box outline. Here, bounding_box[0] and bounding_box[1] represent the x and y coordinates of the top left corner, and bounding_box[2] and bounding_box[3] represent the width and the height of the box, respectively."
},
{
"code": null,
"e": 2609,
"s": 2461,
"text": "Similarly, we can draw the points of the facial landmarks by passing in their coordinates, the radius of the circle, and the thickness of the line."
},
{
"code": null,
"e": 3106,
"s": 2609,
"text": "cv2.rectangle(image, (bounding_box[0], bounding_box[1]), (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]), (0,155,255), 2)cv2.circle(image,(keypoints['left_eye']), 2, (0,155,255), 2)cv2.circle(image,(keypoints['right_eye']), 2, (0,155,255), 2)cv2.circle(image,(keypoints['nose']), 2, (0,155,255), 2)cv2.circle(image,(keypoints['mouth_left']), 2, (0,155,255), 2)cv2.circle(image,(keypoints['mouth_right']), 2, (0,155,255), 2)"
},
{
"code": null,
"e": 3181,
"s": 3106,
"text": "Finally, we create another file named βivan_drawn.jpgβ and show the image."
},
{
"code": null,
"e": 3281,
"s": 3181,
"text": "cv2.imwrite(\"ivan_drawn.jpg\", image)cv2.namedWindow(\"image\")cv2.imshow(\"image\",image)cv2.waitKey(0)"
},
{
"code": null,
"e": 3522,
"s": 3281,
"text": "This was good, but facial detection is a big useless if we could only pass in images. I wanted to modify it so I could use it with my webcam. In doing so, I can also test the paperβs claim that it would be able to locate faces in real time."
},
{
"code": null,
"e": 3588,
"s": 3522,
"text": "Once again, I imported OpenCV and MTCNN, then created a detector:"
},
{
"code": null,
"e": 3646,
"s": 3588,
"text": "import cv2from mtcnn.mtcnn import MTCNNdetector = MTCNN()"
},
{
"code": null,
"e": 3740,
"s": 3646,
"text": "To use my webcam, I created a VideoCapture object. Since I only have 1 camera, I passed in 0."
},
{
"code": null,
"e": 3942,
"s": 3740,
"text": "cap.read() returns a boolean (True/False) that states whether or not a frame is read in correctly. If an error occurs and a frame is not read it, it will return False and the while loop will be broken."
},
{
"code": null,
"e": 4188,
"s": 3942,
"text": "Then, similar to example.py, I called detect_faces on each frame. Since sometimes a face may not be in the frame (and result will be empty), I added βif result != []β for the program to continue running even when there are no faces in the frame."
},
{
"code": null,
"e": 4494,
"s": 4188,
"text": "In addition, there may be more than one face in the frame. In that case, result will return back multiple sets of coordinates, one for each face. Hence, I ran a for loop in result to iterate through every individual face. For each face, I drew out the bounding box frame and dotted the 5 facial landmarks."
},
{
"code": null,
"e": 4744,
"s": 4494,
"text": "Finally, I displayed each individual frame. Each frame will wait for 1 millisecond for the key βqβ, then move on to the next frame. To close the window, all I have to do is press βqβ. Once I do that, I release the video capture and close the window."
},
{
"code": null,
"e": 5852,
"s": 4744,
"text": "cap = cv2.VideoCapture(0)while True: #Capture frame-by-frame __, frame = cap.read() #Use MTCNN to detect faces result = detector.detect_faces(frame) if result != []: for person in result: bounding_box = person['box'] keypoints = person['keypoints'] cv2.rectangle(frame, (bounding_box[0], bounding_box[1]), (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]), (0,155,255), 2) cv2.circle(frame,(keypoints['left_eye']), 2, (0,155,255), 2) cv2.circle(frame,(keypoints['right_eye']), 2, (0,155,255), 2) cv2.circle(frame,(keypoints['nose']), 2, (0,155,255), 2) cv2.circle(frame,(keypoints['mouth_left']), 2, (0,155,255), 2) cv2.circle(frame,(keypoints['mouth_right']), 2, (0,155,255), 2) #display resulting frame cv2.imshow('frame',frame) if cv2.waitKey(1) &0xFF == ord('q'): break#When everything's done, release capturecap.release()cv2.destroyAllWindows()"
},
{
"code": null,
"e": 6051,
"s": 5852,
"text": "Running this new file, I see that the MTCNN network can indeed run in real time. boxing my face and marking out my features. If I move my face out of the frame, the webcam continues running as well."
},
{
"code": null,
"e": 6110,
"s": 6051,
"text": "Click here to read about the structure of the MTCNN model!"
},
{
"code": null,
"e": 6166,
"s": 6110,
"text": "Click here to read about how MTCNN does face detection!"
},
{
"code": null,
"e": 6211,
"s": 6166,
"text": "Download the MTCNN paper and resources here:"
},
{
"code": null,
"e": 6259,
"s": 6211,
"text": "Github download: https://github.com/ipazc/mtcnn"
}
]
|
How to retrieve the OS of the Azure VM using Azure CLI in PowerShell? | To retrieve the Azure VM OS using Azure CLI, we can use the βaz vmβ command but before that, need to make sure that you are connected to the Azure cloud and the subscription.
PS C:\> az vm show -n VMName -g VMRG --query
"[storageProfile.imageReference.offer]" -otsv
OR
PS C:\> az vm show -n VMName -g VMRG --query storageProfile.imageReference.offer -
otsv
WindowsServer
To get the OS SKU or the operating system version, you can use,
PS C:\> az vm show -n VMName -g VMRG --query
"[storageProfile.imageReference.sku]" -otsv
2016-Datacenter
You can also use the below command to get the OS of the VM without providing the resource group name.
PS C:\> az vm list --query
"[?name==VMName].{os:storageProfile.imageReference.offer}" -otsv
To get the OS version or SKU,
PS C:\> az vm list --query "[?name==VMName].{os:storageProfile.imageReference.sku}"
-otsv
To combine all the outputs in the table format,
az vm list --query "[].{vmName:name, ResourceGroup:resourceGroup,
os:storageProfile.imageReference.offer, version:storageProfile.imageReference.sku}" -
otable | [
{
"code": null,
"e": 1237,
"s": 1062,
"text": "To retrieve the Azure VM OS using Azure CLI, we can use the βaz vmβ command but before that, need to make sure that you are connected to the Azure cloud and the subscription."
},
{
"code": null,
"e": 1328,
"s": 1237,
"text": "PS C:\\> az vm show -n VMName -g VMRG --query\n\"[storageProfile.imageReference.offer]\" -otsv"
},
{
"code": null,
"e": 1331,
"s": 1328,
"text": "OR"
},
{
"code": null,
"e": 1419,
"s": 1331,
"text": "PS C:\\> az vm show -n VMName -g VMRG --query storageProfile.imageReference.offer -\notsv"
},
{
"code": null,
"e": 1433,
"s": 1419,
"text": "WindowsServer"
},
{
"code": null,
"e": 1497,
"s": 1433,
"text": "To get the OS SKU or the operating system version, you can use,"
},
{
"code": null,
"e": 1586,
"s": 1497,
"text": "PS C:\\> az vm show -n VMName -g VMRG --query\n\"[storageProfile.imageReference.sku]\" -otsv"
},
{
"code": null,
"e": 1602,
"s": 1586,
"text": "2016-Datacenter"
},
{
"code": null,
"e": 1704,
"s": 1602,
"text": "You can also use the below command to get the OS of the VM without providing the resource group name."
},
{
"code": null,
"e": 1796,
"s": 1704,
"text": "PS C:\\> az vm list --query\n\"[?name==VMName].{os:storageProfile.imageReference.offer}\" -otsv"
},
{
"code": null,
"e": 1826,
"s": 1796,
"text": "To get the OS version or SKU,"
},
{
"code": null,
"e": 1916,
"s": 1826,
"text": "PS C:\\> az vm list --query \"[?name==VMName].{os:storageProfile.imageReference.sku}\"\n-otsv"
},
{
"code": null,
"e": 1964,
"s": 1916,
"text": "To combine all the outputs in the table format,"
},
{
"code": null,
"e": 2123,
"s": 1964,
"text": "az vm list --query \"[].{vmName:name, ResourceGroup:resourceGroup,\nos:storageProfile.imageReference.offer, version:storageProfile.imageReference.sku}\" -\notable"
}
]
|
How to query on list field in MongoDB? | To understand the query on list field, and/or, you can create a collection with documents.
The query to create a collection with a document is as follows β
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[33,40,50,60,70]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9522d316f542d757e2b444")
}
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[87,67,79,98,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c95230916f542d757e2b445")
}
Display all documents from a collection with the help of find() method. The query is as follows β
> db.andOrDemo.find().pretty();
The following is the output β
{
"_id" : ObjectId("5c9522d316f542d757e2b444"),
"StudentName" : "Larry",
"StudentScore" : [
33,
40,
50,
60,
70
]
}
{
"_id" : ObjectId("5c95230916f542d757e2b445"),
"StudentName" : "Larry",
"StudentScore" : [
87,
67,
79,
98,
90
]
}
Here is the query on list field.
The query is as follows β
> db.andOrDemo.find({"StudentScore":70}).pretty();
The following is the output:
{
"_id" : ObjectId("5c9522d316f542d757e2b444"),
"StudentName" : "Larry",
"StudentScore" : [
33,
40,
50,
60,
70
]
}
Case 3 β Here is the query for or list field.
The query is as follows β
> db.andOrDemo.find({"$or":[ {"StudentScore":60}, {"StudentScore":90}]}).pretty();
Sample Output β
{
"_id" : ObjectId("5c9522d316f542d757e2b444"),
"StudentName" : "Larry",
"StudentScore" : [
33,
40,
50,
60,
70
]
}
{
"_id" : ObjectId("5c95230916f542d757e2b445"),
"StudentName" : "Larry",
"StudentScore" : [
87,
67,
79,
98,
90
]
} | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To understand the query on list field, and/or, you can create a collection with documents."
},
{
"code": null,
"e": 1218,
"s": 1153,
"text": "The query to create a collection with a document is as follows β"
},
{
"code": null,
"e": 1554,
"s": 1218,
"text": "> db.andOrDemo.insertOne({\"StudentName\":\"Larry\",\"StudentScore\":[33,40,50,60,70]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9522d316f542d757e2b444\")\n}\n> db.andOrDemo.insertOne({\"StudentName\":\"Larry\",\"StudentScore\":[87,67,79,98,90]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c95230916f542d757e2b445\")\n}"
},
{
"code": null,
"e": 1652,
"s": 1554,
"text": "Display all documents from a collection with the help of find() method. The query is as follows β"
},
{
"code": null,
"e": 1684,
"s": 1652,
"text": "> db.andOrDemo.find().pretty();"
},
{
"code": null,
"e": 1714,
"s": 1684,
"text": "The following is the output β"
},
{
"code": null,
"e": 2028,
"s": 1714,
"text": "{\n \"_id\" : ObjectId(\"5c9522d316f542d757e2b444\"),\n \"StudentName\" : \"Larry\",\n \"StudentScore\" : [\n 33,\n 40,\n 50,\n 60,\n 70\n ]\n}\n{\n \"_id\" : ObjectId(\"5c95230916f542d757e2b445\"),\n \"StudentName\" : \"Larry\",\n \"StudentScore\" : [\n 87,\n 67,\n 79,\n 98,\n 90\n ]\n}"
},
{
"code": null,
"e": 2061,
"s": 2028,
"text": "Here is the query on list field."
},
{
"code": null,
"e": 2087,
"s": 2061,
"text": "The query is as follows β"
},
{
"code": null,
"e": 2138,
"s": 2087,
"text": "> db.andOrDemo.find({\"StudentScore\":70}).pretty();"
},
{
"code": null,
"e": 2167,
"s": 2138,
"text": "The following is the output:"
},
{
"code": null,
"e": 2324,
"s": 2167,
"text": "{\n \"_id\" : ObjectId(\"5c9522d316f542d757e2b444\"),\n \"StudentName\" : \"Larry\",\n \"StudentScore\" : [\n 33,\n 40,\n 50,\n 60,\n 70\n ]\n}"
},
{
"code": null,
"e": 2370,
"s": 2324,
"text": "Case 3 β Here is the query for or list field."
},
{
"code": null,
"e": 2396,
"s": 2370,
"text": "The query is as follows β"
},
{
"code": null,
"e": 2479,
"s": 2396,
"text": "> db.andOrDemo.find({\"$or\":[ {\"StudentScore\":60}, {\"StudentScore\":90}]}).pretty();"
},
{
"code": null,
"e": 2495,
"s": 2479,
"text": "Sample Output β"
},
{
"code": null,
"e": 2809,
"s": 2495,
"text": "{\n \"_id\" : ObjectId(\"5c9522d316f542d757e2b444\"),\n \"StudentName\" : \"Larry\",\n \"StudentScore\" : [\n 33,\n 40,\n 50,\n 60,\n 70\n ]\n}\n{\n \"_id\" : ObjectId(\"5c95230916f542d757e2b445\"),\n \"StudentName\" : \"Larry\",\n \"StudentScore\" : [\n 87,\n 67,\n 79,\n 98,\n 90\n ]\n}"
}
]
|
Selecting Multiple Columns From a Pandas DataFrame | Towards Data Science | Multiple column selection is one of the most common and simple tasks one can perform. In todayβs short guide we will discuss about a few possible ways for selecting multiple columns from a pandas DataFrame. Specifically, we will explore how to do so
using basing indexing
with loc
using iloc
through the creation of a new DataFrame
Additionally, we will discuss when to use one method over the other, based on your specific use-case and whether you need to generate a view or a copy of the original DataFrame object.
First, letβs create an example DataFrame that weβll reference throughout this article in order to demonstrate a few concepts.
import pandas pddf = pd.DataFrame({ 'colA':[1, 2, 3], 'colB': ['a', 'b', 'c'], 'colC': [True, False, True], 'colD': [1.0, 2.0, 3.0],})print(df) colA colB colC colD0 1 a True 1.01 2 b False 2.02 3 c True 3.0
The first option you have when comes to select multiple columns from an existing pandas DataFrame is the use of basic indexing. This approach is usually useful when you know precisely which columns you want to keep.
Therefore, you can take a copy of the original DataFrame containing only those columns by passing the list with the names using the [] notation which is equivalent to __getitem__ implementation in Python classes.
df_result = df[['colA', 'colD']]print(df_result) colA colD0 1 1.01 2 2.02 3 3.0
If you want to learn more about how indexing and slicing works in Python, make sure to read the article below.
towardsdatascience.com
Alternatively, if you want to reference column indices instead of column names and slice the original DataFrame (for instance if you want to keep say the first two columns but you donβt really know the column names), you can use iloc.
df_result = df.iloc[:, 0:2]print(df_result) colA colB0 1 a1 2 b2 3 c
Note that the above operation, will return a view of the original DataFrame. This means that the view will contain only a chunk of the original DataFrame but it will still point to the same locations in memory. Therefore, if you modify the sliced object (df_result), then this may also effect the original object (df).
If you wish to slice the DataFrame but get a copy of the original object instead, then simply call copy():
df_result = df.iloc[:, 0:2].copy()
Now if you want to slice the original DataFrame using the actual column names, then you can use the loc method. For instance, if you want to get the first three columns, you can do so with loc by referencing the first and last name of the range of columns you want to keep:
df_result = df.loc[:, 'colA':'colC']print(df_result) colA colB colC0 1 a True1 2 b False2 3 c True
At this point you may want to read about the differences between loc and iloc in Pandas and clarify which one to use based on your specific requirements and use-cases.
towardsdatascience.com
Finally, you can even create a new DataFrame using only a subset of the columns included in the original DataFrame as shown below.
df_result = pd.DataFrame(df, columns=['colA', 'colC'])print(df_result) colA colC0 1 True1 2 False2 3 True
In todayβs short guide we showcased a few possible ways for selecting multiple columns from a pandas DataFrame. We discussed how to do so using simple indexing, iloc, loc and through the creation of a new DataFrame. Note that some of the methods discussed in this article, may generate a view of the original DataFrame and thus you should be extra careful.
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read.
You may also like | [
{
"code": null,
"e": 421,
"s": 171,
"text": "Multiple column selection is one of the most common and simple tasks one can perform. In todayβs short guide we will discuss about a few possible ways for selecting multiple columns from a pandas DataFrame. Specifically, we will explore how to do so"
},
{
"code": null,
"e": 443,
"s": 421,
"text": "using basing indexing"
},
{
"code": null,
"e": 452,
"s": 443,
"text": "with loc"
},
{
"code": null,
"e": 463,
"s": 452,
"text": "using iloc"
},
{
"code": null,
"e": 503,
"s": 463,
"text": "through the creation of a new DataFrame"
},
{
"code": null,
"e": 688,
"s": 503,
"text": "Additionally, we will discuss when to use one method over the other, based on your specific use-case and whether you need to generate a view or a copy of the original DataFrame object."
},
{
"code": null,
"e": 814,
"s": 688,
"text": "First, letβs create an example DataFrame that weβll reference throughout this article in order to demonstrate a few concepts."
},
{
"code": null,
"e": 1071,
"s": 814,
"text": "import pandas pddf = pd.DataFrame({ 'colA':[1, 2, 3], 'colB': ['a', 'b', 'c'], 'colC': [True, False, True], 'colD': [1.0, 2.0, 3.0],})print(df) colA colB colC colD0 1 a True 1.01 2 b False 2.02 3 c True 3.0"
},
{
"code": null,
"e": 1287,
"s": 1071,
"text": "The first option you have when comes to select multiple columns from an existing pandas DataFrame is the use of basic indexing. This approach is usually useful when you know precisely which columns you want to keep."
},
{
"code": null,
"e": 1500,
"s": 1287,
"text": "Therefore, you can take a copy of the original DataFrame containing only those columns by passing the list with the names using the [] notation which is equivalent to __getitem__ implementation in Python classes."
},
{
"code": null,
"e": 1601,
"s": 1500,
"text": "df_result = df[['colA', 'colD']]print(df_result) colA colD0 1 1.01 2 2.02 3 3.0"
},
{
"code": null,
"e": 1712,
"s": 1601,
"text": "If you want to learn more about how indexing and slicing works in Python, make sure to read the article below."
},
{
"code": null,
"e": 1735,
"s": 1712,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1970,
"s": 1735,
"text": "Alternatively, if you want to reference column indices instead of column names and slice the original DataFrame (for instance if you want to keep say the first two columns but you donβt really know the column names), you can use iloc."
},
{
"code": null,
"e": 2062,
"s": 1970,
"text": "df_result = df.iloc[:, 0:2]print(df_result) colA colB0 1 a1 2 b2 3 c"
},
{
"code": null,
"e": 2381,
"s": 2062,
"text": "Note that the above operation, will return a view of the original DataFrame. This means that the view will contain only a chunk of the original DataFrame but it will still point to the same locations in memory. Therefore, if you modify the sliced object (df_result), then this may also effect the original object (df)."
},
{
"code": null,
"e": 2488,
"s": 2381,
"text": "If you wish to slice the DataFrame but get a copy of the original object instead, then simply call copy():"
},
{
"code": null,
"e": 2523,
"s": 2488,
"text": "df_result = df.iloc[:, 0:2].copy()"
},
{
"code": null,
"e": 2797,
"s": 2523,
"text": "Now if you want to slice the original DataFrame using the actual column names, then you can use the loc method. For instance, if you want to get the first three columns, you can do so with loc by referencing the first and last name of the range of columns you want to keep:"
},
{
"code": null,
"e": 2926,
"s": 2797,
"text": "df_result = df.loc[:, 'colA':'colC']print(df_result) colA colB colC0 1 a True1 2 b False2 3 c True"
},
{
"code": null,
"e": 3094,
"s": 2926,
"text": "At this point you may want to read about the differences between loc and iloc in Pandas and clarify which one to use based on your specific requirements and use-cases."
},
{
"code": null,
"e": 3117,
"s": 3094,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3248,
"s": 3117,
"text": "Finally, you can even create a new DataFrame using only a subset of the columns included in the original DataFrame as shown below."
},
{
"code": null,
"e": 3375,
"s": 3248,
"text": "df_result = pd.DataFrame(df, columns=['colA', 'colC'])print(df_result) colA colC0 1 True1 2 False2 3 True"
},
{
"code": null,
"e": 3732,
"s": 3375,
"text": "In todayβs short guide we showcased a few possible ways for selecting multiple columns from a pandas DataFrame. We discussed how to do so using simple indexing, iloc, loc and through the creation of a new DataFrame. Note that some of the methods discussed in this article, may generate a view of the original DataFrame and thus you should be extra careful."
},
{
"code": null,
"e": 3849,
"s": 3732,
"text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read."
}
]
|
Machine Learning in JavaScript. Is it easier? difficult? or simply fun? | by Rajat S | Towards Data Science | If you have tried Machine Learning before, you are probably thinking that there is a huge typo in the articleβs title and that I meant to write Python or R in place of JavaScript.
And if you are a JavaScript developer, you probably know that since the creation of NodeJS, almost anything is possible in JavaScript. You can use React and Vue to build user interfaces, Node/Express for all the βserversideβ stuff, and D3 for data visualization (another area that gets dominated by Python and R).
In this post, I will show you how to we can perform Machine Learning with JavaScript! We will start by defining what Machine Learning is, get a quick intro to TensorFlow and TensorFlow.js, and then build a very simple image classification application using React and ML5.js!
Unless you have been living under a rock all this time, you have probably heard words such as Machine Learning (ML) and Artificial Intelligence (AI). Even if you are not a very science-oriented person, you have probably seen those Microsoft advertisements on TV and the Internet where Common talks about all the amazing stuff that Microsoft is doing.
The truth is, almost everyone has used Machine Learning and Artificial Intelligence at one point in their life. Scratch that, everyone uses ML and AI every day in their life. From asking Siri and Alexa to play some song to using navigation apps on the phone to get the quickest route to work, itβs all ML and AI.
But how do we define these two terms? Letβs focus on ML since it is the main topic of this article. In the simplest words, Machine Learning is:
A field of study that allows computer systems to do something without giving it any specific instructions to do so.
As a developer, you are to write code in a particular way. Your client or manager tells what they want the desired output to be, and you try to write some code that will get you that output. But in Machine Learning, you only know the problem that needs to be solved! You βteachβ your computer a few things and then sit back and see what astounding results you get from the system!
The question to answer is: How do we do Machine Learning? Python programmers use packages like scikit-learn and Googleβs amazing TensorFlow to perform Machine Learning. But last year (2018), Google released the JavaScript version of TensorFlow elegantly called TensorFlow.js!
But why should one do Machine Learning in JavaScript? Well, first of all, the Python way of Machine Learning required developers to keep the Machine Learning code on the server, and then use JavaScript to allow users to access the models on the client. And here we come across a potential problem. If your machine learning model gets too popular and a lot of users want to access it, there is a good chance that your server can crash!
But if we use Machine Learning, not only are we staying the JavaScript environment for both Machine Learning code and the user interface code, the model will stay on the client-side itself! Also, Machine Learning models are mostly used by financial companies. So a client-side ML model would mean that your data stays private.
You now have some basic knowledge of ML, and why doing it in JavaScript can be a good idea. But ML is one of those things that you will understand better by trying it out. If you would like to read more about Machine Learning, check out this other post that I had written a while back:
medium.com
In this section, we will build a Machine Learning app with React that can perform some very good image classification.
SideBar: The Machine Learning process consists of two steps: Training and Testing. Training involves giving a huge amount of data to the model, which the model will then process and recognize different patterns, which the model will then use to make future predictions.
Since we are building an image classification model, we would need to send thousands of images to the model to process before we can make any predictions. Images need to be relatable to each other in some way, and I honestly donβt have so many pictures (I am a shy person). Also, Machine Learning in JavaScript is still new to me. So as a shortcut, I am going to use one of the pre-trained models.
Before we can start coding, make sure that you have the following things installed on your system:
Node β We will need this to install different packagesCode Editor β Any good editor will do. I personally like to use VSCode
Node β We will need this to install different packages
Code Editor β Any good editor will do. I personally like to use VSCode
The next is to build a boilerplate React application. To do this, open a command terminal and run the following command:
$ npx create-react-app ml-in-js
This command will create a folder named ml-in-js and build a start app in your system. Next, go back to your command terminal and run the following commands:
$ cd ml-in-js$ npm run start
The first command is pretty straightforward. The real magic happens in the second one. The npm run start command creates a local development level of your system and automatically opens it on the browser like this:
This starter app has no idea what Machine Learning or Tensorflow is. To solve this issue, we need to install the Tensorflow.js package. For Python developers, you would need to do a pip install tensorflow once on your system and be free to use the package anywhere and in project. But when it comes to JavaScript, you need to run the npm install command for every project.
But instead of installing Tensorflow.js (TFJS) library in the app, we will install another library called ML5.js. This library is like a better version of TFJS that makes it much easier for us to do Machine Learning on the client-side. So letβs install this library like this:
$ npm install --save ml5
If you want to make sure that the library was successfully installed, go to the App.js file in the src folder and write the following code:
import React, {Component} from 'react';import * as ml5 from 'ml5';export default class App extends Component { render() { return ( <div> <h1>{ml5.version}</h1> </div> ) }}
If you go back to the browser, you will see a big 0.4.1 printed on the screen. This number can be a little different for you based on the latest version of ML5.js. As long as you see a number printed on the screen, you can rest assured that your ML5 library was successfully installed.
With that, we are done with the installation part. Now we need to create a function that can take in an image and classify it using a pre-trained model. To do this, write the following code inside the App component:
classifyImage = async () => { const classifier = await ml5.imageClassifier('MobileNet') this.setState({ready: true}) const image = document.getElementById("image") classifier.predict(image, 1, (err, results) => { this.setState({ predictionLabel: results[0].label, predictionConfidence: results[0].confidence, predicted: true }) })}
Here we have an asynchronous function called classifyImage. Inside this function, we first define our Image Classifier by loading the MobileNet data as the training set. Once this classifier is ready, we set the ready state to true. Then, we select the image inserted by the user and pass it to the classfier and run the predict function. We save the highest predictionβs label and confidence level in the state object.
Our entire App.js file will look something like this:
Time to test the model. To do this, I will give the following image as to the app:
When I press on the Classify button, the app runs the classifyImage function and after some time you will get the following result:
The app is 63.99456858634949% sure that this is bucket
Not what I was expecting. The reason for this incorrect result can be a number of things. The most important of them is that the MobileNet is not the proper dataset to classify this image.
Letβs try some other image. Maybe an animal:
Clicking on the Classify button again, and I get π€:
The app is 90.23570418357849% sure that this is Border collie
Wow! 90% confidence that the image has a Border Collie, which is a type of Dog!
If you have stuck with me till now, then you have just done some Machine Learning in JavaScript! Go ahead and pat yourself on your back!
But you and I are still a long way from being ML experts. In this article, we did the test part of Machine Learning and used a pre-trained model. The real fun starts when you take your own raw data and try to use it to train your data.
That is what I am going to try to do now. So wish me luck! If I succeed then I will write my next article on it.
As always, I would like to thank you all for reading my long articles. I am still new to Machine Learning in JavaScript. So if you think I have made any mistake in this post, or if I could have done something differently, then please do comment about it.
You can take a look at the entire source code of the React App here: | [
{
"code": null,
"e": 351,
"s": 171,
"text": "If you have tried Machine Learning before, you are probably thinking that there is a huge typo in the articleβs title and that I meant to write Python or R in place of JavaScript."
},
{
"code": null,
"e": 665,
"s": 351,
"text": "And if you are a JavaScript developer, you probably know that since the creation of NodeJS, almost anything is possible in JavaScript. You can use React and Vue to build user interfaces, Node/Express for all the βserversideβ stuff, and D3 for data visualization (another area that gets dominated by Python and R)."
},
{
"code": null,
"e": 940,
"s": 665,
"text": "In this post, I will show you how to we can perform Machine Learning with JavaScript! We will start by defining what Machine Learning is, get a quick intro to TensorFlow and TensorFlow.js, and then build a very simple image classification application using React and ML5.js!"
},
{
"code": null,
"e": 1291,
"s": 940,
"text": "Unless you have been living under a rock all this time, you have probably heard words such as Machine Learning (ML) and Artificial Intelligence (AI). Even if you are not a very science-oriented person, you have probably seen those Microsoft advertisements on TV and the Internet where Common talks about all the amazing stuff that Microsoft is doing."
},
{
"code": null,
"e": 1604,
"s": 1291,
"text": "The truth is, almost everyone has used Machine Learning and Artificial Intelligence at one point in their life. Scratch that, everyone uses ML and AI every day in their life. From asking Siri and Alexa to play some song to using navigation apps on the phone to get the quickest route to work, itβs all ML and AI."
},
{
"code": null,
"e": 1748,
"s": 1604,
"text": "But how do we define these two terms? Letβs focus on ML since it is the main topic of this article. In the simplest words, Machine Learning is:"
},
{
"code": null,
"e": 1864,
"s": 1748,
"text": "A field of study that allows computer systems to do something without giving it any specific instructions to do so."
},
{
"code": null,
"e": 2245,
"s": 1864,
"text": "As a developer, you are to write code in a particular way. Your client or manager tells what they want the desired output to be, and you try to write some code that will get you that output. But in Machine Learning, you only know the problem that needs to be solved! You βteachβ your computer a few things and then sit back and see what astounding results you get from the system!"
},
{
"code": null,
"e": 2521,
"s": 2245,
"text": "The question to answer is: How do we do Machine Learning? Python programmers use packages like scikit-learn and Googleβs amazing TensorFlow to perform Machine Learning. But last year (2018), Google released the JavaScript version of TensorFlow elegantly called TensorFlow.js!"
},
{
"code": null,
"e": 2956,
"s": 2521,
"text": "But why should one do Machine Learning in JavaScript? Well, first of all, the Python way of Machine Learning required developers to keep the Machine Learning code on the server, and then use JavaScript to allow users to access the models on the client. And here we come across a potential problem. If your machine learning model gets too popular and a lot of users want to access it, there is a good chance that your server can crash!"
},
{
"code": null,
"e": 3283,
"s": 2956,
"text": "But if we use Machine Learning, not only are we staying the JavaScript environment for both Machine Learning code and the user interface code, the model will stay on the client-side itself! Also, Machine Learning models are mostly used by financial companies. So a client-side ML model would mean that your data stays private."
},
{
"code": null,
"e": 3569,
"s": 3283,
"text": "You now have some basic knowledge of ML, and why doing it in JavaScript can be a good idea. But ML is one of those things that you will understand better by trying it out. If you would like to read more about Machine Learning, check out this other post that I had written a while back:"
},
{
"code": null,
"e": 3580,
"s": 3569,
"text": "medium.com"
},
{
"code": null,
"e": 3699,
"s": 3580,
"text": "In this section, we will build a Machine Learning app with React that can perform some very good image classification."
},
{
"code": null,
"e": 3969,
"s": 3699,
"text": "SideBar: The Machine Learning process consists of two steps: Training and Testing. Training involves giving a huge amount of data to the model, which the model will then process and recognize different patterns, which the model will then use to make future predictions."
},
{
"code": null,
"e": 4367,
"s": 3969,
"text": "Since we are building an image classification model, we would need to send thousands of images to the model to process before we can make any predictions. Images need to be relatable to each other in some way, and I honestly donβt have so many pictures (I am a shy person). Also, Machine Learning in JavaScript is still new to me. So as a shortcut, I am going to use one of the pre-trained models."
},
{
"code": null,
"e": 4466,
"s": 4367,
"text": "Before we can start coding, make sure that you have the following things installed on your system:"
},
{
"code": null,
"e": 4591,
"s": 4466,
"text": "Node β We will need this to install different packagesCode Editor β Any good editor will do. I personally like to use VSCode"
},
{
"code": null,
"e": 4646,
"s": 4591,
"text": "Node β We will need this to install different packages"
},
{
"code": null,
"e": 4717,
"s": 4646,
"text": "Code Editor β Any good editor will do. I personally like to use VSCode"
},
{
"code": null,
"e": 4838,
"s": 4717,
"text": "The next is to build a boilerplate React application. To do this, open a command terminal and run the following command:"
},
{
"code": null,
"e": 4870,
"s": 4838,
"text": "$ npx create-react-app ml-in-js"
},
{
"code": null,
"e": 5028,
"s": 4870,
"text": "This command will create a folder named ml-in-js and build a start app in your system. Next, go back to your command terminal and run the following commands:"
},
{
"code": null,
"e": 5057,
"s": 5028,
"text": "$ cd ml-in-js$ npm run start"
},
{
"code": null,
"e": 5272,
"s": 5057,
"text": "The first command is pretty straightforward. The real magic happens in the second one. The npm run start command creates a local development level of your system and automatically opens it on the browser like this:"
},
{
"code": null,
"e": 5645,
"s": 5272,
"text": "This starter app has no idea what Machine Learning or Tensorflow is. To solve this issue, we need to install the Tensorflow.js package. For Python developers, you would need to do a pip install tensorflow once on your system and be free to use the package anywhere and in project. But when it comes to JavaScript, you need to run the npm install command for every project."
},
{
"code": null,
"e": 5922,
"s": 5645,
"text": "But instead of installing Tensorflow.js (TFJS) library in the app, we will install another library called ML5.js. This library is like a better version of TFJS that makes it much easier for us to do Machine Learning on the client-side. So letβs install this library like this:"
},
{
"code": null,
"e": 5947,
"s": 5922,
"text": "$ npm install --save ml5"
},
{
"code": null,
"e": 6087,
"s": 5947,
"text": "If you want to make sure that the library was successfully installed, go to the App.js file in the src folder and write the following code:"
},
{
"code": null,
"e": 6284,
"s": 6087,
"text": "import React, {Component} from 'react';import * as ml5 from 'ml5';export default class App extends Component { render() { return ( <div> <h1>{ml5.version}</h1> </div> ) }}"
},
{
"code": null,
"e": 6570,
"s": 6284,
"text": "If you go back to the browser, you will see a big 0.4.1 printed on the screen. This number can be a little different for you based on the latest version of ML5.js. As long as you see a number printed on the screen, you can rest assured that your ML5 library was successfully installed."
},
{
"code": null,
"e": 6786,
"s": 6570,
"text": "With that, we are done with the installation part. Now we need to create a function that can take in an image and classify it using a pre-trained model. To do this, write the following code inside the App component:"
},
{
"code": null,
"e": 7144,
"s": 6786,
"text": "classifyImage = async () => { const classifier = await ml5.imageClassifier('MobileNet') this.setState({ready: true}) const image = document.getElementById(\"image\") classifier.predict(image, 1, (err, results) => { this.setState({ predictionLabel: results[0].label, predictionConfidence: results[0].confidence, predicted: true }) })}"
},
{
"code": null,
"e": 7564,
"s": 7144,
"text": "Here we have an asynchronous function called classifyImage. Inside this function, we first define our Image Classifier by loading the MobileNet data as the training set. Once this classifier is ready, we set the ready state to true. Then, we select the image inserted by the user and pass it to the classfier and run the predict function. We save the highest predictionβs label and confidence level in the state object."
},
{
"code": null,
"e": 7618,
"s": 7564,
"text": "Our entire App.js file will look something like this:"
},
{
"code": null,
"e": 7701,
"s": 7618,
"text": "Time to test the model. To do this, I will give the following image as to the app:"
},
{
"code": null,
"e": 7833,
"s": 7701,
"text": "When I press on the Classify button, the app runs the classifyImage function and after some time you will get the following result:"
},
{
"code": null,
"e": 7888,
"s": 7833,
"text": "The app is 63.99456858634949% sure that this is bucket"
},
{
"code": null,
"e": 8077,
"s": 7888,
"text": "Not what I was expecting. The reason for this incorrect result can be a number of things. The most important of them is that the MobileNet is not the proper dataset to classify this image."
},
{
"code": null,
"e": 8122,
"s": 8077,
"text": "Letβs try some other image. Maybe an animal:"
},
{
"code": null,
"e": 8174,
"s": 8122,
"text": "Clicking on the Classify button again, and I get π€:"
},
{
"code": null,
"e": 8236,
"s": 8174,
"text": "The app is 90.23570418357849% sure that this is Border collie"
},
{
"code": null,
"e": 8316,
"s": 8236,
"text": "Wow! 90% confidence that the image has a Border Collie, which is a type of Dog!"
},
{
"code": null,
"e": 8453,
"s": 8316,
"text": "If you have stuck with me till now, then you have just done some Machine Learning in JavaScript! Go ahead and pat yourself on your back!"
},
{
"code": null,
"e": 8689,
"s": 8453,
"text": "But you and I are still a long way from being ML experts. In this article, we did the test part of Machine Learning and used a pre-trained model. The real fun starts when you take your own raw data and try to use it to train your data."
},
{
"code": null,
"e": 8802,
"s": 8689,
"text": "That is what I am going to try to do now. So wish me luck! If I succeed then I will write my next article on it."
},
{
"code": null,
"e": 9057,
"s": 8802,
"text": "As always, I would like to thank you all for reading my long articles. I am still new to Machine Learning in JavaScript. So if you think I have made any mistake in this post, or if I could have done something differently, then please do comment about it."
}
]
|
Employee Management System using Python - GeeksforGeeks | 06 Oct, 2021
The task is to create a Database-driven Employee Management System in Python that will store the information in the MySQL Database. The script will contain the following operations :
Add Employee
Remove Employee
Promote Employee
Display Employees
The idea is that we perform different changes in our Employee Record by using different functions for example the Add_Employee will insert a new row in our Employee, also, we will create a Remove Employee Function which will delete the record of any particular existing employee in our Employee table. This System works on the concepts of taking the information from the database making required changes in the fetched data and applying the changes in the record which we will see in our Promote Employee System. We can also have the information about all the existing employees by using the Display Employee function. The main advantage of connecting our program to the database is that the information becomes lossless even after closing our program a number of times.
For creating the Employee Management System in Python that uses MySQL database we need to connect Python with MySQL.
For making a connection we need to install mysqlconnector which can be done by writing the following command in the command prompt on Windows.
pip install mysqlconnector
Now after successful installation of mysqlconnector we can connect MySQL with Python which can be done by writing the following code
Python3
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", password="password", database="emp")
Now we are Done with the connections, so we can focus on our Employee Management System
Table in Use:
Employee Record
The idea is that we keep all the information about the Employee in the above table and manipulate the table whenever required. So now we will look at the working of each operation in detail.
The check employee function takes employee id as a parameter and checks whether any employee with given id exists in the employee details record or not. For checking this it uses cursor.rowcount() function which counts the number of rows that match with given details. It is a utility function, and we will see its use in later operations like Add employee function, etc.
Program:
Python3
# Function To Check if Employee with# given Id Exist or Not def check_employee(employee_id): # Query to select all Rows f # rom employee Table sql = 'select * from empd where id=%s' # making cursor buffered to make # rowcount method work properly c = con.cursor(buffered=True) data = (employee_id,) # Executing the SQL Query c.execute(sql, data) # rowcount method to find # number of rows with given values r = c.rowcount if r == 1: return True else: return False
The Add Employee function will ask for the Employee Id and uses the check employee function to check whether the employee to be added already exist in our record or not if employee details do not already exist then it asks for details of the employee to be added like Employee Name, Post of Employee and Salary of the employee. Now after getting all such details from the user of that system it simply inserts the information in our Employee details table.
Program:
Python3
# Function to mAdd_Employee def Add_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Already Exist or Not if(check_employee(Id) == True): print("Employee aready exists\nTry Again\n") menu() else: Name = input("Enter Employee Name : ") Post = input("Enter Employee Post : ") Salary = input("Enter Employee Salary : ") data = (Id, Name, Post, Salary) # Inserting Employee details in the Employee # Table sql = 'insert into empd values(%s,%s,%s,%s)' c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in the table con.commit() print("Employee Added Successfully ") menu()
The Remove Employee Function will simply ask for Id of the employee to be removed because Id is Primary key in our Employee Details Record as there can be two employees with the same name, but they must have a unique id. The Remove Employee function uses the check employee function to check whether the employee to be removed exists in our record or not if employee details exist then after getting a valid employee id it deletes the record corresponding to that employee id.
Program
Python3
# Function to Remove Employee with given Iddef Remove_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Exist or Not if(check_employee(Id) == False): print("Employee does not exists\nTry Again\n") menu() else: # Query to Delete Employee from Table sql = 'delete from empd where id=%s' data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Removed") menu()
The Promote Employee function will ask for the Employee Id and uses the check employee function to check whether the employee to be Promoted exist in our record or not if employee details exist then it will ask for the amount by which his salary is to be increased. After getting the valid details it increases the salary of the employee with the given id by the given amount.
Program
Python3
# Function to Promote Employeedef Promote_Employee(): Id = int(input("Enter Employ's Id")) # Checking if Employee with given Id # Exist or Not if(check_employee(Id) == False): print("Employee does not exists\nTry Again\n") menu() else: Amount = int(input("Enter increase in Salary")) # Query to Fetch Salary of Employee with # given Id sql = 'select salary from empd where id=%s' data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # Fetching Salary of Employee with given Id r = c.fetchone() t = r[0]+Amount # Query to Update Salary of Employee with # given Id sql = 'update empd set salary=%s where id=%s' d = (t, Id) # Executing the SQL Query c.execute(sql, d) # commit() method to make changes in the table con.commit() print("Employee Promoted") menu()
The Display Employees function is simply a select query of SQL which fetches all the records stored in the employee details table and prints them line by line.
Program:
Python3
# Function to Display All Employees# from Employee Table def Display_Employees(): # query to select all rows from # Employee Table sql = 'select * from empd' c = con.cursor() # Executing the SQL Query c.execute(sql) # Fetching all details of all the # Employees r = c.fetchall() for i in r: print("Employee Id : ", i[0]) print("Employee Name : ", i[1]) print("Employee Post : ", i[2]) print("Employee Salary : ", i[3]) print("-----------------------------\ -------------------------------------\ -----------------------------------") menu()
The Menu function displays the menu to the user and asks the user to enter his choice for performing operations like Add employee, Remove employee, etc.
Program
Python3
# menu function to display the menudef menu(): print("Welcome to Employee Management Record") print("Press ") print("1 to Add Employee") print("2 to Remove Employee ") print("3 to Promote Employee") print("4 to Display Employees") print("5 to Exit") # Taking choice from user ch = int(input("Enter your Choice ")) if ch == 1: Add_Employ() elif ch == 2: Remove_Employ() elif ch == 3: Promote_Employee() elif ch == 4: Display_Employees() elif ch == 5: exit(0) else: print("Invalid Choice") menu()
Complete Code:
Python3
# importing mysql connectorimport mysql.connector # making Connectioncon = mysql.connector.connect( host="localhost", user="root", password="password", database="emp") # Function to mAdd_Employeedef Add_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Already Exist or Not if(check_employee(Id) == True): print("Employee aready exists\nTry Again\n") menu() else: Name = input("Enter Employee Name : ") Post = input("Enter Employee Post : ") Salary = input("Enter Employee Salary : ") data = (Id, Name, Post, Salary) # Inserting Employee details in # the Employee Table sql = 'insert into empd values(%s,%s,%s,%s)' c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Added Successfully ") menu() # Function to Promote Employeedef Promote_Employee(): Id = int(input("Enter Employ's Id")) # Checking if Employee with given Id # Exist or Not if(check_employee(Id) == False): print("Employee does not exists\nTry Again\n") menu() else: Amount = int(input("Enter increase in Salary")) # Query to Fetch Salary of Employee # with given Id sql = 'select salary from empd where id=%s' data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # Fetching Salary of Employee with given Id r = c.fetchone() t = r[0]+Amount # Query to Update Salary of Employee with # given Id sql = 'update empd set salary=%s where id=%s' d = (t, Id) # Executing the SQL Query c.execute(sql, d) # commit() method to make changes in the table con.commit() print("Employee Promoted") menu() # Function to Remove Employee with given Iddef Remove_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id Exist # or Not if(check_employee(Id) == False): print("Employee does not exists\nTry Again\n") menu() else: # Query to Delete Employee from Table sql = 'delete from empd where id=%s' data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Removed") menu() # Function To Check if Employee with# given Id Exist or Notdef check_employee(employee_id): # Query to select all Rows f # rom employee Table sql = 'select * from empd where id=%s' # making cursor buffered to make # rowcount method work properly c = con.cursor(buffered=True) data = (employee_id,) # Executing the SQL Query c.execute(sql, data) # rowcount method to find # number of rows with given values r = c.rowcount if r == 1: return True else: return False # Function to Display All Employees# from Employee Tabledef Display_Employees(): # query to select all rows from # Employee Table sql = 'select * from empd' c = con.cursor() # Executing the SQL Query c.execute(sql) # Fetching all details of all the # Employees r = c.fetchall() for i in r: print("Employee Id : ", i[0]) print("Employee Name : ", i[1]) print("Employee Post : ", i[2]) print("Employee Salary : ", i[3]) print("---------------------\ -----------------------------\ ------------------------------\ ---------------------") menu() # menu function to display menudef menu(): print("Welcome to Employee Management Record") print("Press ") print("1 to Add Employee") print("2 to Remove Employee ") print("3 to Promote Employee") print("4 to Display Employees") print("5 to Exit") ch = int(input("Enter your Choice ")) if ch == 1: Add_Employ() elif ch == 2: Remove_Employ() elif ch == 3: Promote_Employee() elif ch == 4: Display_Employees() elif ch == 5: exit(0) else: print("Invalid Choice") menu() # Calling menu functionmenu()
Output
anikakapoor
kashishsoda
Python-mySQL
Python-projects
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions | [
{
"code": null,
"e": 23925,
"s": 23897,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24108,
"s": 23925,
"text": "The task is to create a Database-driven Employee Management System in Python that will store the information in the MySQL Database. The script will contain the following operations :"
},
{
"code": null,
"e": 24121,
"s": 24108,
"text": "Add Employee"
},
{
"code": null,
"e": 24137,
"s": 24121,
"text": "Remove Employee"
},
{
"code": null,
"e": 24154,
"s": 24137,
"text": "Promote Employee"
},
{
"code": null,
"e": 24172,
"s": 24154,
"text": "Display Employees"
},
{
"code": null,
"e": 24943,
"s": 24172,
"text": "The idea is that we perform different changes in our Employee Record by using different functions for example the Add_Employee will insert a new row in our Employee, also, we will create a Remove Employee Function which will delete the record of any particular existing employee in our Employee table. This System works on the concepts of taking the information from the database making required changes in the fetched data and applying the changes in the record which we will see in our Promote Employee System. We can also have the information about all the existing employees by using the Display Employee function. The main advantage of connecting our program to the database is that the information becomes lossless even after closing our program a number of times."
},
{
"code": null,
"e": 25060,
"s": 24943,
"text": "For creating the Employee Management System in Python that uses MySQL database we need to connect Python with MySQL."
},
{
"code": null,
"e": 25203,
"s": 25060,
"text": "For making a connection we need to install mysqlconnector which can be done by writing the following command in the command prompt on Windows."
},
{
"code": null,
"e": 25230,
"s": 25203,
"text": "pip install mysqlconnector"
},
{
"code": null,
"e": 25364,
"s": 25230,
"text": "Now after successful installation of mysqlconnector we can connect MySQL with Python which can be done by writing the following code "
},
{
"code": null,
"e": 25372,
"s": 25364,
"text": "Python3"
},
{
"code": "import mysql.connector con = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"password\", database=\"emp\")",
"e": 25498,
"s": 25372,
"text": null
},
{
"code": null,
"e": 25587,
"s": 25498,
"text": "Now we are Done with the connections, so we can focus on our Employee Management System "
},
{
"code": null,
"e": 25601,
"s": 25587,
"text": "Table in Use:"
},
{
"code": null,
"e": 25617,
"s": 25601,
"text": "Employee Record"
},
{
"code": null,
"e": 25808,
"s": 25617,
"text": "The idea is that we keep all the information about the Employee in the above table and manipulate the table whenever required. So now we will look at the working of each operation in detail."
},
{
"code": null,
"e": 26180,
"s": 25808,
"text": "The check employee function takes employee id as a parameter and checks whether any employee with given id exists in the employee details record or not. For checking this it uses cursor.rowcount() function which counts the number of rows that match with given details. It is a utility function, and we will see its use in later operations like Add employee function, etc."
},
{
"code": null,
"e": 26189,
"s": 26180,
"text": "Program:"
},
{
"code": null,
"e": 26197,
"s": 26189,
"text": "Python3"
},
{
"code": "# Function To Check if Employee with# given Id Exist or Not def check_employee(employee_id): # Query to select all Rows f # rom employee Table sql = 'select * from empd where id=%s' # making cursor buffered to make # rowcount method work properly c = con.cursor(buffered=True) data = (employee_id,) # Executing the SQL Query c.execute(sql, data) # rowcount method to find # number of rows with given values r = c.rowcount if r == 1: return True else: return False",
"e": 26726,
"s": 26197,
"text": null
},
{
"code": null,
"e": 27183,
"s": 26726,
"text": "The Add Employee function will ask for the Employee Id and uses the check employee function to check whether the employee to be added already exist in our record or not if employee details do not already exist then it asks for details of the employee to be added like Employee Name, Post of Employee and Salary of the employee. Now after getting all such details from the user of that system it simply inserts the information in our Employee details table."
},
{
"code": null,
"e": 27192,
"s": 27183,
"text": "Program:"
},
{
"code": null,
"e": 27200,
"s": 27192,
"text": "Python3"
},
{
"code": "# Function to mAdd_Employee def Add_Employ(): Id = input(\"Enter Employee Id : \") # Checking if Employee with given Id # Already Exist or Not if(check_employee(Id) == True): print(\"Employee aready exists\\nTry Again\\n\") menu() else: Name = input(\"Enter Employee Name : \") Post = input(\"Enter Employee Post : \") Salary = input(\"Enter Employee Salary : \") data = (Id, Name, Post, Salary) # Inserting Employee details in the Employee # Table sql = 'insert into empd values(%s,%s,%s,%s)' c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in the table con.commit() print(\"Employee Added Successfully \") menu()",
"e": 27988,
"s": 27200,
"text": null
},
{
"code": null,
"e": 28465,
"s": 27988,
"text": "The Remove Employee Function will simply ask for Id of the employee to be removed because Id is Primary key in our Employee Details Record as there can be two employees with the same name, but they must have a unique id. The Remove Employee function uses the check employee function to check whether the employee to be removed exists in our record or not if employee details exist then after getting a valid employee id it deletes the record corresponding to that employee id."
},
{
"code": null,
"e": 28473,
"s": 28465,
"text": "Program"
},
{
"code": null,
"e": 28481,
"s": 28473,
"text": "Python3"
},
{
"code": "# Function to Remove Employee with given Iddef Remove_Employ(): Id = input(\"Enter Employee Id : \") # Checking if Employee with given Id # Exist or Not if(check_employee(Id) == False): print(\"Employee does not exists\\nTry Again\\n\") menu() else: # Query to Delete Employee from Table sql = 'delete from empd where id=%s' data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print(\"Employee Removed\") menu()",
"e": 29096,
"s": 28481,
"text": null
},
{
"code": null,
"e": 29473,
"s": 29096,
"text": "The Promote Employee function will ask for the Employee Id and uses the check employee function to check whether the employee to be Promoted exist in our record or not if employee details exist then it will ask for the amount by which his salary is to be increased. After getting the valid details it increases the salary of the employee with the given id by the given amount."
},
{
"code": null,
"e": 29481,
"s": 29473,
"text": "Program"
},
{
"code": null,
"e": 29489,
"s": 29481,
"text": "Python3"
},
{
"code": "# Function to Promote Employeedef Promote_Employee(): Id = int(input(\"Enter Employ's Id\")) # Checking if Employee with given Id # Exist or Not if(check_employee(Id) == False): print(\"Employee does not exists\\nTry Again\\n\") menu() else: Amount = int(input(\"Enter increase in Salary\")) # Query to Fetch Salary of Employee with # given Id sql = 'select salary from empd where id=%s' data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # Fetching Salary of Employee with given Id r = c.fetchone() t = r[0]+Amount # Query to Update Salary of Employee with # given Id sql = 'update empd set salary=%s where id=%s' d = (t, Id) # Executing the SQL Query c.execute(sql, d) # commit() method to make changes in the table con.commit() print(\"Employee Promoted\") menu()",
"e": 30456,
"s": 29489,
"text": null
},
{
"code": null,
"e": 30616,
"s": 30456,
"text": "The Display Employees function is simply a select query of SQL which fetches all the records stored in the employee details table and prints them line by line."
},
{
"code": null,
"e": 30625,
"s": 30616,
"text": "Program:"
},
{
"code": null,
"e": 30633,
"s": 30625,
"text": "Python3"
},
{
"code": "# Function to Display All Employees# from Employee Table def Display_Employees(): # query to select all rows from # Employee Table sql = 'select * from empd' c = con.cursor() # Executing the SQL Query c.execute(sql) # Fetching all details of all the # Employees r = c.fetchall() for i in r: print(\"Employee Id : \", i[0]) print(\"Employee Name : \", i[1]) print(\"Employee Post : \", i[2]) print(\"Employee Salary : \", i[3]) print(\"-----------------------------\\ -------------------------------------\\ -----------------------------------\") menu()",
"e": 31271,
"s": 30633,
"text": null
},
{
"code": null,
"e": 31429,
"s": 31276,
"text": "The Menu function displays the menu to the user and asks the user to enter his choice for performing operations like Add employee, Remove employee, etc."
},
{
"code": null,
"e": 31439,
"s": 31431,
"text": "Program"
},
{
"code": null,
"e": 31449,
"s": 31441,
"text": "Python3"
},
{
"code": "# menu function to display the menudef menu(): print(\"Welcome to Employee Management Record\") print(\"Press \") print(\"1 to Add Employee\") print(\"2 to Remove Employee \") print(\"3 to Promote Employee\") print(\"4 to Display Employees\") print(\"5 to Exit\") # Taking choice from user ch = int(input(\"Enter your Choice \")) if ch == 1: Add_Employ() elif ch == 2: Remove_Employ() elif ch == 3: Promote_Employee() elif ch == 4: Display_Employees() elif ch == 5: exit(0) else: print(\"Invalid Choice\") menu()",
"e": 32088,
"s": 31449,
"text": null
},
{
"code": null,
"e": 32103,
"s": 32088,
"text": "Complete Code:"
},
{
"code": null,
"e": 32111,
"s": 32103,
"text": "Python3"
},
{
"code": "# importing mysql connectorimport mysql.connector # making Connectioncon = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"password\", database=\"emp\") # Function to mAdd_Employeedef Add_Employ(): Id = input(\"Enter Employee Id : \") # Checking if Employee with given Id # Already Exist or Not if(check_employee(Id) == True): print(\"Employee aready exists\\nTry Again\\n\") menu() else: Name = input(\"Enter Employee Name : \") Post = input(\"Enter Employee Post : \") Salary = input(\"Enter Employee Salary : \") data = (Id, Name, Post, Salary) # Inserting Employee details in # the Employee Table sql = 'insert into empd values(%s,%s,%s,%s)' c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print(\"Employee Added Successfully \") menu() # Function to Promote Employeedef Promote_Employee(): Id = int(input(\"Enter Employ's Id\")) # Checking if Employee with given Id # Exist or Not if(check_employee(Id) == False): print(\"Employee does not exists\\nTry Again\\n\") menu() else: Amount = int(input(\"Enter increase in Salary\")) # Query to Fetch Salary of Employee # with given Id sql = 'select salary from empd where id=%s' data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # Fetching Salary of Employee with given Id r = c.fetchone() t = r[0]+Amount # Query to Update Salary of Employee with # given Id sql = 'update empd set salary=%s where id=%s' d = (t, Id) # Executing the SQL Query c.execute(sql, d) # commit() method to make changes in the table con.commit() print(\"Employee Promoted\") menu() # Function to Remove Employee with given Iddef Remove_Employ(): Id = input(\"Enter Employee Id : \") # Checking if Employee with given Id Exist # or Not if(check_employee(Id) == False): print(\"Employee does not exists\\nTry Again\\n\") menu() else: # Query to Delete Employee from Table sql = 'delete from empd where id=%s' data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print(\"Employee Removed\") menu() # Function To Check if Employee with# given Id Exist or Notdef check_employee(employee_id): # Query to select all Rows f # rom employee Table sql = 'select * from empd where id=%s' # making cursor buffered to make # rowcount method work properly c = con.cursor(buffered=True) data = (employee_id,) # Executing the SQL Query c.execute(sql, data) # rowcount method to find # number of rows with given values r = c.rowcount if r == 1: return True else: return False # Function to Display All Employees# from Employee Tabledef Display_Employees(): # query to select all rows from # Employee Table sql = 'select * from empd' c = con.cursor() # Executing the SQL Query c.execute(sql) # Fetching all details of all the # Employees r = c.fetchall() for i in r: print(\"Employee Id : \", i[0]) print(\"Employee Name : \", i[1]) print(\"Employee Post : \", i[2]) print(\"Employee Salary : \", i[3]) print(\"---------------------\\ -----------------------------\\ ------------------------------\\ ---------------------\") menu() # menu function to display menudef menu(): print(\"Welcome to Employee Management Record\") print(\"Press \") print(\"1 to Add Employee\") print(\"2 to Remove Employee \") print(\"3 to Promote Employee\") print(\"4 to Display Employees\") print(\"5 to Exit\") ch = int(input(\"Enter your Choice \")) if ch == 1: Add_Employ() elif ch == 2: Remove_Employ() elif ch == 3: Promote_Employee() elif ch == 4: Display_Employees() elif ch == 5: exit(0) else: print(\"Invalid Choice\") menu() # Calling menu functionmenu()",
"e": 36538,
"s": 32111,
"text": null
},
{
"code": null,
"e": 36545,
"s": 36538,
"text": "Output"
},
{
"code": null,
"e": 36557,
"s": 36545,
"text": "anikakapoor"
},
{
"code": null,
"e": 36569,
"s": 36557,
"text": "kashishsoda"
},
{
"code": null,
"e": 36582,
"s": 36569,
"text": "Python-mySQL"
},
{
"code": null,
"e": 36598,
"s": 36582,
"text": "Python-projects"
},
{
"code": null,
"e": 36605,
"s": 36598,
"text": "Python"
},
{
"code": null,
"e": 36703,
"s": 36605,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36712,
"s": 36703,
"text": "Comments"
},
{
"code": null,
"e": 36725,
"s": 36712,
"text": "Old Comments"
},
{
"code": null,
"e": 36761,
"s": 36725,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 36784,
"s": 36761,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 36823,
"s": 36784,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 36856,
"s": 36823,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 36905,
"s": 36856,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 36946,
"s": 36905,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 36962,
"s": 36946,
"text": "loops in python"
},
{
"code": null,
"e": 37013,
"s": 36962,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 37045,
"s": 37013,
"text": "Python Dictionary keys() method"
}
]
|
Program for decimal to hexadecimal conversion in C++ | Given with a decimal number as an input, the task is to convert the given decimal number into a hexadecimal number.
Hexadecimal number in computers is represented with base 16 and decimal number is represented with base 10 and represented with values 0 - 9 whereas hexadecimal number have digits starting from 0 β 15 in which 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E and 15 as F.
To convert a decimal number into a hexadecimal number follow the given steps β
Firstly divide the given number with the base value of conversion number e.g. dividing 6789 by 16 because we need to convert 6789 into a hexadecimal numbers which have base 16 and then obtain a quotient and store it. If the remainder is between 0-9 store them as it is and if the remainder lies between 10-15 convert them in their character form as A - F
Divide the obtained quotient with the base value of hexadecimal number which is 16 and keep storing the bits.
Keep doing right shift to the stored bits
Repeat the step until the remainder left indivisible
Given below is the pictorial representation of converting a decimal number into a hexadecimal number.
Input-: 6789
Divide the 6789 with base 16 : 6789 / 16 = 5 (remainder) 424(quotient)
Divide quotient with base: 424 / 16 = 8(remainder) 26(quotient)
Divide quotient with base: 26 / 16 = 10(remainder) 1(quotient)
Now reverse the remainder obtained for final hexadecimal value.
Output-: 1A85
Start
Step 1-> Declare function to convert decimal to hexadecimal
void convert(int num)
declare char arr[100]
set int i = 0
Loop While(num!=0)
Set int temp = 0
Set temp = num % 16
IF temp < 10
Set arr[i] = temp + 48
Increment i++
End
Else
Set arr[i] = temp + 55
Increment i++
End
Set num = num/16
End
Loop For int j=i-1 j>=0 jβ
Print arr[j]
Step 2-> In main()
Set int num = 6789
Call convert(num)
Stop
Live Demo
#include<iostream>
using namespace std;
//convert decimal to hexadecimal
void convert(int num) {
char arr[100];
int i = 0;
while(num!=0) {
int temp = 0;
temp = num % 16;
if(temp < 10) {
arr[i] = temp + 48;
i++;
} else {
arr[i] = temp + 55;
i++;
}
num = num/16;
}
for(int j=i-1; j>=0; j--)
cout << arr[j];
}
int main() {
int num = 6789;
cout<<num<< " converted to hexadeciaml: ";
convert(num);
return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
6789 converted to hexadeciaml: 1A85 | [
{
"code": null,
"e": 1178,
"s": 1062,
"text": "Given with a decimal number as an input, the task is to convert the given decimal number into a hexadecimal number."
},
{
"code": null,
"e": 1460,
"s": 1178,
"text": "Hexadecimal number in computers is represented with base 16 and decimal number is represented with base 10 and represented with values 0 - 9 whereas hexadecimal number have digits starting from 0 β 15 in which 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E and 15 as F."
},
{
"code": null,
"e": 1539,
"s": 1460,
"text": "To convert a decimal number into a hexadecimal number follow the given steps β"
},
{
"code": null,
"e": 1894,
"s": 1539,
"text": "Firstly divide the given number with the base value of conversion number e.g. dividing 6789 by 16 because we need to convert 6789 into a hexadecimal numbers which have base 16 and then obtain a quotient and store it. If the remainder is between 0-9 store them as it is and if the remainder lies between 10-15 convert them in their character form as A - F"
},
{
"code": null,
"e": 2004,
"s": 1894,
"text": "Divide the obtained quotient with the base value of hexadecimal number which is 16 and keep storing the bits."
},
{
"code": null,
"e": 2046,
"s": 2004,
"text": "Keep doing right shift to the stored bits"
},
{
"code": null,
"e": 2099,
"s": 2046,
"text": "Repeat the step until the remainder left indivisible"
},
{
"code": null,
"e": 2201,
"s": 2099,
"text": "Given below is the pictorial representation of converting a decimal number into a hexadecimal number."
},
{
"code": null,
"e": 2502,
"s": 2201,
"text": "Input-: 6789\n Divide the 6789 with base 16 : 6789 / 16 = 5 (remainder) 424(quotient)\n Divide quotient with base: 424 / 16 = 8(remainder) 26(quotient)\n Divide quotient with base: 26 / 16 = 10(remainder) 1(quotient)\n Now reverse the remainder obtained for final hexadecimal value.\nOutput-: 1A85"
},
{
"code": null,
"e": 3063,
"s": 2502,
"text": "Start\nStep 1-> Declare function to convert decimal to hexadecimal\n void convert(int num)\n declare char arr[100]\n set int i = 0\n Loop While(num!=0)\n Set int temp = 0\n Set temp = num % 16\n IF temp < 10\n Set arr[i] = temp + 48\n Increment i++\n End\n Else\n Set arr[i] = temp + 55\n Increment i++\n End\n Set num = num/16\n End\n Loop For int j=i-1 j>=0 jβ\n Print arr[j]\nStep 2-> In main()\n Set int num = 6789\n Call convert(num)\nStop"
},
{
"code": null,
"e": 3074,
"s": 3063,
"text": " Live Demo"
},
{
"code": null,
"e": 3581,
"s": 3074,
"text": "#include<iostream>\nusing namespace std;\n//convert decimal to hexadecimal\nvoid convert(int num) {\n char arr[100];\n int i = 0;\n while(num!=0) {\n int temp = 0;\n temp = num % 16;\n if(temp < 10) {\n arr[i] = temp + 48;\n i++;\n } else {\n arr[i] = temp + 55;\n i++;\n }\n num = num/16;\n }\n for(int j=i-1; j>=0; j--)\n cout << arr[j];\n}\nint main() {\n int num = 6789;\n cout<<num<< \" converted to hexadeciaml: \";\n convert(num);\n return 0;\n}"
},
{
"code": null,
"e": 3640,
"s": 3581,
"text": "IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT"
},
{
"code": null,
"e": 3676,
"s": 3640,
"text": "6789 converted to hexadeciaml: 1A85"
}
]
|
Node.js - Express Framework | Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework β
Allows to set up middlewares to respond to HTTP Requests.
Allows to set up middlewares to respond to HTTP Requests.
Defines a routing table which is used to perform different actions based on HTTP Method and URL.
Defines a routing table which is used to perform different actions based on HTTP Method and URL.
Allows to dynamically render HTML Pages based on passing arguments to templates.
Allows to dynamically render HTML Pages based on passing arguments to templates.
Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal.
$ npm install express --save
The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express β
body-parser β This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
body-parser β This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
cookie-parser β Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
cookie-parser β Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
multer β This is a node.js middleware for handling multipart/form-data.
multer β This is a node.js middleware for handling multipart/form-data.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save
Following is a very basic Express app which starts a server and listens on port 8081 for connection. This app responds with Hello World! for requests to the homepage. For every other path, it will respond with a 404 Not Found.
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Save the above code in a file named server.js and run it with the following command.
$ node server.js
You will see the following output β
Example app listening at http://0.0.0.0:8081
Open http://127.0.0.1:8081/ in any browser to see the following result.
Express application uses a callback function whose parameters are request and response objects.
app.get('/', function (req, res) {
// --
})
Request Object β The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
Request Object β The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
Response Object β The response object represents the HTTP response that an Express app sends when it gets an HTTP request.
Response Object β The response object represents the HTTP response that an Express app sends when it gets an HTTP request.
You can print req and res objects which provide a lot of information related to HTTP request and response including cookies, sessions, URL, etc.
We have seen a basic application which serves HTTP request for the homepage. Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
We will extend our Hello World program to handle more types of HTTP requests.
var express = require('express');
var app = express();
// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Save the above code in a file named server.js and run it with the following command.
$ node server.js
You will see the following output β
Example app listening at http://0.0.0.0:8081
Now you can try different requests at http://127.0.0.1:8081 to see the output generated by server.js. Following are a few screens shots showing different responses for different URLs.
Screen showing again http://127.0.0.1:8081/list_user
Screen showing again http://127.0.0.1:8081/abcd
Screen showing again http://127.0.0.1:8081/abcdefg
Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc.
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this β
app.use(express.static('public'));
We will keep a few images in public/images sub-directory as follows β
node_modules
server.js
public/
public/images
public/images/logo.png
Let's modify "Hello Word" app to add the functionality to handle static files.
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Save the above code in a file named server.js and run it with the following command.
$ node server.js
Now open http://127.0.0.1:8081/images/logo.png in any browser and see observe following result.
Here is a simple example which passes two values using HTML FORM GET method. We are going to use process_get router inside server.js to handle this input.
<html>
<body>
<form action = "http://127.0.0.1:8081/process_get" method = "GET">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as well as the input sent by the HTML form.
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form β
First Name:
Last Name:
Now you can enter the First and Last Name and then click submit button to see the result and it should return the following result β
{"first_name":"John","last_name":"Paul"}
Here is a simple example which passes two values using HTML FORM POST method. We are going to use process_get router inside server.js to handle this input.
<html>
<body>
<form action = "http://127.0.0.1:8081/process_post" method = "POST">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
Let's save the above code in index.htm and modify server.js to handle home page requests as well as the input sent by the HTML form.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form β
First Name:
Last Name:
Now you can enter the First and Last Name and then click the submit button to see the following result β
{"first_name":"John","last_name":"Paul"}
The following HTML code creates a file uploader form. This form has method attribute set to POST and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "http://127.0.0.1:8081/file_upload" method = "POST"
enctype = "multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as well as file upload.
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ) {
console.log( err );
} else {
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form β
File Upload:
Select a file to upload:
NOTE: This is just dummy form and would not work, but it must work at your server.
You can send cookies to a Node.js server which can handle the same using the following middleware option. Following is a simple example to print all the cookies sent by the client.
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8081)
44 Lectures
7.5 hours
Eduonix Learning Solutions
88 Lectures
17 hours
Eduonix Learning Solutions
32 Lectures
1.5 hours
Richard Wells
8 Lectures
33 mins
Anant Rungta
9 Lectures
2.5 hours
SHIVPRASAD KOIRALA
97 Lectures
6 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2297,
"s": 2018,
"text": "Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. Following are some of the core features of Express framework β"
},
{
"code": null,
"e": 2355,
"s": 2297,
"text": "Allows to set up middlewares to respond to HTTP Requests."
},
{
"code": null,
"e": 2413,
"s": 2355,
"text": "Allows to set up middlewares to respond to HTTP Requests."
},
{
"code": null,
"e": 2510,
"s": 2413,
"text": "Defines a routing table which is used to perform different actions based on HTTP Method and URL."
},
{
"code": null,
"e": 2607,
"s": 2510,
"text": "Defines a routing table which is used to perform different actions based on HTTP Method and URL."
},
{
"code": null,
"e": 2688,
"s": 2607,
"text": "Allows to dynamically render HTML Pages based on passing arguments to templates."
},
{
"code": null,
"e": 2769,
"s": 2688,
"text": "Allows to dynamically render HTML Pages based on passing arguments to templates."
},
{
"code": null,
"e": 2899,
"s": 2769,
"text": "Firstly, install the Express framework globally using NPM so that it can be used to create a web application using node terminal."
},
{
"code": null,
"e": 2929,
"s": 2899,
"text": "$ npm install express --save\n"
},
{
"code": null,
"e": 3133,
"s": 2929,
"text": "The above command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express β"
},
{
"code": null,
"e": 3232,
"s": 3133,
"text": "body-parser β This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data."
},
{
"code": null,
"e": 3331,
"s": 3232,
"text": "body-parser β This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data."
},
{
"code": null,
"e": 3434,
"s": 3331,
"text": "cookie-parser β Parse Cookie header and populate req.cookies with an object keyed by the cookie names."
},
{
"code": null,
"e": 3537,
"s": 3434,
"text": "cookie-parser β Parse Cookie header and populate req.cookies with an object keyed by the cookie names."
},
{
"code": null,
"e": 3609,
"s": 3537,
"text": "multer β This is a node.js middleware for handling multipart/form-data."
},
{
"code": null,
"e": 3681,
"s": 3609,
"text": "multer β This is a node.js middleware for handling multipart/form-data."
},
{
"code": null,
"e": 3778,
"s": 3681,
"text": "$ npm install body-parser --save\n$ npm install cookie-parser --save\n$ npm install multer --save\n"
},
{
"code": null,
"e": 4005,
"s": 3778,
"text": "Following is a very basic Express app which starts a server and listens on port 8081 for connection. This app responds with Hello World! for requests to the homepage. For every other path, it will respond with a 404 Not Found."
},
{
"code": null,
"e": 4322,
"s": 4005,
"text": "var express = require('express');\nvar app = express();\n\napp.get('/', function (req, res) {\n res.send('Hello World');\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})"
},
{
"code": null,
"e": 4407,
"s": 4322,
"text": "Save the above code in a file named server.js and run it with the following command."
},
{
"code": null,
"e": 4425,
"s": 4407,
"text": "$ node server.js\n"
},
{
"code": null,
"e": 4461,
"s": 4425,
"text": "You will see the following output β"
},
{
"code": null,
"e": 4507,
"s": 4461,
"text": "Example app listening at http://0.0.0.0:8081\n"
},
{
"code": null,
"e": 4579,
"s": 4507,
"text": "Open http://127.0.0.1:8081/ in any browser to see the following result."
},
{
"code": null,
"e": 4675,
"s": 4579,
"text": "Express application uses a callback function whose parameters are request and response objects."
},
{
"code": null,
"e": 4723,
"s": 4675,
"text": "app.get('/', function (req, res) {\n // --\n})\n"
},
{
"code": null,
"e": 4879,
"s": 4723,
"text": "Request Object β The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on."
},
{
"code": null,
"e": 5035,
"s": 4879,
"text": "Request Object β The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on."
},
{
"code": null,
"e": 5158,
"s": 5035,
"text": "Response Object β The response object represents the HTTP response that an Express app sends when it gets an HTTP request."
},
{
"code": null,
"e": 5281,
"s": 5158,
"text": "Response Object β The response object represents the HTTP response that an Express app sends when it gets an HTTP request."
},
{
"code": null,
"e": 5426,
"s": 5281,
"text": "You can print req and res objects which provide a lot of information related to HTTP request and response including cookies, sessions, URL, etc."
},
{
"code": null,
"e": 5691,
"s": 5426,
"text": "We have seen a basic application which serves HTTP request for the homepage. Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on)."
},
{
"code": null,
"e": 5769,
"s": 5691,
"text": "We will extend our Hello World program to handle more types of HTTP requests."
},
{
"code": null,
"e": 6933,
"s": 5769,
"text": "var express = require('express');\nvar app = express();\n\n// This responds with \"Hello World\" on the homepage\napp.get('/', function (req, res) {\n console.log(\"Got a GET request for the homepage\");\n res.send('Hello GET');\n})\n\n// This responds a POST request for the homepage\napp.post('/', function (req, res) {\n console.log(\"Got a POST request for the homepage\");\n res.send('Hello POST');\n})\n\n// This responds a DELETE request for the /del_user page.\napp.delete('/del_user', function (req, res) {\n console.log(\"Got a DELETE request for /del_user\");\n res.send('Hello DELETE');\n})\n\n// This responds a GET request for the /list_user page.\napp.get('/list_user', function (req, res) {\n console.log(\"Got a GET request for /list_user\");\n res.send('Page Listing');\n})\n\n// This responds a GET request for abcd, abxcd, ab123cd, and so on\napp.get('/ab*cd', function(req, res) { \n console.log(\"Got a GET request for /ab*cd\");\n res.send('Page Pattern Match');\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})"
},
{
"code": null,
"e": 7018,
"s": 6933,
"text": "Save the above code in a file named server.js and run it with the following command."
},
{
"code": null,
"e": 7036,
"s": 7018,
"text": "$ node server.js\n"
},
{
"code": null,
"e": 7072,
"s": 7036,
"text": "You will see the following output β"
},
{
"code": null,
"e": 7118,
"s": 7072,
"text": "Example app listening at http://0.0.0.0:8081\n"
},
{
"code": null,
"e": 7302,
"s": 7118,
"text": "Now you can try different requests at http://127.0.0.1:8081 to see the output generated by server.js. Following are a few screens shots showing different responses for different URLs."
},
{
"code": null,
"e": 7355,
"s": 7302,
"text": "Screen showing again http://127.0.0.1:8081/list_user"
},
{
"code": null,
"e": 7403,
"s": 7355,
"text": "Screen showing again http://127.0.0.1:8081/abcd"
},
{
"code": null,
"e": 7454,
"s": 7403,
"text": "Screen showing again http://127.0.0.1:8081/abcdefg"
},
{
"code": null,
"e": 7569,
"s": 7454,
"text": "Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc."
},
{
"code": null,
"e": 7835,
"s": 7569,
"text": "You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this β"
},
{
"code": null,
"e": 7871,
"s": 7835,
"text": "app.use(express.static('public'));\n"
},
{
"code": null,
"e": 7941,
"s": 7871,
"text": "We will keep a few images in public/images sub-directory as follows β"
},
{
"code": null,
"e": 8010,
"s": 7941,
"text": "node_modules\nserver.js\npublic/\npublic/images\npublic/images/logo.png\n"
},
{
"code": null,
"e": 8089,
"s": 8010,
"text": "Let's modify \"Hello Word\" app to add the functionality to handle static files."
},
{
"code": null,
"e": 8439,
"s": 8089,
"text": "var express = require('express');\nvar app = express();\n\napp.use(express.static('public'));\n\napp.get('/', function (req, res) {\n res.send('Hello World');\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})"
},
{
"code": null,
"e": 8524,
"s": 8439,
"text": "Save the above code in a file named server.js and run it with the following command."
},
{
"code": null,
"e": 8542,
"s": 8524,
"text": "$ node server.js\n"
},
{
"code": null,
"e": 8638,
"s": 8542,
"text": "Now open http://127.0.0.1:8081/images/logo.png in any browser and see observe following result."
},
{
"code": null,
"e": 8793,
"s": 8638,
"text": "Here is a simple example which passes two values using HTML FORM GET method. We are going to use process_get router inside server.js to handle this input."
},
{
"code": null,
"e": 9110,
"s": 8793,
"text": "<html>\n <body>\n \n <form action = \"http://127.0.0.1:8081/process_get\" method = \"GET\">\n First Name: <input type = \"text\" name = \"first_name\"> <br>\n Last Name: <input type = \"text\" name = \"last_name\">\n <input type = \"submit\" value = \"Submit\">\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 9239,
"s": 9110,
"text": "Let's save above code in index.htm and modify server.js to handle home page requests as well as the input sent by the HTML form."
},
{
"code": null,
"e": 9869,
"s": 9239,
"text": "var express = require('express');\nvar app = express();\n\napp.use(express.static('public'));\napp.get('/index.htm', function (req, res) {\n res.sendFile( __dirname + \"/\" + \"index.htm\" );\n})\n\napp.get('/process_get', function (req, res) {\n // Prepare output in JSON format\n response = {\n first_name:req.query.first_name,\n last_name:req.query.last_name\n };\n console.log(response);\n res.end(JSON.stringify(response));\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})"
},
{
"code": null,
"e": 9970,
"s": 9869,
"text": "Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form β"
},
{
"code": null,
"e": 10007,
"s": 9970,
"text": "\n\n\nFirst Name:\n\n\n\nLast Name:\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 10140,
"s": 10007,
"text": "Now you can enter the First and Last Name and then click submit button to see the result and it should return the following result β"
},
{
"code": null,
"e": 10182,
"s": 10140,
"text": "{\"first_name\":\"John\",\"last_name\":\"Paul\"}\n"
},
{
"code": null,
"e": 10338,
"s": 10182,
"text": "Here is a simple example which passes two values using HTML FORM POST method. We are going to use process_get router inside server.js to handle this input."
},
{
"code": null,
"e": 10656,
"s": 10338,
"text": "<html>\n <body>\n \n <form action = \"http://127.0.0.1:8081/process_post\" method = \"POST\">\n First Name: <input type = \"text\" name = \"first_name\"> <br>\n Last Name: <input type = \"text\" name = \"last_name\">\n <input type = \"submit\" value = \"Submit\">\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 10789,
"s": 10656,
"text": "Let's save the above code in index.htm and modify server.js to handle home page requests as well as the input sent by the HTML form."
},
{
"code": null,
"e": 11596,
"s": 10789,
"text": "var express = require('express');\nvar app = express();\nvar bodyParser = require('body-parser');\n\n// Create application/x-www-form-urlencoded parser\nvar urlencodedParser = bodyParser.urlencoded({ extended: false })\n\napp.use(express.static('public'));\napp.get('/index.htm', function (req, res) {\n res.sendFile( __dirname + \"/\" + \"index.htm\" );\n})\n\napp.post('/process_post', urlencodedParser, function (req, res) {\n // Prepare output in JSON format\n response = {\n first_name:req.body.first_name,\n last_name:req.body.last_name\n };\n console.log(response);\n res.end(JSON.stringify(response));\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})"
},
{
"code": null,
"e": 11697,
"s": 11596,
"text": "Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form β"
},
{
"code": null,
"e": 11734,
"s": 11697,
"text": "\n\n\nFirst Name:\n\n\n\nLast Name:\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 11839,
"s": 11734,
"text": "Now you can enter the First and Last Name and then click the submit button to see the following result β"
},
{
"code": null,
"e": 11881,
"s": 11839,
"text": "{\"first_name\":\"John\",\"last_name\":\"Paul\"}\n"
},
{
"code": null,
"e": 12030,
"s": 11881,
"text": "The following HTML code creates a file uploader form. This form has method attribute set to POST and enctype attribute is set to multipart/form-data"
},
{
"code": null,
"e": 12465,
"s": 12030,
"text": "<html>\n <head>\n <title>File Uploading Form</title>\n </head>\n\n <body>\n <h3>File Upload:</h3>\n Select a file to upload: <br />\n \n <form action = \"http://127.0.0.1:8081/file_upload\" method = \"POST\" \n enctype = \"multipart/form-data\">\n <input type=\"file\" name=\"file\" size=\"50\" />\n <br />\n <input type = \"submit\" value = \"Upload File\" />\n </form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 12574,
"s": 12465,
"text": "Let's save above code in index.htm and modify server.js to handle home page requests as well as file upload."
},
{
"code": null,
"e": 13818,
"s": 12574,
"text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\n\napp.use(express.static('public'));\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(multer({ dest: '/tmp/'}));\n\napp.get('/index.htm', function (req, res) {\n res.sendFile( __dirname + \"/\" + \"index.htm\" );\n})\n\napp.post('/file_upload', function (req, res) {\n console.log(req.files.file.name);\n console.log(req.files.file.path);\n console.log(req.files.file.type);\n var file = __dirname + \"/\" + req.files.file.name;\n \n fs.readFile( req.files.file.path, function (err, data) {\n fs.writeFile(file, data, function (err) {\n if( err ) {\n console.log( err );\n } else {\n response = {\n message:'File uploaded successfully',\n filename:req.files.file.name\n };\n }\n \n console.log( response );\n res.end( JSON.stringify( response ) );\n });\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n \n console.log(\"Example app listening at http://%s:%s\", host, port)\n})"
},
{
"code": null,
"e": 13919,
"s": 13818,
"text": "Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the following form β"
},
{
"code": null,
"e": 14045,
"s": 13919,
"text": "File Upload:\nSelect a file to upload: \n\n\n\nNOTE: This is just dummy form and would not work, but it must work at your server.\n"
},
{
"code": null,
"e": 14226,
"s": 14045,
"text": "You can send cookies to a Node.js server which can handle the same using the following middleware option. Following is a simple example to print all the cookies sent by the client."
},
{
"code": null,
"e": 14449,
"s": 14226,
"text": "var express = require('express')\nvar cookieParser = require('cookie-parser')\n\nvar app = express()\napp.use(cookieParser())\n\napp.get('/', function(req, res) {\n console.log(\"Cookies: \", req.cookies)\n})\napp.listen(8081)"
},
{
"code": null,
"e": 14484,
"s": 14449,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 14512,
"s": 14484,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 14546,
"s": 14512,
"text": "\n 88 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 14574,
"s": 14546,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 14609,
"s": 14574,
"text": "\n 32 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14624,
"s": 14609,
"text": " Richard Wells"
},
{
"code": null,
"e": 14655,
"s": 14624,
"text": "\n 8 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 14669,
"s": 14655,
"text": " Anant Rungta"
},
{
"code": null,
"e": 14703,
"s": 14669,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 14723,
"s": 14703,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 14756,
"s": 14723,
"text": "\n 97 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 14776,
"s": 14756,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 14783,
"s": 14776,
"text": " Print"
},
{
"code": null,
"e": 14794,
"s": 14783,
"text": " Add Notes"
}
]
|
How do we convert a string to a set in Python? | Pythonβs standard library contains built-in function set() which converts an iterable to set. A set object doesnβt contain repeated items. So, if a string contains any character more than once, that character appears only once in the set object. Again, the characters may not appear in the same sequence as in the string as set() function has its own hashing mechanism
>>> set("hello")
{'l', 'h', 'o', 'e'} | [
{
"code": null,
"e": 1431,
"s": 1062,
"text": "Pythonβs standard library contains built-in function set() which converts an iterable to set. A set object doesnβt contain repeated items. So, if a string contains any character more than once, that character appears only once in the set object. Again, the characters may not appear in the same sequence as in the string as set() function has its own hashing mechanism"
},
{
"code": null,
"e": 1469,
"s": 1431,
"text": ">>> set(\"hello\")\n{'l', 'h', 'o', 'e'}"
}
]
|
How to set smooth scrolling to stop at a specific position from the top using jQuery ? - GeeksforGeeks | 22 Jun, 2021
The scrollTop() method in jQuery is used to scroll to a particular portion of the page. Animating this method with the available inbuilt animations can make the scroll smoother. And, subtracting the specified value from it will make the scrolling to stop from the top.
Approach: The hash portion of the anchor link is first extracted using the hash property and its position on the page is found out using the offset() method. The scrollTop() method is then called on this hash value to scroll to that location. This method is animated by enclosing it within the animate() method and specifying the duration of the animation to be used in milliseconds. A larger value would make the animation slower to complete than a smaller value. This will smoothly animate all the anchor links on the page when they are clicked. And then we will subtract the specified value to stop the smooth scrolling to stop from the top.
Example:
HTML
<!DOCTYPE html><html> <head> <title> How to set smooth scrolling to stop at a specific position from the top using jQuery? </title> <!-- JQuery Script --> <script src= "https://code.jquery.com/jquery-3.4.1.min.js"> </script> <!-- Style to make scrollbar appear --> <style> .scroll { height: 1000px; background-color: teal; color: white; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to set smooth scrolling to stop at a specific position from the top using jQuery? </b> <p id="dest"> Click on the button below to scroll to the top of the page. </p> <p class="scroll"> GeeksforGeeks is a computer science portal. This is a large scrollable area. </p> <a href="#dest"> Scroll to top </a> <!-- jQuery for smooth scrolling to a specific position from top --> <script> // Define selector for selecting // anchor links with the hash let anchorSelector = 'a[href^="#"]'; $(anchorSelector).on('click', function (e) { // Prevent scrolling if the // hash value is blank e.preventDefault(); // Get the destination to scroll to // using the hash property let destination = $(this.hash); // Get the position of the destination // using the coordinates returned by // offset() method and subtracting 50px // from it. let scrollPosition = destination.offset().top - 50; // Specify animation duration let animationDuration = 500; // Animate the html/body with // the scrollTop() method $('html, body').animate({ scrollTop: scrollPosition }, animationDuration); }); </script></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.
anikakapoor
CSS-Misc
HTML-Misc
jQuery-Misc
Technical Scripter 2020
CSS
HTML
JQuery
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 25070,
"s": 25042,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 25339,
"s": 25070,
"text": "The scrollTop() method in jQuery is used to scroll to a particular portion of the page. Animating this method with the available inbuilt animations can make the scroll smoother. And, subtracting the specified value from it will make the scrolling to stop from the top."
},
{
"code": null,
"e": 25984,
"s": 25339,
"text": "Approach: The hash portion of the anchor link is first extracted using the hash property and its position on the page is found out using the offset() method. The scrollTop() method is then called on this hash value to scroll to that location. This method is animated by enclosing it within the animate() method and specifying the duration of the animation to be used in milliseconds. A larger value would make the animation slower to complete than a smaller value. This will smoothly animate all the anchor links on the page when they are clicked. And then we will subtract the specified value to stop the smooth scrolling to stop from the top."
},
{
"code": null,
"e": 25993,
"s": 25984,
"text": "Example:"
},
{
"code": null,
"e": 25998,
"s": 25993,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to set smooth scrolling to stop at a specific position from the top using jQuery? </title> <!-- JQuery Script --> <script src= \"https://code.jquery.com/jquery-3.4.1.min.js\"> </script> <!-- Style to make scrollbar appear --> <style> .scroll { height: 1000px; background-color: teal; color: white; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to set smooth scrolling to stop at a specific position from the top using jQuery? </b> <p id=\"dest\"> Click on the button below to scroll to the top of the page. </p> <p class=\"scroll\"> GeeksforGeeks is a computer science portal. This is a large scrollable area. </p> <a href=\"#dest\"> Scroll to top </a> <!-- jQuery for smooth scrolling to a specific position from top --> <script> // Define selector for selecting // anchor links with the hash let anchorSelector = 'a[href^=\"#\"]'; $(anchorSelector).on('click', function (e) { // Prevent scrolling if the // hash value is blank e.preventDefault(); // Get the destination to scroll to // using the hash property let destination = $(this.hash); // Get the position of the destination // using the coordinates returned by // offset() method and subtracting 50px // from it. let scrollPosition = destination.offset().top - 50; // Specify animation duration let animationDuration = 500; // Animate the html/body with // the scrollTop() method $('html, body').animate({ scrollTop: scrollPosition }, animationDuration); }); </script></body> </html>",
"e": 27988,
"s": 25998,
"text": null
},
{
"code": null,
"e": 27997,
"s": 27988,
"text": "Output: "
},
{
"code": null,
"e": 28134,
"s": 27997,
"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": 28146,
"s": 28134,
"text": "anikakapoor"
},
{
"code": null,
"e": 28155,
"s": 28146,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28165,
"s": 28155,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28177,
"s": 28165,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28201,
"s": 28177,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28205,
"s": 28201,
"text": "CSS"
},
{
"code": null,
"e": 28210,
"s": 28205,
"text": "HTML"
},
{
"code": null,
"e": 28217,
"s": 28210,
"text": "JQuery"
},
{
"code": null,
"e": 28236,
"s": 28217,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28253,
"s": 28236,
"text": "Web Technologies"
},
{
"code": null,
"e": 28258,
"s": 28253,
"text": "HTML"
},
{
"code": null,
"e": 28356,
"s": 28258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28365,
"s": 28356,
"text": "Comments"
},
{
"code": null,
"e": 28378,
"s": 28365,
"text": "Old Comments"
},
{
"code": null,
"e": 28415,
"s": 28378,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28444,
"s": 28415,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28483,
"s": 28444,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28525,
"s": 28483,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28560,
"s": 28525,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 28620,
"s": 28560,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28681,
"s": 28620,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28734,
"s": 28681,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 28784,
"s": 28734,
"text": "How to Insert Form Data into Database using PHP ?"
}
]
|
Exploring Design Patterns in Python | by Dan Root | Towards Data Science | Design Patterns are used to help programmers with understanding concepts, teaching, learning, and building on other great working ideas and concepts. So, when you are thinking Design Patterns think of solving problems. Design Patterns are models built to help structure and solve simple to complicated issues. A good amount programmers have actually implemented them in their own code without realizing it. That is because it is such an abstract idea that you can use it without even really thinking about what it is. By knowing what Design Patterns are and how to use them you can overcome obstacles that would otherwise seem overwhelming. You also, bring another level of awareness to the table and instead of accidently implementing a shacky Design Pattern, you can implement a great Design Pattern on purpose. Design Patterns are being used increasingly in the software community and it is a big plus knowing them. It is important that you know at least the basics of Object-Oriented Programming. More specifically that you know about Inheritance and Polymorphism.
Design Patterns are often referred to as Design Templates, as they provide a template on how to handle common reoccurring issues. You can use existing Design Patterns or even create your own. There are many categories of Design Patterns, here are some popular ones:
Creative
Structural
Behavioral
They apply to any OOP (Object Orientated Programming) programming language.They are flexible. Constantly changing, evolving, and updating.Left unfinished often for creativity.
They apply to any OOP (Object Orientated Programming) programming language.
They are flexible. Constantly changing, evolving, and updating.
Left unfinished often for creativity.
Brief description of the Pattern.
What is the underlying issue you are trying to solve?
Specifies where a Pattern is applicable. Defines the structure and behavior of the Pattern.
The classes and objects that are involved in the Pattern.
Effects that may incur from using the Pattern.
Factory
Abstract Factory
Singleton
Builder
Prototype
Object Pool
Decorator
Proxy
Adaptor
Composite
Bridge
Facade
Flyweight
Observer
Visitor
Iterator
Strategy
Command
Mediator
Memento
State
Chain of Responsibility
Pattern Name: Factory
Pattern Type: Creative
When implementing a Design Pattern in Python it is important to be able to pick the right Pattern for the right use. Knowing your Design Pattern categories will help in this decision-making process.
Problem: You are unsure of what type of objects you need or what classes you will be using.
So, in this hypothetical scenario let's say that you own a computer store and have only been selling one type of monitor. The monitor you are already selling is a small monitor. You now want to add large monitors to your inventory to sell.
Solution: This Pattern is good for creating new objects. It also has wide applicability in many areas of programming problems involving interfaces or class instantiation. This can be great for expanding your class instantiations at scale and keep your code quick, simple, and organized.
# First Class for Small Monitorclass SmallMonitor(): def __init__(self, brand): self._brand = brand def details(self): details = "24in x 24in 1080p | $87.00" return details# Second Class for Large Monitorclass LargeMonitor(): def __init__(self, brand): self._brand = brand def details(self): details = "32in x 32in 1080p | $115.00" return details# Basic Creative Design Pattern Implementationdef get_monitor(monitor = 'small_monitor'): """factory method""" monitors = dict(small_monitor = SmallMonitor("ASUS"), large_monitor = LargeMonitor("HP")) ruturn monitors[monitor]small_monitor = get_monitor("small_monitor").details()large_monitor = get_monitor("large_monitor").details()print(small_monitor)print(large_monitor)[out]24in x 24in 1080p | $87.0032in x 32in 1080p | $115.00
Participants: The participants would be the SmallMonitor() and LargeMonitor() classes. Also, the small_monitor and large_monitor objects would be included, as well.
Consequences: The pattern has positive consequences when applied to class instantiation at scale but can sometimes be confusing or not necessary for more simple instantiations. In some cases, it can limit the code available. This is also in many applications not recommended in Python.
Design Patterns support consistent coding among the community, as well as individually. They help maintain a healthy programming ecosystem that has well known solutions to common problems. Using Design Patterns can sometimes make things worse though and should be integrated into your coding regimen using logic, reason, and proper implementation. Sometimes you have the wrong Design Pattern for the problem at hand and sometimes not having one or creating your own is the best idea. No matter what though, the knowledge of Design Patterns will do nothing but make you a better programmer. In many cases they will improve your code and efficiency by a noticeable amount. I hope this helps anyone wanting to know more about the basics of Design Patterns in Python. Thank you and happy coding! | [
{
"code": null,
"e": 1241,
"s": 172,
"text": "Design Patterns are used to help programmers with understanding concepts, teaching, learning, and building on other great working ideas and concepts. So, when you are thinking Design Patterns think of solving problems. Design Patterns are models built to help structure and solve simple to complicated issues. A good amount programmers have actually implemented them in their own code without realizing it. That is because it is such an abstract idea that you can use it without even really thinking about what it is. By knowing what Design Patterns are and how to use them you can overcome obstacles that would otherwise seem overwhelming. You also, bring another level of awareness to the table and instead of accidently implementing a shacky Design Pattern, you can implement a great Design Pattern on purpose. Design Patterns are being used increasingly in the software community and it is a big plus knowing them. It is important that you know at least the basics of Object-Oriented Programming. More specifically that you know about Inheritance and Polymorphism."
},
{
"code": null,
"e": 1507,
"s": 1241,
"text": "Design Patterns are often referred to as Design Templates, as they provide a template on how to handle common reoccurring issues. You can use existing Design Patterns or even create your own. There are many categories of Design Patterns, here are some popular ones:"
},
{
"code": null,
"e": 1516,
"s": 1507,
"text": "Creative"
},
{
"code": null,
"e": 1527,
"s": 1516,
"text": "Structural"
},
{
"code": null,
"e": 1538,
"s": 1527,
"text": "Behavioral"
},
{
"code": null,
"e": 1714,
"s": 1538,
"text": "They apply to any OOP (Object Orientated Programming) programming language.They are flexible. Constantly changing, evolving, and updating.Left unfinished often for creativity."
},
{
"code": null,
"e": 1790,
"s": 1714,
"text": "They apply to any OOP (Object Orientated Programming) programming language."
},
{
"code": null,
"e": 1854,
"s": 1790,
"text": "They are flexible. Constantly changing, evolving, and updating."
},
{
"code": null,
"e": 1892,
"s": 1854,
"text": "Left unfinished often for creativity."
},
{
"code": null,
"e": 1926,
"s": 1892,
"text": "Brief description of the Pattern."
},
{
"code": null,
"e": 1980,
"s": 1926,
"text": "What is the underlying issue you are trying to solve?"
},
{
"code": null,
"e": 2072,
"s": 1980,
"text": "Specifies where a Pattern is applicable. Defines the structure and behavior of the Pattern."
},
{
"code": null,
"e": 2130,
"s": 2072,
"text": "The classes and objects that are involved in the Pattern."
},
{
"code": null,
"e": 2177,
"s": 2130,
"text": "Effects that may incur from using the Pattern."
},
{
"code": null,
"e": 2185,
"s": 2177,
"text": "Factory"
},
{
"code": null,
"e": 2202,
"s": 2185,
"text": "Abstract Factory"
},
{
"code": null,
"e": 2212,
"s": 2202,
"text": "Singleton"
},
{
"code": null,
"e": 2220,
"s": 2212,
"text": "Builder"
},
{
"code": null,
"e": 2230,
"s": 2220,
"text": "Prototype"
},
{
"code": null,
"e": 2242,
"s": 2230,
"text": "Object Pool"
},
{
"code": null,
"e": 2252,
"s": 2242,
"text": "Decorator"
},
{
"code": null,
"e": 2258,
"s": 2252,
"text": "Proxy"
},
{
"code": null,
"e": 2266,
"s": 2258,
"text": "Adaptor"
},
{
"code": null,
"e": 2276,
"s": 2266,
"text": "Composite"
},
{
"code": null,
"e": 2283,
"s": 2276,
"text": "Bridge"
},
{
"code": null,
"e": 2290,
"s": 2283,
"text": "Facade"
},
{
"code": null,
"e": 2300,
"s": 2290,
"text": "Flyweight"
},
{
"code": null,
"e": 2309,
"s": 2300,
"text": "Observer"
},
{
"code": null,
"e": 2317,
"s": 2309,
"text": "Visitor"
},
{
"code": null,
"e": 2326,
"s": 2317,
"text": "Iterator"
},
{
"code": null,
"e": 2335,
"s": 2326,
"text": "Strategy"
},
{
"code": null,
"e": 2343,
"s": 2335,
"text": "Command"
},
{
"code": null,
"e": 2352,
"s": 2343,
"text": "Mediator"
},
{
"code": null,
"e": 2360,
"s": 2352,
"text": "Memento"
},
{
"code": null,
"e": 2366,
"s": 2360,
"text": "State"
},
{
"code": null,
"e": 2390,
"s": 2366,
"text": "Chain of Responsibility"
},
{
"code": null,
"e": 2412,
"s": 2390,
"text": "Pattern Name: Factory"
},
{
"code": null,
"e": 2435,
"s": 2412,
"text": "Pattern Type: Creative"
},
{
"code": null,
"e": 2634,
"s": 2435,
"text": "When implementing a Design Pattern in Python it is important to be able to pick the right Pattern for the right use. Knowing your Design Pattern categories will help in this decision-making process."
},
{
"code": null,
"e": 2726,
"s": 2634,
"text": "Problem: You are unsure of what type of objects you need or what classes you will be using."
},
{
"code": null,
"e": 2966,
"s": 2726,
"text": "So, in this hypothetical scenario let's say that you own a computer store and have only been selling one type of monitor. The monitor you are already selling is a small monitor. You now want to add large monitors to your inventory to sell."
},
{
"code": null,
"e": 3253,
"s": 2966,
"text": "Solution: This Pattern is good for creating new objects. It also has wide applicability in many areas of programming problems involving interfaces or class instantiation. This can be great for expanding your class instantiations at scale and keep your code quick, simple, and organized."
},
{
"code": null,
"e": 4113,
"s": 3253,
"text": "# First Class for Small Monitorclass SmallMonitor(): def __init__(self, brand): self._brand = brand def details(self): details = \"24in x 24in 1080p | $87.00\" return details# Second Class for Large Monitorclass LargeMonitor(): def __init__(self, brand): self._brand = brand def details(self): details = \"32in x 32in 1080p | $115.00\" return details# Basic Creative Design Pattern Implementationdef get_monitor(monitor = 'small_monitor'): \"\"\"factory method\"\"\" monitors = dict(small_monitor = SmallMonitor(\"ASUS\"), large_monitor = LargeMonitor(\"HP\")) ruturn monitors[monitor]small_monitor = get_monitor(\"small_monitor\").details()large_monitor = get_monitor(\"large_monitor\").details()print(small_monitor)print(large_monitor)[out]24in x 24in 1080p | $87.0032in x 32in 1080p | $115.00"
},
{
"code": null,
"e": 4278,
"s": 4113,
"text": "Participants: The participants would be the SmallMonitor() and LargeMonitor() classes. Also, the small_monitor and large_monitor objects would be included, as well."
},
{
"code": null,
"e": 4564,
"s": 4278,
"text": "Consequences: The pattern has positive consequences when applied to class instantiation at scale but can sometimes be confusing or not necessary for more simple instantiations. In some cases, it can limit the code available. This is also in many applications not recommended in Python."
}
]
|
What is the correct way to define class variables in Python? | Class variables are variables that are declared outside the__init__method. These are static elements, meaning, they belong to the class rather than to the class instances. These class variables are shared by all instances of that class. Example code for class variables
class MyClass:
__item1 = 123
__item2 = "abc"
def __init__(self):
#pass or something else
You'll understand more clearly with more code β
class MyClass:
stat_elem = 456
def __init__(self):
self.object_elem = 789
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.stat_elem, c1.object_elem
456 789
>>> print c2.stat_elem, c2.object_elem
456 789
# Let's try changing the static element
MyClass.static_elem = 888
>>> print c1.stat_elem, c1.object_elem
888 789
>>> print c2.stat_elem, c2.object_elem
888 789
# Now, let's try changing the object element
c1.object_elem = 777
>>> print c1.stat_elem, c1.object_elem
888 777
>>> print c2.stat_elem, c2.object_elem
888 789 | [
{
"code": null,
"e": 1333,
"s": 1062,
"text": "Class variables are variables that are declared outside the__init__method. These are static elements, meaning, they belong to the class rather than to the class instances. These class variables are shared by all instances of that class. Example code for class variables "
},
{
"code": null,
"e": 1432,
"s": 1333,
"text": "class MyClass:\n __item1 = 123\n __item2 = \"abc\"\n def __init__(self):\n #pass or something else"
},
{
"code": null,
"e": 1480,
"s": 1432,
"text": "You'll understand more clearly with more code β"
},
{
"code": null,
"e": 2048,
"s": 1480,
"text": "class MyClass:\n stat_elem = 456\n def __init__(self):\n self.object_elem = 789\nc1 = MyClass()\nc2 = MyClass()\n# Initial values of both elements\n>>> print c1.stat_elem, c1.object_elem\n456 789\n>>> print c2.stat_elem, c2.object_elem\n456 789\n# Let's try changing the static element\nMyClass.static_elem = 888\n>>> print c1.stat_elem, c1.object_elem\n888 789\n>>> print c2.stat_elem, c2.object_elem\n888 789\n# Now, let's try changing the object element\nc1.object_elem = 777\n>>> print c1.stat_elem, c1.object_elem\n888 777\n>>> print c2.stat_elem, c2.object_elem\n888 789"
}
]
|
C program for Binomial Coefficients table | Given with a positive integer value letβs say βvalβ and the task is to print the value of binomial coefficient B(n, k) where, n and k be any value between 0 to val and hence display the result.
Binomial coefficient (n, k) is the order of choosing βkβ results from the given βnβ possibilities. The value of binomial coefficient of positive n and k is given by
Ckn=n!(nβk)!k!
where, n >= k
Input-: B(9,2)
Output-:
B29=9!(9β2)!2!
9Γ8Γ7Γ6Γ5Γ4Γ3Γ2Γ16Γ5Γ4Γ3Γ2Γ1)Γ2Γ1=362,8801440=252
The Binomial Coefficient Table is formed for calculating the multiple values that can be generated between n and k.
Input-: value = 5
Output-:
Approach used in the below program is as follows β
Input the variable βvalβ from the user for generating the table
Start the loop from 0 to βvalβ because the value of binomial coefficient will lie between 0 to βvalβ
Apply the formula given, if n and k is not 0B(m, x) = B(m, x - 1) * (m - x + 1) / x
Apply the formula given, if n and k is not 0
B(m, x) = B(m, x - 1) * (m - x + 1) / x
Print the result
START
Step 1-> declare function for binomial coefficient table
int bin_table(int val)
Loop For int i = 0 and i <= val and i++
print i
Declare int num = 1
Loop For int j = 0 and j <= i and j++
If (i != 0 && j != 0)
set num = num * (i - j + 1) / j
End
print num
End
print \n
Step 2-> In main()
Declare int value = 5
call bin_table(value)
STOP
#include <stdio.h>
// Function for binomial coefficient table
int bin_table(int val) {
for (int i = 0; i <= val; i++) {
printf("%2d", i);
int num = 1;
for (int j = 0; j <= i; j++) {
if (i != 0 && j != 0)
num = num * (i - j + 1) / j;
printf("%4d", num);
}
printf("\n");
}
}
int main() {
int value = 5;
bin_table(value);
return 0;
} | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "Given with a positive integer value letβs say βvalβ and the task is to print the value of binomial coefficient B(n, k) where, n and k be any value between 0 to val and hence display the result."
},
{
"code": null,
"e": 1421,
"s": 1256,
"text": "Binomial coefficient (n, k) is the order of choosing βkβ results from the given βnβ possibilities. The value of binomial coefficient of positive n and k is given by"
},
{
"code": null,
"e": 1436,
"s": 1421,
"text": "Ckn=n!(nβk)!k!"
},
{
"code": null,
"e": 1450,
"s": 1436,
"text": "where, n >= k"
},
{
"code": null,
"e": 1474,
"s": 1450,
"text": "Input-: B(9,2)\nOutput-:"
},
{
"code": null,
"e": 1490,
"s": 1474,
"text": "B29=9!(9β2)!2! "
},
{
"code": null,
"e": 1540,
"s": 1490,
"text": "9Γ8Γ7Γ6Γ5Γ4Γ3Γ2Γ16Γ5Γ4Γ3Γ2Γ1)Γ2Γ1=362,8801440=252"
},
{
"code": null,
"e": 1656,
"s": 1540,
"text": "The Binomial Coefficient Table is formed for calculating the multiple values that can be generated between n and k."
},
{
"code": null,
"e": 1683,
"s": 1656,
"text": "Input-: value = 5\nOutput-:"
},
{
"code": null,
"e": 1734,
"s": 1683,
"text": "Approach used in the below program is as follows β"
},
{
"code": null,
"e": 1798,
"s": 1734,
"text": "Input the variable βvalβ from the user for generating the table"
},
{
"code": null,
"e": 1899,
"s": 1798,
"text": "Start the loop from 0 to βvalβ because the value of binomial coefficient will lie between 0 to βvalβ"
},
{
"code": null,
"e": 1983,
"s": 1899,
"text": "Apply the formula given, if n and k is not 0B(m, x) = B(m, x - 1) * (m - x + 1) / x"
},
{
"code": null,
"e": 2028,
"s": 1983,
"text": "Apply the formula given, if n and k is not 0"
},
{
"code": null,
"e": 2068,
"s": 2028,
"text": "B(m, x) = B(m, x - 1) * (m - x + 1) / x"
},
{
"code": null,
"e": 2085,
"s": 2068,
"text": "Print the result"
},
{
"code": null,
"e": 2492,
"s": 2085,
"text": "START\nStep 1-> declare function for binomial coefficient table\n int bin_table(int val)\n Loop For int i = 0 and i <= val and i++\n print i\n Declare int num = 1\n Loop For int j = 0 and j <= i and j++\n If (i != 0 && j != 0)\n set num = num * (i - j + 1) / j\n End\n print num\n End\n print \\n\nStep 2-> In main()\n Declare int value = 5\n call bin_table(value)\nSTOP"
},
{
"code": null,
"e": 2895,
"s": 2492,
"text": "#include <stdio.h>\n// Function for binomial coefficient table\nint bin_table(int val) {\n for (int i = 0; i <= val; i++) {\n printf(\"%2d\", i);\n int num = 1;\n for (int j = 0; j <= i; j++) {\n if (i != 0 && j != 0)\n num = num * (i - j + 1) / j;\n printf(\"%4d\", num);\n }\n printf(\"\\n\");\n }\n}\nint main() {\n int value = 5;\n bin_table(value);\n return 0;\n}"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.