title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to Pass ArrayList Object as Function Argument in java? - GeeksforGeeks | 07 Jan, 2021
ArrayList class in Java is basically a resize-able array i.e. it can grow and shrink in size dynamically according to the values that we add or remove to/from it. It is present in java.util package. If we want to pass an ArrayList as an argument to a function then we can easily do it using the syntax mentioned below.
Example:
ArrayList<Integer> list = new ArrayList<>();
modifyList(list);
public static void modifyList(ArrayList<Integer> list){
list.add(69);
list.add(98);
}
In the code above, we created an ArrayList object named ‘list’ and then we passed it to a function named modifyList. The changes that we did to this list (i.e. the values that we added to the list) will appear to the original list inside the main function. This is happening because the Object References are passed by value in java as java is strictly Pass by Value.
Implementation of the problem statement:
Java
// Java program to pass an// ArrayList as an argument import java.util.*; public class GFG { public static void main(String[] args) { // Creating an ArrayList Object of Integer type ArrayList<Integer> list = new ArrayList<>(); // Inserting some Integer values in ArrayList list.add(3); list.add(57); list.add(7); // list after insertions : [3, 57, 7] // Displaying the ArrayList System.out.print("ArrayList after insertions: "); display(list); // Passing the ArrayList as an argument for // modification The modifications done to the list // inside the function will appear inside the // original ArrayList inside main() modifyList(list); // list after modifications : [3, 57, 7, 20, 98] // displaying the ArrayList after modifications System.out.print("ArrayList after modifications: "); display(list); } // Function to modify the arrayList public static void modifyList(ArrayList<Integer> parameterList) { parameterList.add(20); parameterList.add(98); } // Function to display the array List public static void display(ArrayList<Integer> list) { System.out.println(list); }}
ArrayList after insertions: [3, 57, 7]
ArrayList after modifications: [3, 57, 7, 20, 98]
How Java is pass by Value?
Let us assume that the Array list object that we created inside the main function points to an address 1000. When we passed this object to the modifyList function then the address 1000 is passed to it and the object ‘parameterList’ also starts pointing to the same location inside the memory as that of ‘list’ that is why we said that object references are passed by value in java. After that when we did modifications to ‘parameterList’ then the same changes are made to the original ‘list’. This concept is very similar to what happens in C++ when we pass a pointer variable as an argument.
ArrayList<Integer> list = new ArrayList<>();
callByValue(list);
public static void callByValue(ArrayList<Integer> parameterList){
parameterList = new ArrayList<>();
parameterList.add(88);
parameterList.add(200);
parameterList.add(89);
}
In the code above when we passed the list to the callByValue function then the ‘parameterList’ starts pointing to the memory address i.e. 1000. But when we created a new instance of ArrayList and made ‘parameterList’ point to it then ‘parameterList’ starts pointing to a new memory address (let’s say) 2000. The changes made to ArrayList inside this function will no longer affect the ArrayList at memory address 1000. Hence, the ‘list’ inside the main function remains unaffected.
Below is the implementation of the problem statement:
Java
// Java program to pass an// ArrayList as an argument import java.util.ArrayList; public class GFG { public static void main(String[] args) { // Creating an ArrayList Object of Integer type ArrayList<Integer> list = new ArrayList<>(); // Inserting some Integer values in ArrayList list.add(3); list.add(57); list.add(7); // list after insertions : [3, 57, 7] // Displaying the ArrayList System.out.print("ArrayList after insertions: "); display(list); // The changes made to the ArrayList inside this // function will not affect the original ArrayList // that we pass to it as we are simply creating the // new instance of ArrayList and making our // parameterList point to it callByValue(list); // list after function call : [3, 57, 7] // displaying the ArrayList after calling // callByValue System.out.print( "ArrayList after the function call: "); display(list); } public static void callByValue(ArrayList<Integer> parameterList) { // Creating a new instance of ArrayList parameterList = new ArrayList<>(); // Inserting Integer values to the new ArrayList // created inside the function parameterList.add(88); parameterList.add(200); parameterList.add(89); // Displaying our new ArrayList System.out.print( "New ArrayList inside the function: "); display(parameterList); } // Function to display the array List public static void display(ArrayList<Integer> list) { System.out.println(list); }}
ArrayList after insertions: [3, 57, 7]
New ArrayList inside the function: [88, 200, 89]
ArrayList after the function call: [3, 57, 7]
Java-ArrayList
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 23876,
"s": 23557,
"text": "ArrayList class in Java is basically a resize-able array i.e. it can grow and shrink in size dynamically according to the values that we add or remove to/from it. It is present in java.util package. If we want to pass an ArrayList as an argument to a function then we can easily do it using the syntax mentioned below."
},
{
"code": null,
"e": 23885,
"s": 23876,
"text": "Example:"
},
{
"code": null,
"e": 24048,
"s": 23885,
"text": "ArrayList<Integer> list = new ArrayList<>();\nmodifyList(list);\npublic static void modifyList(ArrayList<Integer> list){\n list.add(69);\n list.add(98);\n}"
},
{
"code": null,
"e": 24417,
"s": 24048,
"text": "In the code above, we created an ArrayList object named ‘list’ and then we passed it to a function named modifyList. The changes that we did to this list (i.e. the values that we added to the list) will appear to the original list inside the main function. This is happening because the Object References are passed by value in java as java is strictly Pass by Value. "
},
{
"code": null,
"e": 24458,
"s": 24417,
"text": "Implementation of the problem statement:"
},
{
"code": null,
"e": 24463,
"s": 24458,
"text": "Java"
},
{
"code": "// Java program to pass an// ArrayList as an argument import java.util.*; public class GFG { public static void main(String[] args) { // Creating an ArrayList Object of Integer type ArrayList<Integer> list = new ArrayList<>(); // Inserting some Integer values in ArrayList list.add(3); list.add(57); list.add(7); // list after insertions : [3, 57, 7] // Displaying the ArrayList System.out.print(\"ArrayList after insertions: \"); display(list); // Passing the ArrayList as an argument for // modification The modifications done to the list // inside the function will appear inside the // original ArrayList inside main() modifyList(list); // list after modifications : [3, 57, 7, 20, 98] // displaying the ArrayList after modifications System.out.print(\"ArrayList after modifications: \"); display(list); } // Function to modify the arrayList public static void modifyList(ArrayList<Integer> parameterList) { parameterList.add(20); parameterList.add(98); } // Function to display the array List public static void display(ArrayList<Integer> list) { System.out.println(list); }}",
"e": 25746,
"s": 24463,
"text": null
},
{
"code": null,
"e": 25836,
"s": 25746,
"text": "ArrayList after insertions: [3, 57, 7]\nArrayList after modifications: [3, 57, 7, 20, 98]\n"
},
{
"code": null,
"e": 25865,
"s": 25838,
"text": "How Java is pass by Value?"
},
{
"code": null,
"e": 26458,
"s": 25865,
"text": "Let us assume that the Array list object that we created inside the main function points to an address 1000. When we passed this object to the modifyList function then the address 1000 is passed to it and the object ‘parameterList’ also starts pointing to the same location inside the memory as that of ‘list’ that is why we said that object references are passed by value in java. After that when we did modifications to ‘parameterList’ then the same changes are made to the original ‘list’. This concept is very similar to what happens in C++ when we pass a pointer variable as an argument."
},
{
"code": null,
"e": 26723,
"s": 26458,
"text": "ArrayList<Integer> list = new ArrayList<>();\ncallByValue(list);\npublic static void callByValue(ArrayList<Integer> parameterList){\n parameterList = new ArrayList<>();\n parameterList.add(88);\n parameterList.add(200);\n parameterList.add(89);\n}"
},
{
"code": null,
"e": 27205,
"s": 26723,
"text": "In the code above when we passed the list to the callByValue function then the ‘parameterList’ starts pointing to the memory address i.e. 1000. But when we created a new instance of ArrayList and made ‘parameterList’ point to it then ‘parameterList’ starts pointing to a new memory address (let’s say) 2000. The changes made to ArrayList inside this function will no longer affect the ArrayList at memory address 1000. Hence, the ‘list’ inside the main function remains unaffected."
},
{
"code": null,
"e": 27260,
"s": 27205,
"text": "Below is the implementation of the problem statement: "
},
{
"code": null,
"e": 27265,
"s": 27260,
"text": "Java"
},
{
"code": "// Java program to pass an// ArrayList as an argument import java.util.ArrayList; public class GFG { public static void main(String[] args) { // Creating an ArrayList Object of Integer type ArrayList<Integer> list = new ArrayList<>(); // Inserting some Integer values in ArrayList list.add(3); list.add(57); list.add(7); // list after insertions : [3, 57, 7] // Displaying the ArrayList System.out.print(\"ArrayList after insertions: \"); display(list); // The changes made to the ArrayList inside this // function will not affect the original ArrayList // that we pass to it as we are simply creating the // new instance of ArrayList and making our // parameterList point to it callByValue(list); // list after function call : [3, 57, 7] // displaying the ArrayList after calling // callByValue System.out.print( \"ArrayList after the function call: \"); display(list); } public static void callByValue(ArrayList<Integer> parameterList) { // Creating a new instance of ArrayList parameterList = new ArrayList<>(); // Inserting Integer values to the new ArrayList // created inside the function parameterList.add(88); parameterList.add(200); parameterList.add(89); // Displaying our new ArrayList System.out.print( \"New ArrayList inside the function: \"); display(parameterList); } // Function to display the array List public static void display(ArrayList<Integer> list) { System.out.println(list); }}",
"e": 28968,
"s": 27265,
"text": null
},
{
"code": null,
"e": 29103,
"s": 28968,
"text": "ArrayList after insertions: [3, 57, 7]\nNew ArrayList inside the function: [88, 200, 89]\nArrayList after the function call: [3, 57, 7]\n"
},
{
"code": null,
"e": 29118,
"s": 29103,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 29125,
"s": 29118,
"text": "Picked"
},
{
"code": null,
"e": 29130,
"s": 29125,
"text": "Java"
},
{
"code": null,
"e": 29144,
"s": 29130,
"text": "Java Programs"
},
{
"code": null,
"e": 29149,
"s": 29144,
"text": "Java"
},
{
"code": null,
"e": 29247,
"s": 29149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29256,
"s": 29247,
"text": "Comments"
},
{
"code": null,
"e": 29269,
"s": 29256,
"text": "Old Comments"
},
{
"code": null,
"e": 29299,
"s": 29269,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29314,
"s": 29299,
"text": "Stream In Java"
},
{
"code": null,
"e": 29335,
"s": 29314,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29381,
"s": 29335,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29400,
"s": 29381,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29444,
"s": 29400,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 29470,
"s": 29444,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29504,
"s": 29470,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29551,
"s": 29504,
"text": "Implementing a Linked List in Java using Class"
}
]
|
All permutations of a string using iteration? | In this section we will see how to get all permutations of a string. The recursive approach is very simple. It uses the back-tracking procedure. But here we will use the iterative approach.
All permutations of a string ABC are like {ABC, ACB, BAC, BCA, CAB, CBA}. Let us see the algorithm to get the better idea.
begin
sort the characters of the string
while true, do
print the string str
i := length of str – 1
while str[i - 1] >= str[i], do
i := i – 1
if i is 0, then
return
end if
done
j := length of str – 1
while j > i AND str[j] <= str[i – 1], do
j := j – 1
done
exchange the characters from position str[i - 1], str[j]
reverse the string.
done
end
Live Demo
#include <iostream>
#include <algorithm>
using namespace std;
void getAllPerm(string str){
sort(str.begin(), str.end());
while (true){
cout << str << endl;
int i = str.length() - 1;
while (str[i-1] >= str[i]){
if (--i == 0)
return;
}
int j = str.length() - 1;
while (j > i && str[j] <= str[i - 1])
j--;
swap(str[i - 1], str[j]);
reverse (str.begin() + i, str.end());
}
}
int main(){
string str = "WXYZ";
getAllPerm(str);
}
WXYZ
WXZY
WYXZ
WYZX
WZXY
WZYX
XWYZ
XWZY
XYWZ
XYZW
XZWY
XZYW
YWXZ
YWZX
YXWZ
YXZW
YZWX
YZXW
ZWXY
ZWYX
ZXWY
ZXYW
ZYWX
ZYXW | [
{
"code": null,
"e": 1252,
"s": 1062,
"text": "In this section we will see how to get all permutations of a string. The recursive approach is very simple. It uses the back-tracking procedure. But here we will use the iterative approach."
},
{
"code": null,
"e": 1375,
"s": 1252,
"text": "All permutations of a string ABC are like {ABC, ACB, BAC, BCA, CAB, CBA}. Let us see the algorithm to get the better idea."
},
{
"code": null,
"e": 1828,
"s": 1375,
"text": "begin\n sort the characters of the string\n while true, do\n print the string str\n i := length of str – 1\n while str[i - 1] >= str[i], do\n i := i – 1\n if i is 0, then\n return\n end if\n done\n j := length of str – 1\n while j > i AND str[j] <= str[i – 1], do\n j := j – 1\n done\n exchange the characters from position str[i - 1], str[j]\n reverse the string.\n done\nend"
},
{
"code": null,
"e": 1839,
"s": 1828,
"text": " Live Demo"
},
{
"code": null,
"e": 2349,
"s": 1839,
"text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nvoid getAllPerm(string str){\n sort(str.begin(), str.end());\n while (true){\n cout << str << endl;\n int i = str.length() - 1;\n while (str[i-1] >= str[i]){\n if (--i == 0)\n return;\n }\n int j = str.length() - 1;\n while (j > i && str[j] <= str[i - 1])\n j--;\n swap(str[i - 1], str[j]);\n reverse (str.begin() + i, str.end());\n }\n}\nint main(){\n string str = \"WXYZ\";\n getAllPerm(str);\n}"
},
{
"code": null,
"e": 2469,
"s": 2349,
"text": "WXYZ\nWXZY\nWYXZ\nWYZX\nWZXY\nWZYX\nXWYZ\nXWZY\nXYWZ\nXYZW\nXZWY\nXZYW\nYWXZ\nYWZX\nYXWZ\nYXZW\nYZWX\nYZXW\nZWXY\nZWYX\nZXWY\nZXYW\nZYWX\nZYXW"
}
]
|
How to remove a member from the local group using PowerShell? | To remove a member from the local group using PowerShell, we can use the RemoveLocalGroupMember command. This command is available in the module Microsoft.PowerShell.LocalAccounts in and above PowerShell version 5.1.
To use this command, we need to provide two parameter values. One is the -Group (Local Group Name) and the second is -Member (Name of the Member to remove). For example,
Remove-LocalGroupMember -Group Administrators -Member TestUser
The above command will remove TestUser from the local group Administrators.
To use the above command on the remote computer, we need to use Invoke-Command. For example,
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
Remove-LocalGroupMember -Group "Administrators" -Member "LabDomain\Alpha"
}
The above command will remove LabDomain\Alpha user from the local Administrators group on remote computers.
If you don’t have the LocalAccounts module available or the PowerShell version is below 5.1 then you can use the cmd command as shown below.
net localgroup Administrators labdomain\alpha /delete
In the above example, labdomain\alpha will be removed from the local group Administrators using cmd command. You can execute this command remotely using Invoke-Command method,
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
net localgroup Administrators labdomain\alpha /delete
} | [
{
"code": null,
"e": 1279,
"s": 1062,
"text": "To remove a member from the local group using PowerShell, we can use the RemoveLocalGroupMember command. This command is available in the module Microsoft.PowerShell.LocalAccounts in and above PowerShell version 5.1."
},
{
"code": null,
"e": 1449,
"s": 1279,
"text": "To use this command, we need to provide two parameter values. One is the -Group (Local Group Name) and the second is -Member (Name of the Member to remove). For example,"
},
{
"code": null,
"e": 1512,
"s": 1449,
"text": "Remove-LocalGroupMember -Group Administrators -Member TestUser"
},
{
"code": null,
"e": 1588,
"s": 1512,
"text": "The above command will remove TestUser from the local group Administrators."
},
{
"code": null,
"e": 1681,
"s": 1588,
"text": "To use the above command on the remote computer, we need to use Invoke-Command. For example,"
},
{
"code": null,
"e": 1831,
"s": 1681,
"text": "Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{\n Remove-LocalGroupMember -Group \"Administrators\" -Member \"LabDomain\\Alpha\"\n}"
},
{
"code": null,
"e": 1939,
"s": 1831,
"text": "The above command will remove LabDomain\\Alpha user from the local Administrators group on remote computers."
},
{
"code": null,
"e": 2080,
"s": 1939,
"text": "If you don’t have the LocalAccounts module available or the PowerShell version is below 5.1 then you can use the cmd command as shown below."
},
{
"code": null,
"e": 2134,
"s": 2080,
"text": "net localgroup Administrators labdomain\\alpha /delete"
},
{
"code": null,
"e": 2310,
"s": 2134,
"text": "In the above example, labdomain\\alpha will be removed from the local group Administrators using cmd command. You can execute this command remotely using Invoke-Command method,"
},
{
"code": null,
"e": 2440,
"s": 2310,
"text": "Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{\n net localgroup Administrators labdomain\\alpha /delete\n}"
}
]
|
C program for a number to be expressed as a sum of two prime numbers. | Find out if a given number can be expressed as sum of two prime numbers or not.
Given a positive integer N, we need to check if the number N can be represented as a sum of two prime numbers.
Consider an example given below −
20 can be expressed as sum of two prime numbers 3 and 17, 13 and 7.
20= 3+7
20= 13+7
Refer an algorithm given below for expressing a given number as a sum of two prime numbers.
Step 1 − Input the number to be checked at run time.
Step 2 − Repeat from i = 2 to (num/2).
Step 3 − Check i is a prime number.
Step 4 − If i is prime, check if (n - i) is a prime number.
Step 5 − If both (i)and (n - i) are primes, then, the given number can be represented as the sum of primes i and (n - i).
Following is the C program for expressing a given number as a sum of two prime numbers −
Live Demo
#include <stdio.h>
int Sum(int n);
int main(){
int num, i;
printf("Enter number: ");
scanf("%d", &num);
int flag = 0;
for(i = 2; i <= num/2; ++i){
if (sum(i) == 1){
if (sum(num-i) == 1){
printf("\nThe given %d can be expressed as the sum of %d and %d\n\n", num, i, num - i);
flag = 1;
}
}
}
if (flag == 0)
printf("The given %d cannot be expressed as the sum of two prime numbers\n", num);
return 0;
}
//check if a number is prime or not
int sum(int n){
int i, isPrime = 1;
for(i = 2; i <= n/2; ++i){
if(n % i == 0){
isPrime = 0;
break;
}
}
return isPrime;
}
When the above program is executed, it produces the following output −
Run 1:
Enter number: 34
The given 34 can be expressed as the sum of 3 and 31
The given 34 can be expressed as the sum of 5 and 29
The given 34 can be expressed as the sum of 11 and 23
The given 34 can be expressed as the sum of 17 and 17
Run 2:
Enter number: 11
The given 11 cannot be expressed as the sum of two prime numbers | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "Find out if a given number can be expressed as sum of two prime numbers or not."
},
{
"code": null,
"e": 1253,
"s": 1142,
"text": "Given a positive integer N, we need to check if the number N can be represented as a sum of two prime numbers."
},
{
"code": null,
"e": 1287,
"s": 1253,
"text": "Consider an example given below −"
},
{
"code": null,
"e": 1355,
"s": 1287,
"text": "20 can be expressed as sum of two prime numbers 3 and 17, 13 and 7."
},
{
"code": null,
"e": 1363,
"s": 1355,
"text": "20= 3+7"
},
{
"code": null,
"e": 1372,
"s": 1363,
"text": "20= 13+7"
},
{
"code": null,
"e": 1464,
"s": 1372,
"text": "Refer an algorithm given below for expressing a given number as a sum of two prime numbers."
},
{
"code": null,
"e": 1517,
"s": 1464,
"text": "Step 1 − Input the number to be checked at run time."
},
{
"code": null,
"e": 1556,
"s": 1517,
"text": "Step 2 − Repeat from i = 2 to (num/2)."
},
{
"code": null,
"e": 1592,
"s": 1556,
"text": "Step 3 − Check i is a prime number."
},
{
"code": null,
"e": 1652,
"s": 1592,
"text": "Step 4 − If i is prime, check if (n - i) is a prime number."
},
{
"code": null,
"e": 1774,
"s": 1652,
"text": "Step 5 − If both (i)and (n - i) are primes, then, the given number can be represented as the sum of primes i and (n - i)."
},
{
"code": null,
"e": 1863,
"s": 1774,
"text": "Following is the C program for expressing a given number as a sum of two prime numbers −"
},
{
"code": null,
"e": 1874,
"s": 1863,
"text": " Live Demo"
},
{
"code": null,
"e": 2555,
"s": 1874,
"text": "#include <stdio.h>\nint Sum(int n);\nint main(){\n int num, i;\n printf(\"Enter number: \");\n scanf(\"%d\", &num);\n int flag = 0;\n for(i = 2; i <= num/2; ++i){\n if (sum(i) == 1){\n if (sum(num-i) == 1){\n printf(\"\\nThe given %d can be expressed as the sum of %d and %d\\n\\n\", num, i, num - i);\n flag = 1;\n }\n }\n }\n if (flag == 0)\n printf(\"The given %d cannot be expressed as the sum of two prime numbers\\n\", num);\n return 0;\n}\n//check if a number is prime or not\nint sum(int n){\n int i, isPrime = 1;\n for(i = 2; i <= n/2; ++i){\n if(n % i == 0){\n isPrime = 0;\n break;\n }\n }\n return isPrime;\n}"
},
{
"code": null,
"e": 2626,
"s": 2555,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2953,
"s": 2626,
"text": "Run 1:\nEnter number: 34\nThe given 34 can be expressed as the sum of 3 and 31\nThe given 34 can be expressed as the sum of 5 and 29\nThe given 34 can be expressed as the sum of 11 and 23\nThe given 34 can be expressed as the sum of 17 and 17\nRun 2:\nEnter number: 11\nThe given 11 cannot be expressed as the sum of two prime numbers"
}
]
|
Java Generics - Guidelines for Wildcard Use | Wildcards can be used in three ways −
Upper bound Wildcard − ? extends Type.
Upper bound Wildcard − ? extends Type.
Lower bound Wildcard − ? super Type.
Lower bound Wildcard − ? super Type.
Unbounded Wildcard − ?
Unbounded Wildcard − ?
In order to decide which type of wildcard best suits the condition, let's first classify the type of parameters passed to a method as in and out parameter.
in variable − An in variable provides data to the code. For example, copy(src, dest). Here src acts as in variable being data to be copied.
in variable − An in variable provides data to the code. For example, copy(src, dest). Here src acts as in variable being data to be copied.
out variable − An out variable holds data updated by the code. For example, copy(src, dest). Here dest acts as in variable having copied data.
out variable − An out variable holds data updated by the code. For example, copy(src, dest). Here dest acts as in variable having copied data.
Upper bound wildcard − If a variable is of in category, use extends keyword with wildcard.
Upper bound wildcard − If a variable is of in category, use extends keyword with wildcard.
Lower bound wildcard − If a variable is of out category, use super keyword with wildcard.
Lower bound wildcard − If a variable is of out category, use super keyword with wildcard.
Unbounded wildcard − If a variable can be accessed using Object class method then use an unbound wildcard.
Unbounded wildcard − If a variable can be accessed using Object class method then use an unbound wildcard.
No wildcard − If code is accessing variable in both in and out category then do not use wildcards.
No wildcard − If code is accessing variable in both in and out category then do not use wildcards.
Following example illustrates the above mentioned concepts.
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class GenericsTester {
//Upper bound wildcard
//in category
public static void deleteCat(List<? extends Cat> catList, Cat cat) {
catList.remove(cat);
System.out.println("Cat Removed");
}
//Lower bound wildcard
//out category
public static void addCat(List<? super RedCat> catList) {
catList.add(new RedCat("Red Cat"));
System.out.println("Cat Added");
}
//Unbounded wildcard
//Using Object method toString()
public static void printAll(List<?> list) {
for (Object item : list)
System.out.println(item + " ");
}
public static void main(String[] args) {
List<Animal> animalList= new ArrayList<Animal>();
List<RedCat> redCatList= new ArrayList<RedCat>();
//add list of super class Animal of Cat class
addCat(animalList);
//add list of Cat class
addCat(redCatList);
addCat(redCatList);
//print all animals
printAll(animalList);
printAll(redCatList);
Cat cat = redCatList.get(0);
//delete cat
deleteCat(redCatList, cat);
printAll(redCatList);
}
}
class Animal {
String name;
Animal(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
class Cat extends Animal {
Cat(String name) {
super(name);
}
}
class RedCat extends Cat {
RedCat(String name) {
super(name);
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
}
This will produce the following result −
Cat Added
Cat Added
Cat Added
Red Cat
Red Cat
Red Cat
Cat Removed
Red Cat
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2678,
"s": 2640,
"text": "Wildcards can be used in three ways −"
},
{
"code": null,
"e": 2717,
"s": 2678,
"text": "Upper bound Wildcard − ? extends Type."
},
{
"code": null,
"e": 2756,
"s": 2717,
"text": "Upper bound Wildcard − ? extends Type."
},
{
"code": null,
"e": 2793,
"s": 2756,
"text": "Lower bound Wildcard − ? super Type."
},
{
"code": null,
"e": 2830,
"s": 2793,
"text": "Lower bound Wildcard − ? super Type."
},
{
"code": null,
"e": 2853,
"s": 2830,
"text": "Unbounded Wildcard − ?"
},
{
"code": null,
"e": 2876,
"s": 2853,
"text": "Unbounded Wildcard − ?"
},
{
"code": null,
"e": 3032,
"s": 2876,
"text": "In order to decide which type of wildcard best suits the condition, let's first classify the type of parameters passed to a method as in and out parameter."
},
{
"code": null,
"e": 3172,
"s": 3032,
"text": "in variable − An in variable provides data to the code. For example, copy(src, dest). Here src acts as in variable being data to be copied."
},
{
"code": null,
"e": 3312,
"s": 3172,
"text": "in variable − An in variable provides data to the code. For example, copy(src, dest). Here src acts as in variable being data to be copied."
},
{
"code": null,
"e": 3455,
"s": 3312,
"text": "out variable − An out variable holds data updated by the code. For example, copy(src, dest). Here dest acts as in variable having copied data."
},
{
"code": null,
"e": 3598,
"s": 3455,
"text": "out variable − An out variable holds data updated by the code. For example, copy(src, dest). Here dest acts as in variable having copied data."
},
{
"code": null,
"e": 3689,
"s": 3598,
"text": "Upper bound wildcard − If a variable is of in category, use extends keyword with wildcard."
},
{
"code": null,
"e": 3780,
"s": 3689,
"text": "Upper bound wildcard − If a variable is of in category, use extends keyword with wildcard."
},
{
"code": null,
"e": 3870,
"s": 3780,
"text": "Lower bound wildcard − If a variable is of out category, use super keyword with wildcard."
},
{
"code": null,
"e": 3960,
"s": 3870,
"text": "Lower bound wildcard − If a variable is of out category, use super keyword with wildcard."
},
{
"code": null,
"e": 4067,
"s": 3960,
"text": "Unbounded wildcard − If a variable can be accessed using Object class method then use an unbound wildcard."
},
{
"code": null,
"e": 4174,
"s": 4067,
"text": "Unbounded wildcard − If a variable can be accessed using Object class method then use an unbound wildcard."
},
{
"code": null,
"e": 4273,
"s": 4174,
"text": "No wildcard − If code is accessing variable in both in and out category then do not use wildcards."
},
{
"code": null,
"e": 4372,
"s": 4273,
"text": "No wildcard − If code is accessing variable in both in and out category then do not use wildcards."
},
{
"code": null,
"e": 4432,
"s": 4372,
"text": "Following example illustrates the above mentioned concepts."
},
{
"code": null,
"e": 6016,
"s": 4432,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class GenericsTester {\n\n //Upper bound wildcard\n //in category\n public static void deleteCat(List<? extends Cat> catList, Cat cat) {\n catList.remove(cat);\n System.out.println(\"Cat Removed\");\n }\n\n //Lower bound wildcard\n //out category\n public static void addCat(List<? super RedCat> catList) {\n catList.add(new RedCat(\"Red Cat\"));\n System.out.println(\"Cat Added\");\n }\n\n //Unbounded wildcard\n //Using Object method toString()\n public static void printAll(List<?> list) {\n for (Object item : list)\n System.out.println(item + \" \");\n }\n\n public static void main(String[] args) {\n\n List<Animal> animalList= new ArrayList<Animal>();\n List<RedCat> redCatList= new ArrayList<RedCat>();\n\n //add list of super class Animal of Cat class\n addCat(animalList);\n //add list of Cat class\n addCat(redCatList); \n addCat(redCatList); \n\n //print all animals\n printAll(animalList);\n printAll(redCatList);\n\n Cat cat = redCatList.get(0);\n //delete cat\n deleteCat(redCatList, cat);\n printAll(redCatList); \n }\n}\n\nclass Animal {\n String name;\n Animal(String name) { \n this.name = name;\n }\n public String toString() { \n return name;\n }\n}\n\nclass Cat extends Animal { \n Cat(String name) {\n super(name);\n }\n}\n\nclass RedCat extends Cat {\n RedCat(String name) {\n super(name);\n }\n}\n\nclass Dog extends Animal {\n Dog(String name) {\n super(name);\n }\n}"
},
{
"code": null,
"e": 6057,
"s": 6016,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6136,
"s": 6057,
"text": "Cat Added\nCat Added\nCat Added\nRed Cat \nRed Cat \nRed Cat \nCat Removed\nRed Cat \n"
},
{
"code": null,
"e": 6169,
"s": 6136,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6185,
"s": 6169,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6218,
"s": 6185,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6234,
"s": 6218,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6269,
"s": 6234,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6283,
"s": 6269,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6317,
"s": 6283,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6331,
"s": 6317,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6368,
"s": 6331,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6383,
"s": 6368,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6416,
"s": 6383,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6435,
"s": 6416,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6442,
"s": 6435,
"text": " Print"
},
{
"code": null,
"e": 6453,
"s": 6442,
"text": " Add Notes"
}
]
|
How to find the unique values in a column of an R data frame? | Categorical variables have multiple categories but if the data set is large and the categories are also large in numbers then it becomes a little difficult to recognize them. Therefore, we can extract unique values for categorical variables that will help us to easily recognize the categories of a categorical variable. We can do this by using unique for every column of an R data frame.
Consider the below data frame −
> x1<-rep(c("A","B","C","D"),each=5)
> x2<-rep(c(5,10,15,20),times=c(2,8,6,4))
> x3<-rep(c("India","Russia","China","Indonesia","Iceland"),times=c(4,3,5,2,6))
> x4<-rep(c(letters[1:10]),times=2)
> df<-data.frame(x1,x2,x3,x4)
> df
x1 x2 x3 x4
1 A 5 India a
2 A 5 India b
3 A 10 India c
4 A 10 India d
5 A 10 Russia e
6 B 10 Russia f
7 B 10 Russia g
8 B 10 China h
9 B 10 China i
10 B 10 China j
11 C 15 China a
12 C 15 China b
13 C 15 Indonesia c
14 C 15 Indonesia d
15 C 15 Iceland e
16 D 15 Iceland f
17 D 20 Iceland g
18 D 20 Iceland h
19 D 20 Iceland i
20 D 20 Iceland j
Finding the unique values in column x1 −
> unique(df[c("x1")])
x1
1 A
6 B
11 C
16 D
Finding the unique values in column x2 −
> unique(df[c("x2")])
x2
1 5
3 10
11 15
17 20
Finding the unique values in column x3 −
> unique(df[c("x3")])
x3
1 India
5 Russia
8 China
13 Indonesia
15 Iceland
Finding the unique values in column x4 −
> unique(df[c("x4")])
x4
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
10 j | [
{
"code": null,
"e": 1451,
"s": 1062,
"text": "Categorical variables have multiple categories but if the data set is large and the categories are also large in numbers then it becomes a little difficult to recognize them. Therefore, we can extract unique values for categorical variables that will help us to easily recognize the categories of a categorical variable. We can do this by using unique for every column of an R data frame."
},
{
"code": null,
"e": 1483,
"s": 1451,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 2133,
"s": 1483,
"text": "> x1<-rep(c(\"A\",\"B\",\"C\",\"D\"),each=5)\n> x2<-rep(c(5,10,15,20),times=c(2,8,6,4))\n> x3<-rep(c(\"India\",\"Russia\",\"China\",\"Indonesia\",\"Iceland\"),times=c(4,3,5,2,6))\n> x4<-rep(c(letters[1:10]),times=2)\n> df<-data.frame(x1,x2,x3,x4)\n> df\n x1 x2 x3 x4\n1 A 5 India a\n2 A 5 India b\n3 A 10 India c\n4 A 10 India d\n5 A 10 Russia e\n6 B 10 Russia f\n7 B 10 Russia g\n8 B 10 China h\n9 B 10 China i\n10 B 10 China j\n11 C 15 China a\n12 C 15 China b\n13 C 15 Indonesia c\n14 C 15 Indonesia d\n15 C 15 Iceland e\n16 D 15 Iceland f\n17 D 20 Iceland g\n18 D 20 Iceland h\n19 D 20 Iceland i\n20 D 20 Iceland j"
},
{
"code": null,
"e": 2174,
"s": 2133,
"text": "Finding the unique values in column x1 −"
},
{
"code": null,
"e": 2217,
"s": 2174,
"text": "> unique(df[c(\"x1\")])\nx1\n1 A\n6 B\n11 C\n16 D"
},
{
"code": null,
"e": 2258,
"s": 2217,
"text": "Finding the unique values in column x2 −"
},
{
"code": null,
"e": 2304,
"s": 2258,
"text": "> unique(df[c(\"x2\")])\nx2\n1 5\n3 10\n11 15\n17 20"
},
{
"code": null,
"e": 2345,
"s": 2304,
"text": "Finding the unique values in column x3 −"
},
{
"code": null,
"e": 2419,
"s": 2345,
"text": "> unique(df[c(\"x3\")])\nx3\n1 India\n5 Russia\n8 China\n13 Indonesia\n15 Iceland"
},
{
"code": null,
"e": 2460,
"s": 2419,
"text": "Finding the unique values in column x4 −"
},
{
"code": null,
"e": 2526,
"s": 2460,
"text": "> unique(df[c(\"x4\")])\nx4\n1 a\n2 b\n3 c\n4 d\n5 e\n6 f\n7 g\n8 h\n9 i\n10 j"
}
]
|
How to update field to add value to existing value in MySQL? | You can update field to add value to an existing value with the help of UPDATE and SET command. The syntax is as follows −
UPDATE yourTableName SET yourColumnName = yourColumnName+integerValueToAdd WHERE yourCondition;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table addingValueToExisting
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> Name varchar(30),
-> GameScore int,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.58 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into addingValueToExisting(Name,GameScore) values('John',89);
Query OK, 1 row affected (0.11 sec)
mysql> insert into addingValueToExisting(Name,GameScore) values('Mike',56);
Query OK, 1 row affected (0.28 sec)
mysql> insert into addingValueToExisting(Name,GameScore) values('Sam',99);
Query OK, 1 row affected (0.18 sec)
mysql> insert into addingValueToExisting(Name,GameScore) values('Carol',100);
Query OK, 1 row affected (0.17 sec)
mysql> insert into addingValueToExisting(Name,GameScore) values('David',67);
Query OK, 1 row affected (0.25 sec)
mysql> insert into addingValueToExisting(Name,GameScore) values('Bob',78);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from addingValueToExisting;
The following is the output −
+----+-------+-----------+
| Id | Name | GameScore |
+----+-------+-----------+
| 1 | John | 89 |
| 2 | Mike | 56 |
| 3 | Sam | 99 |
| 4 | Carol | 100 |
| 5 | David | 67 |
| 6 | Bob | 78 |
+----+-------+-----------+
6 rows in set (0.00 sec)
Update field to add a value to existing value. For our example, let us update 100 with the value 110 by adding 10. The query is as follows −
mysql> update addingValueToExisting set GameScore = GameScore+10 where Id = 4;
Query OK, 1 row affected (0.23 sec)
Rows matched − 1 Changed − 1 Warnings − 0
Check the specific record has been updated or not. The query is as follows −
mysql> select *from addingValueToExisting where Id = 4;
The following is the output −
+----+-------+-----------+
| Id | Name | GameScore |
+----+-------+-----------+
| 4 | Carol | 110 |
+----+-------+-----------+
1 row in set (0.00 sec)
Look at the above output, the value 100 is incremented by 10, which is now 110. | [
{
"code": null,
"e": 1185,
"s": 1062,
"text": "You can update field to add value to an existing value with the help of UPDATE and SET command. The syntax is as follows −"
},
{
"code": null,
"e": 1281,
"s": 1185,
"text": "UPDATE yourTableName SET yourColumnName = yourColumnName+integerValueToAdd WHERE yourCondition;"
},
{
"code": null,
"e": 1380,
"s": 1281,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1581,
"s": 1380,
"text": "mysql> create table addingValueToExisting\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Name varchar(30),\n -> GameScore int,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1657,
"s": 1581,
"text": "Insert records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2335,
"s": 1657,
"text": "mysql> insert into addingValueToExisting(Name,GameScore) values('John',89);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into addingValueToExisting(Name,GameScore) values('Mike',56);\nQuery OK, 1 row affected (0.28 sec)\n\nmysql> insert into addingValueToExisting(Name,GameScore) values('Sam',99);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into addingValueToExisting(Name,GameScore) values('Carol',100);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into addingValueToExisting(Name,GameScore) values('David',67);\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into addingValueToExisting(Name,GameScore) values('Bob',78);\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 2420,
"s": 2335,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2463,
"s": 2420,
"text": "mysql> select *from addingValueToExisting;"
},
{
"code": null,
"e": 2493,
"s": 2463,
"text": "The following is the output −"
},
{
"code": null,
"e": 2788,
"s": 2493,
"text": "+----+-------+-----------+\n| Id | Name | GameScore |\n+----+-------+-----------+\n| 1 | John | 89 |\n| 2 | Mike | 56 |\n| 3 | Sam | 99 |\n| 4 | Carol | 100 |\n| 5 | David | 67 |\n| 6 | Bob | 78 |\n+----+-------+-----------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2929,
"s": 2788,
"text": "Update field to add a value to existing value. For our example, let us update 100 with the value 110 by adding 10. The query is as follows −"
},
{
"code": null,
"e": 3086,
"s": 2929,
"text": "mysql> update addingValueToExisting set GameScore = GameScore+10 where Id = 4;\nQuery OK, 1 row affected (0.23 sec)\nRows matched − 1 Changed − 1 Warnings − 0"
},
{
"code": null,
"e": 3163,
"s": 3086,
"text": "Check the specific record has been updated or not. The query is as follows −"
},
{
"code": null,
"e": 3219,
"s": 3163,
"text": "mysql> select *from addingValueToExisting where Id = 4;"
},
{
"code": null,
"e": 3249,
"s": 3219,
"text": "The following is the output −"
},
{
"code": null,
"e": 3408,
"s": 3249,
"text": "+----+-------+-----------+\n| Id | Name | GameScore |\n+----+-------+-----------+\n| 4 | Carol | 110 |\n+----+-------+-----------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 3488,
"s": 3408,
"text": "Look at the above output, the value 100 is incremented by 10, which is now 110."
}
]
|
Let’s be A* — Learn and Code a Path Planning algorithm to fly a Drone — Part II | by Percy Jaiswal | Towards Data Science | Unity Simulator, Python Environment Installation and Starter FilesBefore beginning to code anything, we need to get our setup and tools installed. We begin this by downloading required Unity simulator that’s appropriate for your operating system from here. Next, we get required Python libraries installed. I would encourage you to create a separate Python environment (in any IDE of your choice) so as to keep it clean and separate. Follow installation instructions from this github repo. Finally, we download this github repo to get our start files. Make sure you got your setup correct by checking if you are able to run instructions provided in Step# 4 of above provided github repo for starter files.
Starter Code To begin with this project, we are provided with two scripts, motion_planning.py and planning_utils.py. Here you’ll also find a file called colliders.csv, which contains the 2.5D map of the simulator environment. A 2.5D map is nothing but a 2D map (x, y location) with additional ‘height’ information for the obstacle. We will explore this file little more once we begin coding. The main function in motion_planning.py establishes a “Mavlink” connection with simulator and creates a ‘drone’ object of ‘MotionPlanning’ class. Motion Planning class contains lot of built in functions already prepared for us. It contains callback functions ‘local_position_callback’, ‘velocity_callback’, ‘state_callback’.
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--port', type=int, default=5760, help='Port number') parser.add_argument('--host', type=str, default='127.0.0.1', help="host address, i.e. '127.0.0.1'") args = parser.parse_args()conn = MavlinkConnection('tcp:{0}:{1}'.format(args.host, args.port), timeout=60) drone = MotionPlanning(conn) time.sleep(1)drone.start()
What are callback functions? A callback function is intended to be executed only when a particular event triggers it. For e.g., if you look at code line ‘self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback)’ what it is doing is registering MsgID.LOCAL_POSITION and self.local_position_callback as key-value pair in a python dictionary (implemented inside ‘self.register_callback’ function). Now whenever value in ‘MsgID.LOCAL_POSITION’ variable changes, it will trigger a call to ‘self.local_position_callback’ function. Hence it’s called a callback function. Because the function is not called during normal ‘sequential’ flow of program, but instead it gets called only when a particular event has happened, which is change in value of ‘MsgID.LOCAL_POSITION’ in this particular case.
class MotionPlanning(Drone):def __init__(self, connection): super().__init__(connection) self.target_position = np.array([0.0, 0.0, 0.0]) self.waypoints = [] self.in_mission = True self.check_state = {} # initial state self.flight_state = States.MANUAL # register all your callbacks here self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback) self.register_callback(MsgID.LOCAL_VELOCITY, self.velocity_callback) self.register_callback(MsgID.STATE, self.state_callback)
This all callback functions form the core structure of overall program of flying drone. Various operations like take-off, landing, transitioning to waypoint following state, arming and disarming drone along with required callback functions are taken care of in this starter code. You can go over motion_planning.py file and understand this functions, but as the primary goal of this article is to explain the code for ‘plan_path’ function, we will not dwell too much on starter code. Once a drone has been armed, it has taken off successfully and transitioned into waypoint following state, we need to start sending it one waypoint at a time, which will be generated by our ‘plan_path’ function before drone even takes off.
Once we make sure our drone is armed (basically a system check to make sure all propellers and other systems are operating as per expectation), the first thing we done before taking off is prepare a valid path to follow. To begin simple, we plan to fly at constant height. We will also be keeping a ‘Safety_distance’ from obstacles in our map / world.
TARGET_ALTITUDE = 5SAFETY_DISTANCE = 5
Creat_GridIn order to create a path, we need a map, and that is provided to us in ‘colliders.csv’ file. Opening the file, we can see that first row contains ‘lat0’ and ‘lon0’ values. These are home location or 0, 0, 0 for our map.
Following lines read home latitude and longitude provided in 1st row of colliders.csv and set it as our home position.
# TODO: read lat0, lon0 from colliders into floating point values lat0_lon0 = pd.read_csv('colliders.csv', nrows = 1, header = None) lat0, lon0 = lat0_lon0.iloc[0,0], lat0_lon0.iloc[0,1] _, lat0 = lat0.split() _, lon0 = lon0.split() lat0 = np.float64(lat0) lon0 = np.float64(lon0)# TODO: set home position to (lat0, lon0, 0) self.set_home_position(lon0, lat0, 0)
When then check our current global position and convert it into local position, which will be with respect to home position we set earlier. We then print our current local and global position along with global home position value.
# TODO: retrieve current global position # TODO: convert to current local position using global_to_local()current_local_pos = global_to_local(self.global_position, self.global_home) # Me: checking current local positionprint ('current local position {0} and {1}'.format(current_local_pos[0], current_local_pos[1])) print('global home {0}, position {1}, local position {2}'.format(self.global_home, self.global_position, self.local_position))
Next we work on defining our map in grid format that we studied in part 1 of this series. We first read complete data from colliders.csv, and then pass that numpy array to function called ‘create_grid’.
# Read in obstacle mapdata = np.loadtxt('colliders.csv', delimiter=',', dtype='Float64', skiprows=3) # Define a grid for a particular altitude and safety margin around obstaclesgrid, north_offset, east_offset = create_grid(data, TARGET_ALTITUDE, SAFETY_DISTANCE)
Before we understand how ‘create_grid’ will create our grid map, we need to understand the format in which data is provided in colliders.csv. If we look at the heading for each column (as shown in row2 of image2), we see that we are given 3 positional values of a point — its x, y and z coordinates, and 3 distance values. The x, y and z coordinates are coordinates of a center point for an obstacle and 3 distances are its width, length and height values. Actually they are half of height, width and length, as they are distance from center point to one side of obstacle. Below diagram explains how both center point and dimensions values for obstacles are provided.
We will be creating maps similar to 2.5D structure explained in part 1. In fact, we will be going one step further. We have already fixed the flying altitude for our drone with ‘TARGET_ALTITUDE’ variable. So while creating map, we will only include an obstacle in our map if its height (PozZ + 2 * halfSizeZ) is greater than ‘TARGET_ALTITUDE’. If height of the obstacle is less than ‘TARGET_ALTITUDE’ we will just assume it to be a free space as our drone can fly over it. This approach greatly reduces the space and processing complexity that our map needs.
With height parameter sorted out, we need to determine size of the map which we need to create. For this, we first determine the closest and furthest point from our origin in both X and Y direction. Consider X direction to be North and Y direction to be East, we can get value of closet and furthest point in both directions as follows:
# minimum and maximum north coordinatesnorth_min = np.floor(np.min(data[:, 0] - data[:, 3]))north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))# minimum and maximum east coordinateseast_min = np.floor(np.min(data[:, 1] - data[:, 4]))east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))# given the minimum and maximum coordinates we can# calculate the size of the grid.north_size = int(np.ceil((north_max - north_min + 1)))east_size = int(np.ceil((east_max - east_min + 1)))
And finally we initialize our grid map as numpy zeros array
# Initialize an empty gridgrid = np.zeros((north_size, east_size))
Next, we will iterate over each obstacle from our colliders.csv data, which we have already captured in variable ‘data’. We will first compare whether obstacle’s height is above ‘TARGET_ALTITUDE’, and if it is, then we will mark the area occupied by the obstacle + a safety distance we configured in variable ‘SAFETY_DISTANCE’ as 1 in our grid world. Finally, we return our grid world along with north_min and east_min values.
# Populate the grid with obstacles for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i, :] if alt + d_alt + safety_distance > drone_altitude: obstacle = [ int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)), int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)), int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)), int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)), ] grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1return grid, int(north_min), int(east_min)
A small caveat which we need to understand is, the obstacles in colliders and our current local location are with respect to global home, which we had configured in with help of lat0 and lon0 variables. Whereas, the grid world which we create in create_grid function has origin at first obstacle point. Remember how we had calculated north min & max and east min & max and then north and east size to create a grid. Well, because of that there is an offset between colliders & our drone’s positional values and corresponding same position in our grid world. Following diagram will help us understand it better.
So every time we are trying to map a value from our drone’s positional sensor to grid world, we need to subtract north and east offset respectively. This offset value is nothing but north_min and east_min returned by create_grid function. We set our current position in grid_world as
# TODO: convert start position to current position rather than map centergrid_start = (int(current_local_pos[0] - north_offset), int(current_local_pos[1] - east_offset))
Assign a goal location of our choice
# Take GPS co-ordinates as Grid goal -Megrid_goal = (-122.396582, 37.795714, 0)grid_goal = global_to_local(grid_goal, self.global_home)grid_goal = (int(grid_goal[0] - north_offset), int(grid_goal[1] - east_offset))
Print our start and goal location and off we go on our way to be A*!!
print('Local Start and Goal: ', grid_start, grid_goal)path, _ = a_star(grid, heuristic, grid_start, grid_goal)
A* in the city We pass the grid we just now created in above section, a heuristic function and our start and goal location as arguments to a_star function. Hopefully the concepts we had gained in part 1 of this series will help us understand code for this function better. In fact let’s revisit the list of steps we had gone through while understanding Breadth First Algorithm. Knowing which step of our algorithm is performed in which set of lines will help us understand below code block better. As stated in Part 1, a A* algorithm adds ‘cost’ and ‘heuristic’ function on top of a BFS. So along with code for implementing below steps, it will include adding and accessing ‘cost’ and ‘heuristic’ functions too. The backbone of a breadth-first search consists of these basic steps: 1. Add a node/vertex from the grid to a queue of nodes to be “visited”. 2. Visit the topmost node in the queue, and mark it as such. 3. If that node has any neighbors, check to see if they have been “visited” or not. 4. Add any neighboring nodes that still need to be “visited” to the queue. 5. Remove current node we’ve visited from the queue. We first declare few variables. We will be using a Priority Queue to store nodes we need to visit. A typical pattern for entries in priority queue is a tuple in the form: (priority_number, data). The lowest valued entries are retrieved first and as we will be using ‘cost to reach corresponding node’ value as ‘priority_number’, whenever we will ‘get’ (or pop) an element from this priority queue, we will get an element which has least ‘cost’ value. We start at our ‘start’ node.
path = [] path_cost = 0 queue = PriorityQueue() queue.put((0, start)) visited = set(start)branch = {}found = False# Check till we have searched all nodes or have found our ‘goal’while not queue.empty(): item = queue.get() # Step2. Visit the topmost node in the queue current_cost = item[0] current_node = item[1] if current_node == goal: print('Found a path.') found = True break else:#Step3. If that node has any neighbors, check to see if they have been “visited” or not. for a in valid_actions(grid, current_node): next_node = (current_node[0] + a.delta[0], current_node[1] + a.delta[1]) new_cost = current_cost + a.cost + h(next_node, goal)#Step4. Add any neighboring nodes that still need to be “visited” to the queue. if next_node not in visited: visited.add(next_node) queue.put((new_cost, next_node)) branch[next_node] = (new_cost, current_node, a)
As we saw in part 1, whenever we reach a node in BFS algorithm, it is guaranteed to be the shortest path to that node from our ‘start’ location. So to keep track of path we are tracing, in a_star function, we will be maintaining a dictionary, for which ‘key’ will be the node we will be visiting next, and its value will be a tuple of current node, action to be taken from current node in order to reach next node and total cost to reach next node. This tuple (current node + action to take to reach next node) will represent the shortest path to reach next node coming from ‘start’ location. Now once we find ‘goal’ location, we will trace back the route to ‘start’ location with the help of this ‘branch’ dictionary. We first copy the value of total cost to reach ‘goal’ location. Next, as we know that node present in ‘value’ of dictionary lies on the shortest path, we will build our ‘path’ list as -> [goal, node present in value of branch[goal], ...]. And we will keep tracing back our route till we find ‘start’ location, adding nodes to ‘path’ list.
if found: # retrace steps n = goal path_cost = branch[n][0] path.append(goal) while branch[n][1] != start: path.append(branch[n][1]) n = branch[n][1] path.append(branch[n][1]) else: print('**********************') print('Failed to find a path!') print('**********************') return path[::-1], path_cost
Helper FunctionsPath Pruning: Once we have our path figured out, we will prune it by removing collinear points as explained in Collinearity Check section in Part 1. We take 3 consecutive points from our final path and check whether they lie on same line. We do this by calculating the area enclosed by selected 3 points. If it is very close to 0, we can assume that they lie on same line. We first convert a point in a 3 element (x-coordinate, y-coordinate, 1) to numpy array. We add this last element “1” so that we can arrange 3 vertices into a nice 3 x 3 matrix. After reshaping points in “points()” function, we create a matrix by concating them and then calculating the determinant of that matrix using a convenient np.linalg.det() function.Valid Actions: One function which was used by us in a_star is valid_actions (grid, current_node). This was used to carry out step# 3 of BFS algorithm, where we search for current node’s neighbours. We already have our action set (as explained in “Search space, Action set and Cost” section of Part1) and location of our current node. This function will return a subset of action set. It will check weather an action (i.e. moving up, down, left, right or diagonal) will lead us off grid or to an obstacle / No Fly zone node. And if that is the case, it will remove this action from list of valid actions feasible from current node.
Coming back to motion_planning.py, once we get pruned path, take each point from it, convert it into waypoint in local frame coordinate (by adding north and east offsets) and send it to autopilot using self.send_waypoints() function. And with that, we have finished coding our path planning A* algorithm. So without further ado, lets fire up Udacity’s drone simulator and run our motion_planning.py python file. You can find all the source code in my github repo here. If everything runs smoothly, you should be able to see your drone fly from a user configured starting and goal location like shown in below gif.
Hope you have enjoyed reading couple of articles in this series and now have a good understanding of fundamentals of A*.
If you found this article useful, you know what to do next 😊 Till next time....cheers!! | [
{
"code": null,
"e": 878,
"s": 172,
"text": "Unity Simulator, Python Environment Installation and Starter FilesBefore beginning to code anything, we need to get our setup and tools installed. We begin this by downloading required Unity simulator that’s appropriate for your operating system from here. Next, we get required Python libraries installed. I would encourage you to create a separate Python environment (in any IDE of your choice) so as to keep it clean and separate. Follow installation instructions from this github repo. Finally, we download this github repo to get our start files. Make sure you got your setup correct by checking if you are able to run instructions provided in Step# 4 of above provided github repo for starter files."
},
{
"code": null,
"e": 1595,
"s": 878,
"text": "Starter Code To begin with this project, we are provided with two scripts, motion_planning.py and planning_utils.py. Here you’ll also find a file called colliders.csv, which contains the 2.5D map of the simulator environment. A 2.5D map is nothing but a 2D map (x, y location) with additional ‘height’ information for the obstacle. We will explore this file little more once we begin coding. The main function in motion_planning.py establishes a “Mavlink” connection with simulator and creates a ‘drone’ object of ‘MotionPlanning’ class. Motion Planning class contains lot of built in functions already prepared for us. It contains callback functions ‘local_position_callback’, ‘velocity_callback’, ‘state_callback’."
},
{
"code": null,
"e": 2012,
"s": 1595,
"text": "if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('--port', type=int, default=5760, help='Port number') parser.add_argument('--host', type=str, default='127.0.0.1', help=\"host address, i.e. '127.0.0.1'\") args = parser.parse_args()conn = MavlinkConnection('tcp:{0}:{1}'.format(args.host, args.port), timeout=60) drone = MotionPlanning(conn) time.sleep(1)drone.start()"
},
{
"code": null,
"e": 2819,
"s": 2012,
"text": "What are callback functions? A callback function is intended to be executed only when a particular event triggers it. For e.g., if you look at code line ‘self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback)’ what it is doing is registering MsgID.LOCAL_POSITION and self.local_position_callback as key-value pair in a python dictionary (implemented inside ‘self.register_callback’ function). Now whenever value in ‘MsgID.LOCAL_POSITION’ variable changes, it will trigger a call to ‘self.local_position_callback’ function. Hence it’s called a callback function. Because the function is not called during normal ‘sequential’ flow of program, but instead it gets called only when a particular event has happened, which is change in value of ‘MsgID.LOCAL_POSITION’ in this particular case."
},
{
"code": null,
"e": 3385,
"s": 2819,
"text": "class MotionPlanning(Drone):def __init__(self, connection): super().__init__(connection) self.target_position = np.array([0.0, 0.0, 0.0]) self.waypoints = [] self.in_mission = True self.check_state = {} # initial state self.flight_state = States.MANUAL # register all your callbacks here self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback) self.register_callback(MsgID.LOCAL_VELOCITY, self.velocity_callback) self.register_callback(MsgID.STATE, self.state_callback)"
},
{
"code": null,
"e": 4109,
"s": 3385,
"text": "This all callback functions form the core structure of overall program of flying drone. Various operations like take-off, landing, transitioning to waypoint following state, arming and disarming drone along with required callback functions are taken care of in this starter code. You can go over motion_planning.py file and understand this functions, but as the primary goal of this article is to explain the code for ‘plan_path’ function, we will not dwell too much on starter code. Once a drone has been armed, it has taken off successfully and transitioned into waypoint following state, we need to start sending it one waypoint at a time, which will be generated by our ‘plan_path’ function before drone even takes off."
},
{
"code": null,
"e": 4461,
"s": 4109,
"text": "Once we make sure our drone is armed (basically a system check to make sure all propellers and other systems are operating as per expectation), the first thing we done before taking off is prepare a valid path to follow. To begin simple, we plan to fly at constant height. We will also be keeping a ‘Safety_distance’ from obstacles in our map / world."
},
{
"code": null,
"e": 4500,
"s": 4461,
"text": "TARGET_ALTITUDE = 5SAFETY_DISTANCE = 5"
},
{
"code": null,
"e": 4731,
"s": 4500,
"text": "Creat_GridIn order to create a path, we need a map, and that is provided to us in ‘colliders.csv’ file. Opening the file, we can see that first row contains ‘lat0’ and ‘lon0’ values. These are home location or 0, 0, 0 for our map."
},
{
"code": null,
"e": 4850,
"s": 4731,
"text": "Following lines read home latitude and longitude provided in 1st row of colliders.csv and set it as our home position."
},
{
"code": null,
"e": 5262,
"s": 4850,
"text": "# TODO: read lat0, lon0 from colliders into floating point values lat0_lon0 = pd.read_csv('colliders.csv', nrows = 1, header = None) lat0, lon0 = lat0_lon0.iloc[0,0], lat0_lon0.iloc[0,1] _, lat0 = lat0.split() _, lon0 = lon0.split() lat0 = np.float64(lat0) lon0 = np.float64(lon0)# TODO: set home position to (lat0, lon0, 0) self.set_home_position(lon0, lat0, 0)"
},
{
"code": null,
"e": 5493,
"s": 5262,
"text": "When then check our current global position and convert it into local position, which will be with respect to home position we set earlier. We then print our current local and global position along with global home position value."
},
{
"code": null,
"e": 6021,
"s": 5493,
"text": "# TODO: retrieve current global position # TODO: convert to current local position using global_to_local()current_local_pos = global_to_local(self.global_position, self.global_home) # Me: checking current local positionprint ('current local position {0} and {1}'.format(current_local_pos[0], current_local_pos[1])) print('global home {0}, position {1}, local position {2}'.format(self.global_home, self.global_position, self.local_position))"
},
{
"code": null,
"e": 6224,
"s": 6021,
"text": "Next we work on defining our map in grid format that we studied in part 1 of this series. We first read complete data from colliders.csv, and then pass that numpy array to function called ‘create_grid’."
},
{
"code": null,
"e": 6494,
"s": 6224,
"text": "# Read in obstacle mapdata = np.loadtxt('colliders.csv', delimiter=',', dtype='Float64', skiprows=3) # Define a grid for a particular altitude and safety margin around obstaclesgrid, north_offset, east_offset = create_grid(data, TARGET_ALTITUDE, SAFETY_DISTANCE)"
},
{
"code": null,
"e": 7162,
"s": 6494,
"text": "Before we understand how ‘create_grid’ will create our grid map, we need to understand the format in which data is provided in colliders.csv. If we look at the heading for each column (as shown in row2 of image2), we see that we are given 3 positional values of a point — its x, y and z coordinates, and 3 distance values. The x, y and z coordinates are coordinates of a center point for an obstacle and 3 distances are its width, length and height values. Actually they are half of height, width and length, as they are distance from center point to one side of obstacle. Below diagram explains how both center point and dimensions values for obstacles are provided."
},
{
"code": null,
"e": 7721,
"s": 7162,
"text": "We will be creating maps similar to 2.5D structure explained in part 1. In fact, we will be going one step further. We have already fixed the flying altitude for our drone with ‘TARGET_ALTITUDE’ variable. So while creating map, we will only include an obstacle in our map if its height (PozZ + 2 * halfSizeZ) is greater than ‘TARGET_ALTITUDE’. If height of the obstacle is less than ‘TARGET_ALTITUDE’ we will just assume it to be a free space as our drone can fly over it. This approach greatly reduces the space and processing complexity that our map needs."
},
{
"code": null,
"e": 8058,
"s": 7721,
"text": "With height parameter sorted out, we need to determine size of the map which we need to create. For this, we first determine the closest and furthest point from our origin in both X and Y direction. Consider X direction to be North and Y direction to be East, we can get value of closet and furthest point in both directions as follows:"
},
{
"code": null,
"e": 8532,
"s": 8058,
"text": "# minimum and maximum north coordinatesnorth_min = np.floor(np.min(data[:, 0] - data[:, 3]))north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))# minimum and maximum east coordinateseast_min = np.floor(np.min(data[:, 1] - data[:, 4]))east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))# given the minimum and maximum coordinates we can# calculate the size of the grid.north_size = int(np.ceil((north_max - north_min + 1)))east_size = int(np.ceil((east_max - east_min + 1)))"
},
{
"code": null,
"e": 8592,
"s": 8532,
"text": "And finally we initialize our grid map as numpy zeros array"
},
{
"code": null,
"e": 8659,
"s": 8592,
"text": "# Initialize an empty gridgrid = np.zeros((north_size, east_size))"
},
{
"code": null,
"e": 9086,
"s": 8659,
"text": "Next, we will iterate over each obstacle from our colliders.csv data, which we have already captured in variable ‘data’. We will first compare whether obstacle’s height is above ‘TARGET_ALTITUDE’, and if it is, then we will mark the area occupied by the obstacle + a safety distance we configured in variable ‘SAFETY_DISTANCE’ as 1 in our grid world. Finally, we return our grid world along with north_min and east_min values."
},
{
"code": null,
"e": 9791,
"s": 9086,
"text": "# Populate the grid with obstacles for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i, :] if alt + d_alt + safety_distance > drone_altitude: obstacle = [ int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)), int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)), int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)), int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)), ] grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1return grid, int(north_min), int(east_min)"
},
{
"code": null,
"e": 10402,
"s": 9791,
"text": "A small caveat which we need to understand is, the obstacles in colliders and our current local location are with respect to global home, which we had configured in with help of lat0 and lon0 variables. Whereas, the grid world which we create in create_grid function has origin at first obstacle point. Remember how we had calculated north min & max and east min & max and then north and east size to create a grid. Well, because of that there is an offset between colliders & our drone’s positional values and corresponding same position in our grid world. Following diagram will help us understand it better."
},
{
"code": null,
"e": 10686,
"s": 10402,
"text": "So every time we are trying to map a value from our drone’s positional sensor to grid world, we need to subtract north and east offset respectively. This offset value is nothing but north_min and east_min returned by create_grid function. We set our current position in grid_world as"
},
{
"code": null,
"e": 10856,
"s": 10686,
"text": "# TODO: convert start position to current position rather than map centergrid_start = (int(current_local_pos[0] - north_offset), int(current_local_pos[1] - east_offset))"
},
{
"code": null,
"e": 10893,
"s": 10856,
"text": "Assign a goal location of our choice"
},
{
"code": null,
"e": 11108,
"s": 10893,
"text": "# Take GPS co-ordinates as Grid goal -Megrid_goal = (-122.396582, 37.795714, 0)grid_goal = global_to_local(grid_goal, self.global_home)grid_goal = (int(grid_goal[0] - north_offset), int(grid_goal[1] - east_offset))"
},
{
"code": null,
"e": 11178,
"s": 11108,
"text": "Print our start and goal location and off we go on our way to be A*!!"
},
{
"code": null,
"e": 11289,
"s": 11178,
"text": "print('Local Start and Goal: ', grid_start, grid_goal)path, _ = a_star(grid, heuristic, grid_start, grid_goal)"
},
{
"code": null,
"e": 12897,
"s": 11289,
"text": "A* in the city We pass the grid we just now created in above section, a heuristic function and our start and goal location as arguments to a_star function. Hopefully the concepts we had gained in part 1 of this series will help us understand code for this function better. In fact let’s revisit the list of steps we had gone through while understanding Breadth First Algorithm. Knowing which step of our algorithm is performed in which set of lines will help us understand below code block better. As stated in Part 1, a A* algorithm adds ‘cost’ and ‘heuristic’ function on top of a BFS. So along with code for implementing below steps, it will include adding and accessing ‘cost’ and ‘heuristic’ functions too. The backbone of a breadth-first search consists of these basic steps: 1. Add a node/vertex from the grid to a queue of nodes to be “visited”. 2. Visit the topmost node in the queue, and mark it as such. 3. If that node has any neighbors, check to see if they have been “visited” or not. 4. Add any neighboring nodes that still need to be “visited” to the queue. 5. Remove current node we’ve visited from the queue. We first declare few variables. We will be using a Priority Queue to store nodes we need to visit. A typical pattern for entries in priority queue is a tuple in the form: (priority_number, data). The lowest valued entries are retrieved first and as we will be using ‘cost to reach corresponding node’ value as ‘priority_number’, whenever we will ‘get’ (or pop) an element from this priority queue, we will get an element which has least ‘cost’ value. We start at our ‘start’ node."
},
{
"code": null,
"e": 13859,
"s": 12897,
"text": "path = [] path_cost = 0 queue = PriorityQueue() queue.put((0, start)) visited = set(start)branch = {}found = False# Check till we have searched all nodes or have found our ‘goal’while not queue.empty(): item = queue.get() # Step2. Visit the topmost node in the queue current_cost = item[0] current_node = item[1] if current_node == goal: print('Found a path.') found = True break else:#Step3. If that node has any neighbors, check to see if they have been “visited” or not. for a in valid_actions(grid, current_node): next_node = (current_node[0] + a.delta[0], current_node[1] + a.delta[1]) new_cost = current_cost + a.cost + h(next_node, goal)#Step4. Add any neighboring nodes that still need to be “visited” to the queue. if next_node not in visited: visited.add(next_node) queue.put((new_cost, next_node)) branch[next_node] = (new_cost, current_node, a)"
},
{
"code": null,
"e": 14917,
"s": 13859,
"text": "As we saw in part 1, whenever we reach a node in BFS algorithm, it is guaranteed to be the shortest path to that node from our ‘start’ location. So to keep track of path we are tracing, in a_star function, we will be maintaining a dictionary, for which ‘key’ will be the node we will be visiting next, and its value will be a tuple of current node, action to be taken from current node in order to reach next node and total cost to reach next node. This tuple (current node + action to take to reach next node) will represent the shortest path to reach next node coming from ‘start’ location. Now once we find ‘goal’ location, we will trace back the route to ‘start’ location with the help of this ‘branch’ dictionary. We first copy the value of total cost to reach ‘goal’ location. Next, as we know that node present in ‘value’ of dictionary lies on the shortest path, we will build our ‘path’ list as -> [goal, node present in value of branch[goal], ...]. And we will keep tracing back our route till we find ‘start’ location, adding nodes to ‘path’ list."
},
{
"code": null,
"e": 15316,
"s": 14917,
"text": "if found: # retrace steps n = goal path_cost = branch[n][0] path.append(goal) while branch[n][1] != start: path.append(branch[n][1]) n = branch[n][1] path.append(branch[n][1]) else: print('**********************') print('Failed to find a path!') print('**********************') return path[::-1], path_cost"
},
{
"code": null,
"e": 16693,
"s": 15316,
"text": "Helper FunctionsPath Pruning: Once we have our path figured out, we will prune it by removing collinear points as explained in Collinearity Check section in Part 1. We take 3 consecutive points from our final path and check whether they lie on same line. We do this by calculating the area enclosed by selected 3 points. If it is very close to 0, we can assume that they lie on same line. We first convert a point in a 3 element (x-coordinate, y-coordinate, 1) to numpy array. We add this last element “1” so that we can arrange 3 vertices into a nice 3 x 3 matrix. After reshaping points in “points()” function, we create a matrix by concating them and then calculating the determinant of that matrix using a convenient np.linalg.det() function.Valid Actions: One function which was used by us in a_star is valid_actions (grid, current_node). This was used to carry out step# 3 of BFS algorithm, where we search for current node’s neighbours. We already have our action set (as explained in “Search space, Action set and Cost” section of Part1) and location of our current node. This function will return a subset of action set. It will check weather an action (i.e. moving up, down, left, right or diagonal) will lead us off grid or to an obstacle / No Fly zone node. And if that is the case, it will remove this action from list of valid actions feasible from current node."
},
{
"code": null,
"e": 17307,
"s": 16693,
"text": "Coming back to motion_planning.py, once we get pruned path, take each point from it, convert it into waypoint in local frame coordinate (by adding north and east offsets) and send it to autopilot using self.send_waypoints() function. And with that, we have finished coding our path planning A* algorithm. So without further ado, lets fire up Udacity’s drone simulator and run our motion_planning.py python file. You can find all the source code in my github repo here. If everything runs smoothly, you should be able to see your drone fly from a user configured starting and goal location like shown in below gif."
},
{
"code": null,
"e": 17428,
"s": 17307,
"text": "Hope you have enjoyed reading couple of articles in this series and now have a good understanding of fundamentals of A*."
}
]
|
Difference between DELETE and DROP in SQL - GeeksforGeeks | 19 Aug, 2019
Prerequisite – SQL CommandsDELETE is a Data Manipulation Language (DML) command and used when you want to remove some or all the tuples from a relation. If WHERE clause is used along with the DELETE command it removes only those tuples which satisfy the WHERE clause condition but if WHERE clause is missing from the DELETE statement then by default all the tuples present in relation are removed.
The syntax of DELETE command:
DELETE FROM relation_name
WHERE condition;
DROP is a Data Definition Language (DDL) command which removes the named elements of the schema like relations, domains or constraints and you can also remove an entire schema using DROP command.
The syntax of DROP command:
DROP SCHEMA schema_name RESTRICT;
DROP Table table_name CASCADE;
Comparison Chart:
NikhilKoyikkamannil
DBMS-SQL
DBMS
SQL
Technical Scripter
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
KDD Process in Data Mining
Structure of Database Management System
Difference between File System and DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server? | [
{
"code": null,
"e": 24304,
"s": 24276,
"text": "\n19 Aug, 2019"
},
{
"code": null,
"e": 24702,
"s": 24304,
"text": "Prerequisite – SQL CommandsDELETE is a Data Manipulation Language (DML) command and used when you want to remove some or all the tuples from a relation. If WHERE clause is used along with the DELETE command it removes only those tuples which satisfy the WHERE clause condition but if WHERE clause is missing from the DELETE statement then by default all the tuples present in relation are removed."
},
{
"code": null,
"e": 24732,
"s": 24702,
"text": "The syntax of DELETE command:"
},
{
"code": null,
"e": 24776,
"s": 24732,
"text": "DELETE FROM relation_name \nWHERE condition;"
},
{
"code": null,
"e": 24972,
"s": 24776,
"text": "DROP is a Data Definition Language (DDL) command which removes the named elements of the schema like relations, domains or constraints and you can also remove an entire schema using DROP command."
},
{
"code": null,
"e": 25000,
"s": 24972,
"text": "The syntax of DROP command:"
},
{
"code": null,
"e": 25065,
"s": 25000,
"text": "DROP SCHEMA schema_name RESTRICT;\nDROP Table table_name CASCADE;"
},
{
"code": null,
"e": 25083,
"s": 25065,
"text": "Comparison Chart:"
},
{
"code": null,
"e": 25103,
"s": 25083,
"text": "NikhilKoyikkamannil"
},
{
"code": null,
"e": 25112,
"s": 25103,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 25117,
"s": 25112,
"text": "DBMS"
},
{
"code": null,
"e": 25121,
"s": 25117,
"text": "SQL"
},
{
"code": null,
"e": 25140,
"s": 25121,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25145,
"s": 25140,
"text": "DBMS"
},
{
"code": null,
"e": 25149,
"s": 25145,
"text": "SQL"
},
{
"code": null,
"e": 25247,
"s": 25149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25256,
"s": 25247,
"text": "Comments"
},
{
"code": null,
"e": 25269,
"s": 25256,
"text": "Old Comments"
},
{
"code": null,
"e": 25310,
"s": 25269,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 25353,
"s": 25310,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 25380,
"s": 25353,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 25420,
"s": 25380,
"text": "Structure of Database Management System"
},
{
"code": null,
"e": 25460,
"s": 25420,
"text": "Difference between File System and DBMS"
},
{
"code": null,
"e": 25502,
"s": 25460,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 25546,
"s": 25502,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 25567,
"s": 25546,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 25633,
"s": 25567,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
]
|
Split an image array into tiles using numpy | Towards Data Science | There are plenty of situations where you would need to break down a large image in tiles (e.g. as part of a ML preprocessing pipeline) for batch processing. This article aims to explore lower-level ways of doing just that, in Python.
One of the most common ways of creating a stack of image tiles I have seen around is with nested for-loops, as in instantiating a new array with the desired dimensions and populating it within those loops. However, this method is particularly inefficient (especially) in Python and does not scale well, at all, with large datasets (nor smaller tiles, for that matter).
A nested for-loops approach would look something like the snippet below:
# Nested for-loops method.# Creating a stack of 2 x 2 tiles out of a 4 x 4# RGB image with channels on the last axis.import numpy as npimage = np.random.randn(4, 4, 3)tiles = np.zeros((4, 2, 2, 3))c = 0for i in range(0, image.shape[1], 2): for j in range(0, image.shape[2], 2): tiles[c] = image[i:i+2, j:j+2, :] c += 1
As the iterations grow (image size over tile size ratio), not to mention iterating over large number of images (3rd for-loop), this can occupy resources and quickly create a bottleneck in your pipeline.
What if we could just use a different view to the same chunk of memory and present it as tiles? Let’s talk a bit about arrays.
Numpy arrays, and arrays in general, are laid out in memory as contiguous chunks of bytes. That contiguous piece of memory can then be viewed in different shapes using strides.
On the memory level of arrays, the stride represents the number of bytes you need to jump forward in order to get to the next element contained in the array. This depends on the byte-length of the data types contained in the array.
e.g. A 1-dimensional array of 16-bit integers (2 bytes length) will have a stride of 2 bytes.
Something else to note is that arrays have to contain elements of the same data-type, so as to guarantee equal byte-length intervals. There are ways of representing different data types in a single array, of course, but that is outside the scope of this article.
So, what are the elements in an array? Just bytes laid out in order. Elements can vary in length, depending on the number of bytes needed to represent each of them.
An element, then, is an aggregation of bytes, which in turn are an aggregation of bits, 8 bits in particular. All living within the same physical space. So, is it possible to aggregate an array further into larger chunks? Yes it is. That is exactly what array dimensions do.
In order to organize your array elements into rows and create a second dimension, all you need to do is to define a second stride to point to the beginning of each row. On that dimension, then, the individual elements are the rows. This can also be thought of as splitting an array into multiple equal-sized sub-arrays.
In the array dimension sizes returned by numpy.shape(), the above depicted example would be presented as a 2-dimensional shape (3,3). The order of the dimensions returned always start (left-most) from the highest level going towards the lowest one (right-most). This means the size 3 of the first dimension in the tuple indicates the number of rows, while the size 3 of the second dimension indicates the number of individual elements per row. As we will see later on, there are numpy methods that can change the dimension hierarchy, but the above generally stands for array views formed using numpy.reshape() as well as newly instantiated arrays in numpy.
Note 1: The dimension order above is referring to the order accessed in the tuple returned by numpy.shape(), with the first dimension being at index position 0 (shape[0]) and the second dimension being at index position 1 (shape[1]).
Note 2: There are multiple layouts (row/column major), but this article only discusses row-major a.k.a. C order, as it is the one I am most familiar with. More information on layouts here.
For our purposes, we will give a generic definition of a dimension size as follows:
Using an 4-dimensional array of shape (m, n, i, j) as an example, the 1st (highest & left-most) dimension holds m number of elements organized in shapes (n, i, j). The 2nd dimension, holds n elements of shape (i, j), while the 3rd holds i elements of sizes ( j ). The 4th and last dimension is simply a single row of j elements. Then:
Dimension size: The number of elements described by the subsequent (lower) dimensions.
Now, a 2D image represented as a numpy array will have shape (m,n), where m would indicate the image height in pixels, while n would indicate the image width in pixels. As an example, let’s take a 6 by 4, 8-bit grayscale image array and aim to divide it in 2 by 2 tiles by creating a new memory view using strides. Remember, the elements have to be of equal length, hence, both array dimensions have to be divisible by 2.
Our image can then be thought of as being organized in 6 rows of elements of 4. The visualization of our example would look something like the following:
So, how do we get there?
Let’s take it one step at a time. Seeing that we need 6 tiles all together, organized in 3 rows and 2 columns, lets first try to split our current rows in 2 columns. Our current shape is (6, 4), thus, we need to halve the last dimension and add a higher dimension of 2, representing the columns that we want to form. Our target 3-dimensional shape for this step, then, is (2,6,2): 2 columns by 6 rows by 2 array elements in each row. Now that we know the shape we need. We can go ahead to figure out the strides.
Let’s observe the image below. The strides for our 2D image were (4,1). Stride 1 of the lowest dimension has to remain intact, as messing with it would make us lose the spatial relationship at the pixel level (e.g. increasing it would mean to skip pixels). Stride 4 of the rows dimension will also stay constant, since the number of desired rows remain 6. Generally speaking, if you changed any of those two strides, you would end up distorting the image. Then, all we need to do is figure out the stride for our highest dimension of size 2, which represents the new higher level columns we are defining. Having in mind that we split our original 4 per row elements in half so they can be included in separate columns, gives us a hint.
Check figure 2.5. All pixels in our array are numbered in the order they are laid out in memory (C order). Before, every 4 elements we had to change a row, a rule that still stands. We want to include an additional rule: In each row, change columns every 2 elements. So the stride in our highest dimension is 2 x element_byte_size. In our case of 8-bit integers, the stride is 2x1 byte = 2.
Let’s open up a terminal and test it in code:
In numpy, you can manipulate the strides of an array using numpy.lib.stride_tricks.as_strided(). We need to specify the array we want to manipulate, the shape we want it in, and the stride we want for each dimension:
We got our two columns with the elements we wanted! We can continue now to divide each column in 3 groups of 2 rows, giving us a total of 6 tiles.
Our current shape is (2, 6, 2), with 6 being our number of rows in the image. Similarly to the previous step where we needed our 3rd dimension elements (the 2 columns) to hold rows with just 2 array elements in each (1st dimension elements) row, we now need our 4th dimension elements in the top hierarchy to hold only 2 image rows each. So, we need to decrease the “image rows” dimension from 6 down to 2. Our target shape then will be (3, 2, 2, 2).
In summary, the lower level elements remain 2, our rows decrease to 2, the columns at the 3rd dimension remain 2, and we now add a 4th dimension to split those columns in 3 parts.
Our definition of this 4-dimensional array dictates that the highest dimension will now change elements every 2 image rows, instead of 1. So, in conclusion, the new stride has to be twice that of an image row. Then, the stride for our new dimension will be 2 x row_stride = 2x4 = 8 bytes.
Testing it in code:
And we’re done! All 6 tiles formed. Now we can merge the 2 highest dimensions using numpy.reshape() to make our array in the 3-dimensional shape of (number_of_tiles, tile_height, tile_width) if we wanted to, since this is the basic format for image batches. The reason we needed 4 dimensions instead of 3 in the first place, is because the location of every tile in memory cannot be represented by a single stride. Our image has 2 dimensions after all.
What we just implemented to split a 6 x 4 image of 8-bit integers in 2 x 2 tiles using strides, can be generalized to any C ordered 2D image like this:
As it turns out, we can have a similar formula for specifically formatted multi-channel images as well. Specific in a way that, they are contiguous C ordered arrays with channels at the lowest dimension (having same pixel RGB values next to one another), otherwise the strides will differ in each occasion. Some libraries load images directly like that, some don’t, but it’s not particularly hard to reshape them.
GDAL, for example, will load images with channels as the highest (left-most) dimension.
When our multi-channel array dimensions are formatted that way, the lowest dimension will be our per-channel values for each pixel, which we can navigate by doing only a single byte-length step. Since, instead of 1 single pixel value, we will have n pixel values for n channels, all we need to do is to multiply all other strides by the number of channels. Summarizing, everything remains the same, but we now have multiple values per pixel to jump, 1 for each channel:
Not a particularly clean approach, but we will see in the next section that there is a cleaner way. Dealing with strides is a very sensitive procedure and requires extreme caution. Every time you would have to verify contiguity and take necessary steps.
Luckily enough, numpy provides a few higher level methods to save us most of the trouble.
Numpy.reshape() is the standard, most common way of manipulating an array shape in numpy. However, if we simply stated in our previous 6 x 4 image example that we wanted an array of shape (3, 2, 2, 2) it would not have worked.
That happens because numpy.reshape(), by default, tries to maintain contiguity of subsequent values. It means that sequential indexes of your array, used through your program, will continue to be in adjacent blocks of memory. Unfortunately, in order to get our result we need to break contiguity. Although, we can make it contiguous again after breaking it in tiles, for performance reasons.
<< Strides differ from our previous solution.
How does it work? It basically takes a dimension (at any level), breaks it down in equal adjacent pieces and stacks them together at a higher level. In our case, it does something like the following:
Instead, what we want is this:
So, how do we fix it?
As a simple comparison of the two arrays’ strides hints, all we need to do is swap strides between axis 1 and axis 2 (1st and 2nd dimensions). Specifically, the strides we need are (8, 2, 4, 1), but numpy.reshape() returns an array with strides (8, 4, 2, 1). Numpy arrays expose a method just for that, called swapaxes:
The numpy.reshape() implementation, then, can be generalized for any 2D or 3D image with channels in the last dimension as follows:
Let’s compare executions!
We’ll use an RGB JPEG of this cool looking fellow right here:
After we explore our image’s dimensions, we can see they are divisible by 25 and 12 accordingly, so let’s just use these for our tile-size.
We’ll also use this decorator to time each execution:
Our for-loop implementation looks like this:
The strides implementation is:
And the numpy.reshape() implementation is:
We will load our image as a numpy array, set tile dimensions from command line, run each function and check for equality of arrays.
The moment of truth:
The numpy.reshape() approach appears to be the cleanest as well as the most efficient. Additionally, it is apparent that the for-loop implementation can’t really compare to the memory view methods. It’s also noteworthy that memory view performance is barely affected by the “amount” of tiles that must be generated, while the for-loop’s time of execution would blow up with an increasing workload.
Final note: There’s an additional step to bringing our tiles in a batch processing form as expected by most frameworks. To merge our tiles in a single index all we have to do is tiled_arr.reshape(-1, *tile_dimensions) and use numpy.moveaxis() to relocate the channels dimension where appropriate. Usually as (n_tiles,n_channels,t_height,t_width).
Thank you for reading!
I hope this article was insightful and you can implement what was demonstrated here in your own computer vision workflows!
Illustrations and formulas were created in LibreOffice.
Code: You can find the testing script here.
Feel free to contact me with any recommendations or corrections at [email protected]
You can connect with me on LinkedIn.
Sources:
[1]: Memory layout of multi-dimensional arrays
[2]: An Illustrated Guide to Shapes and Strides (Part 1)
[3]: Numpy documentation: numpy.lib.stride_tricks.as_strided()
[4]: Numpy documentation: numpy.reshape() | [
{
"code": null,
"e": 406,
"s": 172,
"text": "There are plenty of situations where you would need to break down a large image in tiles (e.g. as part of a ML preprocessing pipeline) for batch processing. This article aims to explore lower-level ways of doing just that, in Python."
},
{
"code": null,
"e": 775,
"s": 406,
"text": "One of the most common ways of creating a stack of image tiles I have seen around is with nested for-loops, as in instantiating a new array with the desired dimensions and populating it within those loops. However, this method is particularly inefficient (especially) in Python and does not scale well, at all, with large datasets (nor smaller tiles, for that matter)."
},
{
"code": null,
"e": 848,
"s": 775,
"text": "A nested for-loops approach would look something like the snippet below:"
},
{
"code": null,
"e": 1186,
"s": 848,
"text": "# Nested for-loops method.# Creating a stack of 2 x 2 tiles out of a 4 x 4# RGB image with channels on the last axis.import numpy as npimage = np.random.randn(4, 4, 3)tiles = np.zeros((4, 2, 2, 3))c = 0for i in range(0, image.shape[1], 2): for j in range(0, image.shape[2], 2): tiles[c] = image[i:i+2, j:j+2, :] c += 1"
},
{
"code": null,
"e": 1389,
"s": 1186,
"text": "As the iterations grow (image size over tile size ratio), not to mention iterating over large number of images (3rd for-loop), this can occupy resources and quickly create a bottleneck in your pipeline."
},
{
"code": null,
"e": 1516,
"s": 1389,
"text": "What if we could just use a different view to the same chunk of memory and present it as tiles? Let’s talk a bit about arrays."
},
{
"code": null,
"e": 1693,
"s": 1516,
"text": "Numpy arrays, and arrays in general, are laid out in memory as contiguous chunks of bytes. That contiguous piece of memory can then be viewed in different shapes using strides."
},
{
"code": null,
"e": 1925,
"s": 1693,
"text": "On the memory level of arrays, the stride represents the number of bytes you need to jump forward in order to get to the next element contained in the array. This depends on the byte-length of the data types contained in the array."
},
{
"code": null,
"e": 2019,
"s": 1925,
"text": "e.g. A 1-dimensional array of 16-bit integers (2 bytes length) will have a stride of 2 bytes."
},
{
"code": null,
"e": 2282,
"s": 2019,
"text": "Something else to note is that arrays have to contain elements of the same data-type, so as to guarantee equal byte-length intervals. There are ways of representing different data types in a single array, of course, but that is outside the scope of this article."
},
{
"code": null,
"e": 2447,
"s": 2282,
"text": "So, what are the elements in an array? Just bytes laid out in order. Elements can vary in length, depending on the number of bytes needed to represent each of them."
},
{
"code": null,
"e": 2722,
"s": 2447,
"text": "An element, then, is an aggregation of bytes, which in turn are an aggregation of bits, 8 bits in particular. All living within the same physical space. So, is it possible to aggregate an array further into larger chunks? Yes it is. That is exactly what array dimensions do."
},
{
"code": null,
"e": 3042,
"s": 2722,
"text": "In order to organize your array elements into rows and create a second dimension, all you need to do is to define a second stride to point to the beginning of each row. On that dimension, then, the individual elements are the rows. This can also be thought of as splitting an array into multiple equal-sized sub-arrays."
},
{
"code": null,
"e": 3699,
"s": 3042,
"text": "In the array dimension sizes returned by numpy.shape(), the above depicted example would be presented as a 2-dimensional shape (3,3). The order of the dimensions returned always start (left-most) from the highest level going towards the lowest one (right-most). This means the size 3 of the first dimension in the tuple indicates the number of rows, while the size 3 of the second dimension indicates the number of individual elements per row. As we will see later on, there are numpy methods that can change the dimension hierarchy, but the above generally stands for array views formed using numpy.reshape() as well as newly instantiated arrays in numpy."
},
{
"code": null,
"e": 3933,
"s": 3699,
"text": "Note 1: The dimension order above is referring to the order accessed in the tuple returned by numpy.shape(), with the first dimension being at index position 0 (shape[0]) and the second dimension being at index position 1 (shape[1])."
},
{
"code": null,
"e": 4122,
"s": 3933,
"text": "Note 2: There are multiple layouts (row/column major), but this article only discusses row-major a.k.a. C order, as it is the one I am most familiar with. More information on layouts here."
},
{
"code": null,
"e": 4206,
"s": 4122,
"text": "For our purposes, we will give a generic definition of a dimension size as follows:"
},
{
"code": null,
"e": 4541,
"s": 4206,
"text": "Using an 4-dimensional array of shape (m, n, i, j) as an example, the 1st (highest & left-most) dimension holds m number of elements organized in shapes (n, i, j). The 2nd dimension, holds n elements of shape (i, j), while the 3rd holds i elements of sizes ( j ). The 4th and last dimension is simply a single row of j elements. Then:"
},
{
"code": null,
"e": 4628,
"s": 4541,
"text": "Dimension size: The number of elements described by the subsequent (lower) dimensions."
},
{
"code": null,
"e": 5050,
"s": 4628,
"text": "Now, a 2D image represented as a numpy array will have shape (m,n), where m would indicate the image height in pixels, while n would indicate the image width in pixels. As an example, let’s take a 6 by 4, 8-bit grayscale image array and aim to divide it in 2 by 2 tiles by creating a new memory view using strides. Remember, the elements have to be of equal length, hence, both array dimensions have to be divisible by 2."
},
{
"code": null,
"e": 5204,
"s": 5050,
"text": "Our image can then be thought of as being organized in 6 rows of elements of 4. The visualization of our example would look something like the following:"
},
{
"code": null,
"e": 5229,
"s": 5204,
"text": "So, how do we get there?"
},
{
"code": null,
"e": 5742,
"s": 5229,
"text": "Let’s take it one step at a time. Seeing that we need 6 tiles all together, organized in 3 rows and 2 columns, lets first try to split our current rows in 2 columns. Our current shape is (6, 4), thus, we need to halve the last dimension and add a higher dimension of 2, representing the columns that we want to form. Our target 3-dimensional shape for this step, then, is (2,6,2): 2 columns by 6 rows by 2 array elements in each row. Now that we know the shape we need. We can go ahead to figure out the strides."
},
{
"code": null,
"e": 6478,
"s": 5742,
"text": "Let’s observe the image below. The strides for our 2D image were (4,1). Stride 1 of the lowest dimension has to remain intact, as messing with it would make us lose the spatial relationship at the pixel level (e.g. increasing it would mean to skip pixels). Stride 4 of the rows dimension will also stay constant, since the number of desired rows remain 6. Generally speaking, if you changed any of those two strides, you would end up distorting the image. Then, all we need to do is figure out the stride for our highest dimension of size 2, which represents the new higher level columns we are defining. Having in mind that we split our original 4 per row elements in half so they can be included in separate columns, gives us a hint."
},
{
"code": null,
"e": 6869,
"s": 6478,
"text": "Check figure 2.5. All pixels in our array are numbered in the order they are laid out in memory (C order). Before, every 4 elements we had to change a row, a rule that still stands. We want to include an additional rule: In each row, change columns every 2 elements. So the stride in our highest dimension is 2 x element_byte_size. In our case of 8-bit integers, the stride is 2x1 byte = 2."
},
{
"code": null,
"e": 6915,
"s": 6869,
"text": "Let’s open up a terminal and test it in code:"
},
{
"code": null,
"e": 7132,
"s": 6915,
"text": "In numpy, you can manipulate the strides of an array using numpy.lib.stride_tricks.as_strided(). We need to specify the array we want to manipulate, the shape we want it in, and the stride we want for each dimension:"
},
{
"code": null,
"e": 7279,
"s": 7132,
"text": "We got our two columns with the elements we wanted! We can continue now to divide each column in 3 groups of 2 rows, giving us a total of 6 tiles."
},
{
"code": null,
"e": 7730,
"s": 7279,
"text": "Our current shape is (2, 6, 2), with 6 being our number of rows in the image. Similarly to the previous step where we needed our 3rd dimension elements (the 2 columns) to hold rows with just 2 array elements in each (1st dimension elements) row, we now need our 4th dimension elements in the top hierarchy to hold only 2 image rows each. So, we need to decrease the “image rows” dimension from 6 down to 2. Our target shape then will be (3, 2, 2, 2)."
},
{
"code": null,
"e": 7910,
"s": 7730,
"text": "In summary, the lower level elements remain 2, our rows decrease to 2, the columns at the 3rd dimension remain 2, and we now add a 4th dimension to split those columns in 3 parts."
},
{
"code": null,
"e": 8199,
"s": 7910,
"text": "Our definition of this 4-dimensional array dictates that the highest dimension will now change elements every 2 image rows, instead of 1. So, in conclusion, the new stride has to be twice that of an image row. Then, the stride for our new dimension will be 2 x row_stride = 2x4 = 8 bytes."
},
{
"code": null,
"e": 8219,
"s": 8199,
"text": "Testing it in code:"
},
{
"code": null,
"e": 8672,
"s": 8219,
"text": "And we’re done! All 6 tiles formed. Now we can merge the 2 highest dimensions using numpy.reshape() to make our array in the 3-dimensional shape of (number_of_tiles, tile_height, tile_width) if we wanted to, since this is the basic format for image batches. The reason we needed 4 dimensions instead of 3 in the first place, is because the location of every tile in memory cannot be represented by a single stride. Our image has 2 dimensions after all."
},
{
"code": null,
"e": 8824,
"s": 8672,
"text": "What we just implemented to split a 6 x 4 image of 8-bit integers in 2 x 2 tiles using strides, can be generalized to any C ordered 2D image like this:"
},
{
"code": null,
"e": 9238,
"s": 8824,
"text": "As it turns out, we can have a similar formula for specifically formatted multi-channel images as well. Specific in a way that, they are contiguous C ordered arrays with channels at the lowest dimension (having same pixel RGB values next to one another), otherwise the strides will differ in each occasion. Some libraries load images directly like that, some don’t, but it’s not particularly hard to reshape them."
},
{
"code": null,
"e": 9326,
"s": 9238,
"text": "GDAL, for example, will load images with channels as the highest (left-most) dimension."
},
{
"code": null,
"e": 9796,
"s": 9326,
"text": "When our multi-channel array dimensions are formatted that way, the lowest dimension will be our per-channel values for each pixel, which we can navigate by doing only a single byte-length step. Since, instead of 1 single pixel value, we will have n pixel values for n channels, all we need to do is to multiply all other strides by the number of channels. Summarizing, everything remains the same, but we now have multiple values per pixel to jump, 1 for each channel:"
},
{
"code": null,
"e": 10050,
"s": 9796,
"text": "Not a particularly clean approach, but we will see in the next section that there is a cleaner way. Dealing with strides is a very sensitive procedure and requires extreme caution. Every time you would have to verify contiguity and take necessary steps."
},
{
"code": null,
"e": 10140,
"s": 10050,
"text": "Luckily enough, numpy provides a few higher level methods to save us most of the trouble."
},
{
"code": null,
"e": 10367,
"s": 10140,
"text": "Numpy.reshape() is the standard, most common way of manipulating an array shape in numpy. However, if we simply stated in our previous 6 x 4 image example that we wanted an array of shape (3, 2, 2, 2) it would not have worked."
},
{
"code": null,
"e": 10759,
"s": 10367,
"text": "That happens because numpy.reshape(), by default, tries to maintain contiguity of subsequent values. It means that sequential indexes of your array, used through your program, will continue to be in adjacent blocks of memory. Unfortunately, in order to get our result we need to break contiguity. Although, we can make it contiguous again after breaking it in tiles, for performance reasons."
},
{
"code": null,
"e": 10805,
"s": 10759,
"text": "<< Strides differ from our previous solution."
},
{
"code": null,
"e": 11005,
"s": 10805,
"text": "How does it work? It basically takes a dimension (at any level), breaks it down in equal adjacent pieces and stacks them together at a higher level. In our case, it does something like the following:"
},
{
"code": null,
"e": 11036,
"s": 11005,
"text": "Instead, what we want is this:"
},
{
"code": null,
"e": 11058,
"s": 11036,
"text": "So, how do we fix it?"
},
{
"code": null,
"e": 11378,
"s": 11058,
"text": "As a simple comparison of the two arrays’ strides hints, all we need to do is swap strides between axis 1 and axis 2 (1st and 2nd dimensions). Specifically, the strides we need are (8, 2, 4, 1), but numpy.reshape() returns an array with strides (8, 4, 2, 1). Numpy arrays expose a method just for that, called swapaxes:"
},
{
"code": null,
"e": 11510,
"s": 11378,
"text": "The numpy.reshape() implementation, then, can be generalized for any 2D or 3D image with channels in the last dimension as follows:"
},
{
"code": null,
"e": 11536,
"s": 11510,
"text": "Let’s compare executions!"
},
{
"code": null,
"e": 11598,
"s": 11536,
"text": "We’ll use an RGB JPEG of this cool looking fellow right here:"
},
{
"code": null,
"e": 11738,
"s": 11598,
"text": "After we explore our image’s dimensions, we can see they are divisible by 25 and 12 accordingly, so let’s just use these for our tile-size."
},
{
"code": null,
"e": 11792,
"s": 11738,
"text": "We’ll also use this decorator to time each execution:"
},
{
"code": null,
"e": 11837,
"s": 11792,
"text": "Our for-loop implementation looks like this:"
},
{
"code": null,
"e": 11868,
"s": 11837,
"text": "The strides implementation is:"
},
{
"code": null,
"e": 11911,
"s": 11868,
"text": "And the numpy.reshape() implementation is:"
},
{
"code": null,
"e": 12043,
"s": 11911,
"text": "We will load our image as a numpy array, set tile dimensions from command line, run each function and check for equality of arrays."
},
{
"code": null,
"e": 12064,
"s": 12043,
"text": "The moment of truth:"
},
{
"code": null,
"e": 12462,
"s": 12064,
"text": "The numpy.reshape() approach appears to be the cleanest as well as the most efficient. Additionally, it is apparent that the for-loop implementation can’t really compare to the memory view methods. It’s also noteworthy that memory view performance is barely affected by the “amount” of tiles that must be generated, while the for-loop’s time of execution would blow up with an increasing workload."
},
{
"code": null,
"e": 12809,
"s": 12462,
"text": "Final note: There’s an additional step to bringing our tiles in a batch processing form as expected by most frameworks. To merge our tiles in a single index all we have to do is tiled_arr.reshape(-1, *tile_dimensions) and use numpy.moveaxis() to relocate the channels dimension where appropriate. Usually as (n_tiles,n_channels,t_height,t_width)."
},
{
"code": null,
"e": 12832,
"s": 12809,
"text": "Thank you for reading!"
},
{
"code": null,
"e": 12955,
"s": 12832,
"text": "I hope this article was insightful and you can implement what was demonstrated here in your own computer vision workflows!"
},
{
"code": null,
"e": 13011,
"s": 12955,
"text": "Illustrations and formulas were created in LibreOffice."
},
{
"code": null,
"e": 13055,
"s": 13011,
"text": "Code: You can find the testing script here."
},
{
"code": null,
"e": 13153,
"s": 13055,
"text": "Feel free to contact me with any recommendations or corrections at [email protected]"
},
{
"code": null,
"e": 13190,
"s": 13153,
"text": "You can connect with me on LinkedIn."
},
{
"code": null,
"e": 13199,
"s": 13190,
"text": "Sources:"
},
{
"code": null,
"e": 13246,
"s": 13199,
"text": "[1]: Memory layout of multi-dimensional arrays"
},
{
"code": null,
"e": 13303,
"s": 13246,
"text": "[2]: An Illustrated Guide to Shapes and Strides (Part 1)"
},
{
"code": null,
"e": 13366,
"s": 13303,
"text": "[3]: Numpy documentation: numpy.lib.stride_tricks.as_strided()"
}
]
|
Selecting the Best Predictors for Linear Regression in R | by Atinakarim | Towards Data Science | To get the best fit for a multiple regression model, it is important to include the most significant subset of predictors from the dataset. However, it can be quite challenging to understand which predictors, among a large set of predictors, have a significant influence on our target variable. This can be particularly cumbersome given that the p-value for each variable is adjusted for the other terms in the model.
In this post, I will demonstrate how to use R’s leaps package to get the best possible regression model.
Leaps is a regression subset selection tool that performs an exhaustive search to determine the most influential predictors for our model(Lumley, 2020). The best predictors are selected by evaluating the combination that leads to the best adjusted r2 and Mallow’s CP.
We will use the regsubsets() function on Cortez and Morais’ 2007 forest fire dataset, to predict the size of the burned area(ha) in Montesinho Natural Park in Portugal.
The forest fire dataset contains information on 517 forest fires in Montesinho Natural Park in Portugal. There are 12 attributes in the dataset.
During EDA, I noticed multicollinearity among several dependent variables, hence this dataset is a good candidate for feature selection.
The original dataset was also transformed to fulfill the assumptions of linear regression prior to modeling. Additional dummy variables were also added because we were interested in looking at temporal interactions.
Now, that we have our dataset ready let’s start modeling.
1.Perform Linear Regression with All Predictors
Before selecting the best subset of predictors for our regression, let’s run a simple linear regression on our dataset with all predictors to set the base adjusted r2 for comparison.
lm1 <- lm(fires.clean1,formula=area ~.)summary(lm1)
We can see that with all of our variables included in the model, the base adjusted r2 is 0.02 and the Residual Standard Error is 0.6454. However, this relationship is not significant at the P<.05 level.
2. Install and load the leaps library
After installing the leaps package load, the library using the following command:
library(leaps)
3. Regsubsets()
Run the regsubsets() function on all variables.
Best_Subset <- regsubsets(area~., data =fires.clean1, nbest = 1, # 1 best model for each number of predictors nvmax = NULL, # NULL for no limit on number of variables force.in = NULL, force.out = NULL, method = "exhaustive")summary_best_subset <- summary(regsubsets.out)as.data.frame(summary_best_subset$outmat)
4. Number of Predictors
Now, that we have run leaps through our dataset, let’s see what the package recommends in terms of the number of predictors to use for our dataset.
which.max(summary_best_subset$adjr2)
Seems like we have to use 13 predictors to get the best model.
5. What are the best predictors?
Summary table below provides details on which predictors to use for the model. The best predictors are indicated by ‘TRUE’.
summary_best_subset$which[13,]
It looks like including only the following predictors will give us the best model fit for our linear regression model : day.thu, month.aug, month.dec, month.jan, month.jul, month.jun, month.mar, month.oct, month.sep, X, DMC, temp and RH
6. Run the regression model with the best predictors
best.model <- lm(area ~ day.thu + month.aug + month.dec + month.jan + month.jul+ month.jun+month.mar+month.oct+month.sep+X+Y+DMC+temp+RH, data = fires.clean1)summary(best.model)```
We can see that compared to our model in Step 1, our adjusted r2 has improved significantly (from 0.02 to 0.05) and is significant.
The next steps would be to further evaluate the model by looking at its diagnostic plots. If the data set was split into a train and test set, we could also use the predict() function to run this model on our test dataset and subsequently, evaluate those results to fully understand our model performance.
One thing to note would be that — our adjusted r2 is still very low. The best model only explains 5% variability in the data. This may imply that we need to transform our dataset further — or try different methods of transformation. It can also imply that maybe our dataset isn’t the best candidate for linear regression.
The purpose of this post was to demonstrate how to perform variable selection for linear regression models using the leaps package. Comments and suggestions on the method or alternative (superior) methods for variable selection are welcome. Please check out the resources below to learn more about variable selection using leaps.
(2018, April 27). Retrieved May 23, 2021, from https://www.youtube.com/watch?v=3HKMjEK02Cs
Lumley, Thomas (2020, Jan 16). Package Leaps. https://cran.r-project.org/web/packages/leaps/leaps.pdf
Kassambara (2018, November 3). Best Subsets Regression Essentials in R. Statistical tools for high-throughput data analysis. http://www.sthda.com/english/articles/37-model-selection-essentials-in-r/155-best-subsets-regression-essentials-in-r/
All subset regression with leaps, bestglm, glmulti, and meifly. Retrieved May 23, 2021 from https://rstudio-pubs-static.s3.amazonaws.com/2897_9220b21cfc0c43a396ff9abf122bb351.html
Minitab (2017, June 29). Cp and Cpk: Two Process Perspectives, One Process Reality. Minitab. https://blog.minitab.com/en/statistics-and-quality-data-analysis/cp-and-cpk-two-process-perspectives-one-process-reality#:~:text=Cp%20is%20a%20ratio%20of,indicate%20a%20more%20capable%20process.&text=When%20the%20specification%20spread%20is%20less,process%20spread,%20Cp%20is%20low.
Glen, Stephanie (2021). Adjusted R2 / Adjusted R-Squared: What is it used for. StatisticsHowTo.com: Elementary Statistics for the rest of us! https://www.statisticshowto.com/probability-and-statistics/statistics-definitions/adjusted-r2/
P. Cortez and A. Morais (2007, December 1). A Data Mining Approach to Predict Forest Fires using Meteorological Data. In Proceedings of the 13th EPIA 2007 — Portuguese Conference on Artificial Intelligence, December, 2007. (http://www.dsi.uminho.pt/~pcortez/fires.pdf)
Zach (2020, January 08). The Four Assumptions of Linear Regression. Statology. https://www.statology.org/linear-regression-assumptions/https://www.statology.org/linear-regression-assumptions/ | [
{
"code": null,
"e": 590,
"s": 172,
"text": "To get the best fit for a multiple regression model, it is important to include the most significant subset of predictors from the dataset. However, it can be quite challenging to understand which predictors, among a large set of predictors, have a significant influence on our target variable. This can be particularly cumbersome given that the p-value for each variable is adjusted for the other terms in the model."
},
{
"code": null,
"e": 695,
"s": 590,
"text": "In this post, I will demonstrate how to use R’s leaps package to get the best possible regression model."
},
{
"code": null,
"e": 963,
"s": 695,
"text": "Leaps is a regression subset selection tool that performs an exhaustive search to determine the most influential predictors for our model(Lumley, 2020). The best predictors are selected by evaluating the combination that leads to the best adjusted r2 and Mallow’s CP."
},
{
"code": null,
"e": 1132,
"s": 963,
"text": "We will use the regsubsets() function on Cortez and Morais’ 2007 forest fire dataset, to predict the size of the burned area(ha) in Montesinho Natural Park in Portugal."
},
{
"code": null,
"e": 1277,
"s": 1132,
"text": "The forest fire dataset contains information on 517 forest fires in Montesinho Natural Park in Portugal. There are 12 attributes in the dataset."
},
{
"code": null,
"e": 1414,
"s": 1277,
"text": "During EDA, I noticed multicollinearity among several dependent variables, hence this dataset is a good candidate for feature selection."
},
{
"code": null,
"e": 1630,
"s": 1414,
"text": "The original dataset was also transformed to fulfill the assumptions of linear regression prior to modeling. Additional dummy variables were also added because we were interested in looking at temporal interactions."
},
{
"code": null,
"e": 1688,
"s": 1630,
"text": "Now, that we have our dataset ready let’s start modeling."
},
{
"code": null,
"e": 1736,
"s": 1688,
"text": "1.Perform Linear Regression with All Predictors"
},
{
"code": null,
"e": 1919,
"s": 1736,
"text": "Before selecting the best subset of predictors for our regression, let’s run a simple linear regression on our dataset with all predictors to set the base adjusted r2 for comparison."
},
{
"code": null,
"e": 1971,
"s": 1919,
"text": "lm1 <- lm(fires.clean1,formula=area ~.)summary(lm1)"
},
{
"code": null,
"e": 2174,
"s": 1971,
"text": "We can see that with all of our variables included in the model, the base adjusted r2 is 0.02 and the Residual Standard Error is 0.6454. However, this relationship is not significant at the P<.05 level."
},
{
"code": null,
"e": 2212,
"s": 2174,
"text": "2. Install and load the leaps library"
},
{
"code": null,
"e": 2294,
"s": 2212,
"text": "After installing the leaps package load, the library using the following command:"
},
{
"code": null,
"e": 2309,
"s": 2294,
"text": "library(leaps)"
},
{
"code": null,
"e": 2325,
"s": 2309,
"text": "3. Regsubsets()"
},
{
"code": null,
"e": 2373,
"s": 2325,
"text": "Run the regsubsets() function on all variables."
},
{
"code": null,
"e": 2766,
"s": 2373,
"text": "Best_Subset <- regsubsets(area~., data =fires.clean1, nbest = 1, # 1 best model for each number of predictors nvmax = NULL, # NULL for no limit on number of variables force.in = NULL, force.out = NULL, method = \"exhaustive\")summary_best_subset <- summary(regsubsets.out)as.data.frame(summary_best_subset$outmat)"
},
{
"code": null,
"e": 2790,
"s": 2766,
"text": "4. Number of Predictors"
},
{
"code": null,
"e": 2938,
"s": 2790,
"text": "Now, that we have run leaps through our dataset, let’s see what the package recommends in terms of the number of predictors to use for our dataset."
},
{
"code": null,
"e": 2975,
"s": 2938,
"text": "which.max(summary_best_subset$adjr2)"
},
{
"code": null,
"e": 3038,
"s": 2975,
"text": "Seems like we have to use 13 predictors to get the best model."
},
{
"code": null,
"e": 3071,
"s": 3038,
"text": "5. What are the best predictors?"
},
{
"code": null,
"e": 3195,
"s": 3071,
"text": "Summary table below provides details on which predictors to use for the model. The best predictors are indicated by ‘TRUE’."
},
{
"code": null,
"e": 3226,
"s": 3195,
"text": "summary_best_subset$which[13,]"
},
{
"code": null,
"e": 3463,
"s": 3226,
"text": "It looks like including only the following predictors will give us the best model fit for our linear regression model : day.thu, month.aug, month.dec, month.jan, month.jul, month.jun, month.mar, month.oct, month.sep, X, DMC, temp and RH"
},
{
"code": null,
"e": 3516,
"s": 3463,
"text": "6. Run the regression model with the best predictors"
},
{
"code": null,
"e": 3697,
"s": 3516,
"text": "best.model <- lm(area ~ day.thu + month.aug + month.dec + month.jan + month.jul+ month.jun+month.mar+month.oct+month.sep+X+Y+DMC+temp+RH, data = fires.clean1)summary(best.model)```"
},
{
"code": null,
"e": 3829,
"s": 3697,
"text": "We can see that compared to our model in Step 1, our adjusted r2 has improved significantly (from 0.02 to 0.05) and is significant."
},
{
"code": null,
"e": 4135,
"s": 3829,
"text": "The next steps would be to further evaluate the model by looking at its diagnostic plots. If the data set was split into a train and test set, we could also use the predict() function to run this model on our test dataset and subsequently, evaluate those results to fully understand our model performance."
},
{
"code": null,
"e": 4457,
"s": 4135,
"text": "One thing to note would be that — our adjusted r2 is still very low. The best model only explains 5% variability in the data. This may imply that we need to transform our dataset further — or try different methods of transformation. It can also imply that maybe our dataset isn’t the best candidate for linear regression."
},
{
"code": null,
"e": 4787,
"s": 4457,
"text": "The purpose of this post was to demonstrate how to perform variable selection for linear regression models using the leaps package. Comments and suggestions on the method or alternative (superior) methods for variable selection are welcome. Please check out the resources below to learn more about variable selection using leaps."
},
{
"code": null,
"e": 4878,
"s": 4787,
"text": "(2018, April 27). Retrieved May 23, 2021, from https://www.youtube.com/watch?v=3HKMjEK02Cs"
},
{
"code": null,
"e": 4980,
"s": 4878,
"text": "Lumley, Thomas (2020, Jan 16). Package Leaps. https://cran.r-project.org/web/packages/leaps/leaps.pdf"
},
{
"code": null,
"e": 5223,
"s": 4980,
"text": "Kassambara (2018, November 3). Best Subsets Regression Essentials in R. Statistical tools for high-throughput data analysis. http://www.sthda.com/english/articles/37-model-selection-essentials-in-r/155-best-subsets-regression-essentials-in-r/"
},
{
"code": null,
"e": 5403,
"s": 5223,
"text": "All subset regression with leaps, bestglm, glmulti, and meifly. Retrieved May 23, 2021 from https://rstudio-pubs-static.s3.amazonaws.com/2897_9220b21cfc0c43a396ff9abf122bb351.html"
},
{
"code": null,
"e": 5779,
"s": 5403,
"text": "Minitab (2017, June 29). Cp and Cpk: Two Process Perspectives, One Process Reality. Minitab. https://blog.minitab.com/en/statistics-and-quality-data-analysis/cp-and-cpk-two-process-perspectives-one-process-reality#:~:text=Cp%20is%20a%20ratio%20of,indicate%20a%20more%20capable%20process.&text=When%20the%20specification%20spread%20is%20less,process%20spread,%20Cp%20is%20low."
},
{
"code": null,
"e": 6016,
"s": 5779,
"text": "Glen, Stephanie (2021). Adjusted R2 / Adjusted R-Squared: What is it used for. StatisticsHowTo.com: Elementary Statistics for the rest of us! https://www.statisticshowto.com/probability-and-statistics/statistics-definitions/adjusted-r2/"
},
{
"code": null,
"e": 6285,
"s": 6016,
"text": "P. Cortez and A. Morais (2007, December 1). A Data Mining Approach to Predict Forest Fires using Meteorological Data. In Proceedings of the 13th EPIA 2007 — Portuguese Conference on Artificial Intelligence, December, 2007. (http://www.dsi.uminho.pt/~pcortez/fires.pdf)"
}
]
|
Vaadin - Themes | This chapter discusses in detail about another feature of Vaadin, known as Theme. In general, theme means a framework which is customizable at runtime. The content will be dynamic depending on the response received at the server end.
Vaadin provides a cool interface to use a theme with in a second with the help of its own Java based SAAS compiler. Theme feature is given to Vaadin in order to provide customizable style and look to the application. Theme is a pre-made template and developers need to customize it in order to build their own application which saves their time.
You can find all the themes in Vaadin under the theme folder and each of the sub folders are self-descript able. Hence, it is also very easy to change the code and customize the same. Any theme can have two types of CSS files in it − .saas type and .css type. Although Vaadin does not have any restriction on folder name, it is always recommended to use the folder name as you can notice from the image given above.
There are two kind of themes available − Inbuilt and Custom. This section discusses them in detail.
Vaadin built in theme is provided by annotating it with a theme name as shown below.
@Theme("mytheme")
public class MyUI extends UI {
All the grey color back ground while running a Vaadin application comes from the inbuilt css files. We can make change those files in order to make them as a custom theme which is another kind of theme. There is nothing we can learn about the Vaadin built in themes. All the above mentioned components are part of Vaadin Theme.
Custom themes are placed in the VAADIN/themes folder of the web application, in an Eclipse project under the WebContent folder or src/main/webapp in Maven projects. These locations are fixed and recommended not to change for any type of requirement. To define a SAAS theme with the name mytheme , you must place the file in the mytheme folder under theme folder then rebuild your project. Vaadin will automatically create its own .css file on the fly whenever requested by the browser.
You can change the style content in the css file as per your requirement. However, remember to build the project once again and it will start reflecting in progress.
Vaadin supports responsive theme too. Responsive web page can automatically set the font size according to the screen size. In the Vaadin application, we need to add a single line of code in order to make the entire application responsive.
Let us consider the following example to learn further about Vaadin. Make changes in the MyUI.java class as shown below.
package com.TutorialsMy.myApp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.TreeData;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.Responsive;
import com.vaadin.server.UserError;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.DateField;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Grid;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Tree;
import com.vaadin.ui.UI;
import com.vaadin.ui.Upload;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.VerticalSplitPanel;
import com.vaadin.ui.Window;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout hLayout = new VerticalLayout();
Label l1 = new Label("Enter today's Date\n",ContentMode.PREFORMATTED);
DateField date = new DateField();
date.setValue(LocalDate.now());
date.setLocale(new Locale("en","IND"));
hLayout.addComponents(l1,date);
hLayout.setComponentAlignment(l1,Alignment.BOTTOM_CENTER);
hLayout.setComponentAlignment(date,Alignment.BOTTOM_CENTER);
Responsive.makeResponsive(hLayout);
setContent(hLayout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
When you run the code given above, you can observe the following output in the browser.
To test the responsiveness of the layout, reduce the browser and you can observe that the panel and layout component will change their size and shape accordingly.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2003,
"s": 1769,
"text": "This chapter discusses in detail about another feature of Vaadin, known as Theme. In general, theme means a framework which is customizable at runtime. The content will be dynamic depending on the response received at the server end."
},
{
"code": null,
"e": 2349,
"s": 2003,
"text": "Vaadin provides a cool interface to use a theme with in a second with the help of its own Java based SAAS compiler. Theme feature is given to Vaadin in order to provide customizable style and look to the application. Theme is a pre-made template and developers need to customize it in order to build their own application which saves their time."
},
{
"code": null,
"e": 2765,
"s": 2349,
"text": "You can find all the themes in Vaadin under the theme folder and each of the sub folders are self-descript able. Hence, it is also very easy to change the code and customize the same. Any theme can have two types of CSS files in it − .saas type and .css type. Although Vaadin does not have any restriction on folder name, it is always recommended to use the folder name as you can notice from the image given above."
},
{
"code": null,
"e": 2865,
"s": 2765,
"text": "There are two kind of themes available − Inbuilt and Custom. This section discusses them in detail."
},
{
"code": null,
"e": 2950,
"s": 2865,
"text": "Vaadin built in theme is provided by annotating it with a theme name as shown below."
},
{
"code": null,
"e": 3000,
"s": 2950,
"text": "@Theme(\"mytheme\")\npublic class MyUI extends UI {\n"
},
{
"code": null,
"e": 3328,
"s": 3000,
"text": "All the grey color back ground while running a Vaadin application comes from the inbuilt css files. We can make change those files in order to make them as a custom theme which is another kind of theme. There is nothing we can learn about the Vaadin built in themes. All the above mentioned components are part of Vaadin Theme."
},
{
"code": null,
"e": 3814,
"s": 3328,
"text": "Custom themes are placed in the VAADIN/themes folder of the web application, in an Eclipse project under the WebContent folder or src/main/webapp in Maven projects. These locations are fixed and recommended not to change for any type of requirement. To define a SAAS theme with the name mytheme , you must place the file in the mytheme folder under theme folder then rebuild your project. Vaadin will automatically create its own .css file on the fly whenever requested by the browser."
},
{
"code": null,
"e": 3980,
"s": 3814,
"text": "You can change the style content in the css file as per your requirement. However, remember to build the project once again and it will start reflecting in progress."
},
{
"code": null,
"e": 4220,
"s": 3980,
"text": "Vaadin supports responsive theme too. Responsive web page can automatically set the font size according to the screen size. In the Vaadin application, we need to add a single line of code in order to make the entire application responsive."
},
{
"code": null,
"e": 4341,
"s": 4220,
"text": "Let us consider the following example to learn further about Vaadin. Make changes in the MyUI.java class as shown below."
},
{
"code": null,
"e": 6484,
"s": 4341,
"text": "package com.TutorialsMy.myApp;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.OutputStream;\nimport java.time.LocalDate;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;\nimport javax.servlet.annotation.WebServlet;\n\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.data.TreeData;\nimport com.vaadin.icons.VaadinIcons;\nimport com.vaadin.server.Responsive;\nimport com.vaadin.server.UserError;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.shared.ui.ContentMode;\n\nimport com.vaadin.ui.AbsoluteLayout;\nimport com.vaadin.ui.Alignment;\nimport com.vaadin.ui.Button;\nimport com.vaadin.ui.CustomLayout;\nimport com.vaadin.ui.DateField;\nimport com.vaadin.ui.FormLayout;\nimport com.vaadin.ui.Grid;\nimport com.vaadin.ui.HorizontalLayout;\nimport com.vaadin.ui.HorizontalSplitPanel;\n\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.Notification;\nimport com.vaadin.ui.Panel;\nimport com.vaadin.ui.TabSheet;\nimport com.vaadin.ui.TextField;\nimport com.vaadin.ui.Tree;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.Upload;\nimport com.vaadin.ui.Upload.Receiver;\nimport com.vaadin.ui.VerticalLayout;\nimport com.vaadin.ui.VerticalSplitPanel;\nimport com.vaadin.ui.Window;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n final VerticalLayout hLayout = new VerticalLayout();\n Label l1 = new Label(\"Enter today's Date\\n\",ContentMode.PREFORMATTED);\n DateField date = new DateField();\n date.setValue(LocalDate.now());\n date.setLocale(new Locale(\"en\",\"IND\"));\n hLayout.addComponents(l1,date);\n hLayout.setComponentAlignment(l1,Alignment.BOTTOM_CENTER);\n hLayout.setComponentAlignment(date,Alignment.BOTTOM_CENTER);\n Responsive.makeResponsive(hLayout);\n setContent(hLayout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 6572,
"s": 6484,
"text": "When you run the code given above, you can observe the following output in the browser."
},
{
"code": null,
"e": 6735,
"s": 6572,
"text": "To test the responsiveness of the layout, reduce the browser and you can observe that the panel and layout component will change their size and shape accordingly."
},
{
"code": null,
"e": 6742,
"s": 6735,
"text": " Print"
},
{
"code": null,
"e": 6753,
"s": 6742,
"text": " Add Notes"
}
]
|
Form validation using Django | In this article, we are going to learn how to validate a form in django. Django comes with build-in validators for forms. We can use them in the tutorial to validate forms.
You must familiar with the Django to follow along with this tutorial. If you are not familiar with Django, then this article is not for you.
Set up the basic Django project with the following commands.
mkdir form_validation
cd form_validation
python -m venv env (Activate environment based on your OS)
pip install django===3.0
django-admin startproject form_validation . (Don't forget dot(.) at the end)
python manage.py startapp validation
Now, create a filed called forms.py inside the validations app
We are going to validate a login form. See the following code of a Login model. Copy and paste it in the models.py file of the validations folder.
from django.db import models
class User(models.Model):
# username field
username = models.CharField(max_length=30, blank=False, null=False)
# password field
password = models.CharField(max_length=8, blank=False, null=False)
Now, we have to migrate the models. To make migrations, run the following command.
python manage.py makemigrations
python manage.py migrate
Now, place the following code in forms.py file.
from django.forms import ModelForm
from django import forms
from validation.models import User
class UserForm(ModelForm):
# meta data for displaying a form
class Meta:
# model
model = User
# displaying fields
fields = '__all__'
# method for cleaning the data
def clean(self):
super(UserForm, self).clean()
# getting username and password from cleaned_data
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
# validating the username and password
if len(username) < 5:
self._errors['username'] = self.error_class(['A minimum of 5 characters is required'])
if len(password) < 8:
self._errors['password'] = self.error_class(['Password length should not be less than 8 characters'])
return self.cleaned_data
Create a templates folder and a template called home.html inside the app. And paste the following code inside the home template.
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Validation</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h2>User</h2>
<form action="" method="post">
{%csrf_token%} {{ form|crispy }}
<div class="form-group">
<button type="submit" class="btn btn-success">
Add User
</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Now, let's write some code in the views.py file.
from django.shortcuts import render
from django.http import HttpResponse
from .forms import UserForm
# Create your views here.
def home_view(request):
# cheking the request
if request.method == 'POST':
# passing the form data to LoginForm
user_details = UserForm(request.POST)
# validating the user_details with is_valid() method
if user_details.is_valid():
# writing data to the database
user_details.save()
# redirect to another page with success message
return HttpResponse("Data submitted successfully")
else:
# redirect back to the user page with errors
return render(request, 'validation/home.html', {'form':user_details})
else:
# in case of GET request
form = UserForm(None)
return render(request, 'validation/home.html', {'form':form})
Add the path of home.html template in the urls.py file of the project. See the below code. Replace the validation with your app name.
from django.contrib import admin
from django.urls import path
from validation.views import home_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='home'),
]
After completing all the above steps, you can view the form in the browser.
If you have any doubts in the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1235,
"s": 1062,
"text": "In this article, we are going to learn how to validate a form in django. Django comes with build-in validators for forms. We can use them in the tutorial to validate forms."
},
{
"code": null,
"e": 1376,
"s": 1235,
"text": "You must familiar with the Django to follow along with this tutorial. If you are not familiar with Django, then this article is not for you."
},
{
"code": null,
"e": 1437,
"s": 1376,
"text": "Set up the basic Django project with the following commands."
},
{
"code": null,
"e": 1745,
"s": 1437,
"text": "mkdir form_validation\n\ncd form_validation\n\npython -m venv env (Activate environment based on your OS)\n\npip install django===3.0\n\ndjango-admin startproject form_validation . (Don't forget dot(.) at the end)\n\npython manage.py startapp validation\n\nNow, create a filed called forms.py inside the validations app"
},
{
"code": null,
"e": 1892,
"s": 1745,
"text": "We are going to validate a login form. See the following code of a Login model. Copy and paste it in the models.py file of the validations folder."
},
{
"code": null,
"e": 2118,
"s": 1892,
"text": "from django.db import models\n\n\nclass User(models.Model):\n# username field\nusername = models.CharField(max_length=30, blank=False, null=False)\n# password field\npassword = models.CharField(max_length=8, blank=False, null=False)"
},
{
"code": null,
"e": 2201,
"s": 2118,
"text": "Now, we have to migrate the models. To make migrations, run the following command."
},
{
"code": null,
"e": 2259,
"s": 2201,
"text": "python manage.py makemigrations\n\npython manage.py migrate"
},
{
"code": null,
"e": 2307,
"s": 2259,
"text": "Now, place the following code in forms.py file."
},
{
"code": null,
"e": 3162,
"s": 2307,
"text": "from django.forms import ModelForm\nfrom django import forms\n\nfrom validation.models import User\n\n\nclass UserForm(ModelForm):\n\n # meta data for displaying a form\n class Meta:\n # model\n model = User\n\n # displaying fields\n fields = '__all__'\n\n # method for cleaning the data\n def clean(self):\n super(UserForm, self).clean()\n\n # getting username and password from cleaned_data\n username = self.cleaned_data.get('username')\n password = self.cleaned_data.get('password')\n\n # validating the username and password\n if len(username) < 5:\n self._errors['username'] = self.error_class(['A minimum of 5 characters is required'])\n\n if len(password) < 8:\n self._errors['password'] = self.error_class(['Password length should not be less than 8 characters'])\n\n return self.cleaned_data"
},
{
"code": null,
"e": 3291,
"s": 3162,
"text": "Create a templates folder and a template called home.html inside the app. And paste the following code inside the home template."
},
{
"code": null,
"e": 4018,
"s": 3291,
"text": "{% load crispy_forms_tags %}\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Form Validation</title>\n<link\nrel=\"stylesheet\"\nhref=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\"\nintegrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\"\ncrossorigin=\"anonymous\"\n/>\n</head>\n<body>\n<div class=\"container\">\n<div class=\"row\">\n<div class=\"col-md-4 col-md-offset-4\">\n<h2>User</h2>\n<form action=\"\" method=\"post\">\n{%csrf_token%} {{ form|crispy }}\n<div class=\"form-group\">\n<button type=\"submit\" class=\"btn btn-success\">\nAdd User\n</button>\n</div>\n</form>\n</div>\n</div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 4067,
"s": 4018,
"text": "Now, let's write some code in the views.py file."
},
{
"code": null,
"e": 4945,
"s": 4067,
"text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom .forms import UserForm\n\n\n# Create your views here.\ndef home_view(request):\n\n # cheking the request\n if request.method == 'POST':\n\n # passing the form data to LoginForm\n user_details = UserForm(request.POST)\n\n # validating the user_details with is_valid() method\n if user_details.is_valid():\n\n # writing data to the database\n user_details.save()\n\n # redirect to another page with success message\n return HttpResponse(\"Data submitted successfully\")\n\n else:\n\n # redirect back to the user page with errors\n return render(request, 'validation/home.html', {'form':user_details})\n else:\n\n # in case of GET request\n form = UserForm(None)\n return render(request, 'validation/home.html', {'form':form})"
},
{
"code": null,
"e": 5079,
"s": 4945,
"text": "Add the path of home.html template in the urls.py file of the project. See the below code. Replace the validation with your app name."
},
{
"code": null,
"e": 5273,
"s": 5079,
"text": "from django.contrib import admin\nfrom django.urls import path\n\nfrom validation.views import home_view\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', home_view, name='home'),\n]"
},
{
"code": null,
"e": 5349,
"s": 5273,
"text": "After completing all the above steps, you can view the form in the browser."
},
{
"code": null,
"e": 5426,
"s": 5349,
"text": "If you have any doubts in the tutorial, mention them in the comment section."
}
]
|
How to get connected remote desktop users on computers using PowerShell? | To get the user sessions on the remote computers using PowerShell, we need to use the cmd query command. First of all, we will get the user sessions on the local computer using the below command.
query session
Let’s see what are other supported parameters for the query session command.
PS C:\> query session /?
Display information about Remote Desktop Services sessions.
QUERY SESSION [sessionname | username | sessionid]
[/SERVER:servername] [/MODE] [/FLOW] [/CONNECT] [/COUNTER] [/VM]
sessionname Identifies the session named sessionname.
username Identifies the session with user username.
sessionid Identifies the session with ID sessionid.
/SERVER:servername The server to be queried (default is current).
/MODE Display current line settings.
/FLOW Display current flow control settings.
/CONNECT Display current connect settings.
/COUNTER Display current Remote Desktop Services counters information.
/VM Display information about sessions within virtual machines.
To get the sessions on the remote computers, we can use /Server:ServerName switch.
query session /server:Test1-win2k12 | [
{
"code": null,
"e": 1258,
"s": 1062,
"text": "To get the user sessions on the remote computers using PowerShell, we need to use the cmd query command. First of all, we will get the user sessions on the local computer using the below command."
},
{
"code": null,
"e": 1272,
"s": 1258,
"text": "query session"
},
{
"code": null,
"e": 1349,
"s": 1272,
"text": "Let’s see what are other supported parameters for the query session command."
},
{
"code": null,
"e": 2146,
"s": 1349,
"text": "PS C:\\> query session /?\nDisplay information about Remote Desktop Services sessions.\n\nQUERY SESSION [sessionname | username | sessionid]\n [/SERVER:servername] [/MODE] [/FLOW] [/CONNECT] [/COUNTER] [/VM]\n\nsessionname Identifies the session named sessionname.\nusername Identifies the session with user username.\nsessionid Identifies the session with ID sessionid.\n/SERVER:servername The server to be queried (default is current).\n/MODE Display current line settings.\n/FLOW Display current flow control settings.\n/CONNECT Display current connect settings.\n/COUNTER Display current Remote Desktop Services counters information.\n/VM Display information about sessions within virtual machines."
},
{
"code": null,
"e": 2229,
"s": 2146,
"text": "To get the sessions on the remote computers, we can use /Server:ServerName switch."
},
{
"code": null,
"e": 2265,
"s": 2229,
"text": "query session /server:Test1-win2k12"
}
]
|
Beginner’s guide to creating a powerful chatbot | by Louis Teo | Towards Data Science | Are you facing too many standard requests and questions from customers and struggling to cope with them? Are you looking for a way to expand your customer service without incurring much costs?
In my previous story, I shared how I tackled data overburden issues by creating a personal text summarizer to summarize a document.
In this story, I will show you how you can easily create a powerful chatbot to handle your growing customer requests and inquiries. I will also show you how to deploy your chatbot to a web application using Flask.
The Covid-19 pandemic has hit the world hard. Many businesses have suffered major losses due to lockdown / movement controls. To ride through this tough time, many were forced to move their businesses online.
One of the main, common problems faced by online business owners is having to respond to an overwhelming number of questions and requests from customers. For those with limited manpower resources, it’s impossible to deal with all requests in time.
To solve this problem, many business owners have turned to using chatbot for their customer service.
What is a chatbot: a chatbot is AI-powered intelligent software that is capable of having conversations with human and performing human-like tasks. Chatbots are present in many smart devices (e.g. Siri (iOS), Google Assistant (Android), Cortana (Microsoft), Alexa (Amazon)), websites and applications.
Why use a chatbot: According to a research carried out by HubSpot, 71% of users were willing to use quick-to-respond chat apps to receive customer assistance, and many do so because they want their problems to be solved FAST (and efficiently, of course). A chatbot, if configured intelligently, indeed can unlock great values for businesses by allowing manpower resources to be focused on critical operations while maintaining the same level of customer satisfaction.
I will divide this into three major sections — but know that you can go directly to the section that is of your interest:
(a) Building a chatbot using Jupyter notebook
(b) Running chatbot in terminal
(c) Deploying chatbot as web app using Flask
Thanks to the ChatterBot library in Python, creating a chatbot is no longer a daunting machine learning task that it used to be.
Now, let’s get our hands dirty...
(1) Install the ChatterBot library
We will begin by installing the ChatterBot library. Installation commands for terminal are as follows:
pip install chatterbot
The ChatterBot text corpus (language resource consisting of a large and structured set of texts) is distributed in its own Python package, so you need to install it separately:
pip install chatterbot_corpus
If you have not installed spaCy (an open source library for advanced Natural Language Processing) before, then please install it now because the ChatterBot library needs spaCy library to work:
pip install spacy
Install spaCy English (‘en’) model after installing the spaCy library:
python -m spacy download en
(2) Create chatbot instance
We will develop our chatbot using Jupyter Notebook before we package the entire chatbot to Python scripts. Let’s begin by importing the module we need:
from chatterbot import ChatBot
We will create a chatbot instance, name our bot as Buddy and specify read_only parameter to True because we only want our chatbot to learn from our training data.
By creating a chatbot instance, a chatbot database named db.sqlite3 will be created for you.
bot = ChatBot('Buddy', read_only = True)
(3) Train the chatbot
It’s time to train our chatbot... (What, just like that? Yes — it’s no joke!)
The training simply means feeding conversations into the chatbot database. See the example below:
As soon as the chatbot is fed with ‘conversation 1’ and ‘conversation 2’, the chatbot will store the conversations in its ‘knowledge graph’ database in the correct order.
After that, you can initiate a conversation using any of the statements above.
For example, you can start a conversation with statement 6 (“ What payment methods do you accept?”), and the chatbot will respond with statement 7 (“We accept debit cards and major credit cards).
With this concept in mind, let’s train our chatbot with ‘conversation 1’ and ‘conversation 2’.
We do so by importing the ListTrainer module, instantiating it by passing the chatbot object (Buddy) and calling the train() method to pass a list of sentences.
from chatterbot.trainers import ListTrainertrainer = ListTrainer(bot)trainer.train([ "Hi, can I help you", "Who are you?", "I am your virtual assistant. Ask me any questions...", "Where do you operate?", "We operate from Singapore", "What payment methods do you accept?", "We accept debit cards and major credit cards", "I would like to speak to your customer service agent", "please call +65 3333 3333. Our operating hours are from 9am to 5pm, Monday to Friday" ])trainer.train([ "What payment methods do you offer?", "We accept debit cards and major credit cards", "How to contact customer service agent", "please call +65 3333 3333. Our operating hours are from 9am to 5pm, Monday to Friday" ])
Chatbot Testing
To check if we have fed our conversations correctly to our chatbot, let’s test it out by feeding the chatbot with just a simple input statement - ‘payment method’.
response = bot.get_response ('payment method')print(response)
The chatbot responded to us with:
This response is exactly what we want.
We will create a while loop to enable our chatbot to respond to each of our queries continuously. We will put an end to the loop and stop the program when we get ‘Bye’ or ‘bye’ statement from the user.
name = input('Enter Your Name: ')print ('Welcome to Chatbot Service! Let me know how can I help you')while True: request = input(name+':') if request=="Bye" or request=='bye': print('Bot: Bye') break else: response=bot.get_response(request) print('Bot: ', response)
Let’s try it out...
Congratulations! You have just created your very first, working chatbot!
Corpus data training
Of course you would want your chatbot to be able to have more conversations on top of those that we just fed in (!) — in that case, we need to train our chatbot further.
Fortunately, this task has been simplified for us. We can quickly train our chatbot to communicate in a more ‘human-like’ and smarter way with us, by using the available English corpus data in the package.
Note: If you face problems in running the corpus training, please copy this chatterbot_corpus folder to the file directory specified in the error message.
Just run the codes below, and your chatbot will be trained to have conversations in the following scope: AI, botprofile, computers, conversations, emotion, food, gossip, greetings, health, history, humor, literature, money, movies, politics, psychology, science, sports & trivia.
from chatterbot.trainers import ChatterBotCorpusTrainertrainer = ChatterBotCorpusTrainer(bot)trainer.train('chatterbot.corpus.english')
Let’s test if our chatbot has become smarter now....
Yes! It’s become smarter — it can tell you a joke now...
Preprocess input
ChatterBot comes with several built-in preprocessors that allow us to clean our input statement, before we get the statement processed by the bot’s logic adapter.
Cleaning makes our input statement more readable and analyzable by our chatbot. It removes ‘noise’ that can interfere with the text analysis from the input statement - e.g. additional space, Unicode characters and escaped html characters.
We will now include the preprocessors in our chatbot instance and rerun the chatbot instance with the codes below.
bot = ChatBot('Buddy', read_only = True, preprocessors=['chatterbot.preprocessors.clean_whitespace', 'chatterbot.preprocessors.unescape_html', 'chatterbot.preprocessors.convert_to_ascii'])
Then, rerun the chatbot, and you can see we get the same response for who are you and whó are yóu.
Low confidence response
On top of that, we can also configure our chatbot to inform users if the input is not understood, with a default response:
‘I am sorry, I do not understand. I am still learning. Please contact [email protected] for further assistance.’
Let’s include the low confidence response to our chatbot instance and rerun the chatbot instance.
bot = ChatBot('Buddy', logic_adapters = [ { 'import_path': 'chatterbot.logic.BestMatch', 'default_response': 'I am sorry, I do not understand. I am still learning. Please contact [email protected] for further assistance.', 'maximum_similarity_threshold': 0.90 } ], read_only = True, preprocessors=['chatterbot.preprocessors.clean_whitespace','chatterbot.preprocessors.unescape_html','chatterbot.preprocessors.convert_to_ascii'])
Then, rerun the chatbot, and let’s try to get a response from an unexpected input — our chatbot will reply with the default_response when it doesn’t understand a statement.
Congratulations! You have successfully built a chatbot using Jupyter notebook.
Here is the link to my Github for the Jupyter Notebook on this.
Note: If you have come straight to this section (and skipped section (a) Building a chatbot using Jupyter notebook), then please ensure you have installed all the required library and packages mentioned in that section before proceeding to run the chatbot in terminal.
We will use the Jupyter notebook above to write scripts that run the steps above and perform the chatbot training based on the conversation files specified by the user, and then see our chatbot in action...!
You can download my complete scripts here which you can use right away to train and run your chatbot!
Create a training_data folder and store all the conversations you want to train in text file(s). The chatbot_training.py script will read all the text files in the training_data folder.
Create a training_data folder and store all the conversations you want to train in text file(s). The chatbot_training.py script will read all the text files in the training_data folder.
The conversation in the text file should be inputted as one sentence per line:
2. Run chatbot_training.py. You will be asked to choose if you want to train the chatbot with English corpus data — select Y or N.
Select Y — your chatbot will be trained to have conversations in the following scope: AI, botprofile, computers, conversations, emotion, food, gossip, greetings, health, history, humor, literature, money, movies, politics, psychology, science, sports & trivia.
3. Then, run the chatbot.py to launch the chatbot. Input some conversations and test if it responds properly.
Tadaa... there you go! You have completed your chatbot training and run it in the terminal.
Note: If you have come straight this section (and skipped section (a) Building a chatbot using Jupyter notebook), then please ensure you have installed all the required library and packages mentioned in that section before proceeding to deploy chatbot to web app using Flask.
We deploy our chatbot to a web application so that it can be used by customers.
To run our chatbot on a web application, we need to find a way for our application to receive incoming data and to return data. We can do this in any way we want — HTTP requests, web sockets etc.
There are a few existing examples available on the ChatterBot FAQ page that show us how to do this. I will show you how to deploy a web application using Flask.
Download the example codes from my Github, edit the index.html file in template folder and style.css file in static folder to your liking. Leave the files as they are if you just want to test the chatbot on a web application.
After that, let’s run web_app.py.
This deploys our chatbot to a local server at http://127.0.0.1:5000/
Launch your web browser and go to the URL above to launch your chatbot.
Congratulations (again)! You’ve successfully built your first business chatbot and deployed it to a web application using Flask. The chatbot, I should hope, did a pretty good job in answering some standard business questions you’ve had it trained on.
One of the things you can do to further improve the performance of your chatbot, is compile a list of FAQs that have been posted by your customers to date, provide answers to the FAQs and then train them on your chatbot.
Why some chatbots failed to live up to expectations? Some chatbots failed simply because the standard questions and requests made to a business had not been analysed sufficiently, and as a result the chatbot did not receive the training it required. Training and improving your chatbot is a continuous process in the beginning and is similar to how humans learn new skills and knowledge. And once the skills are learned, they’re built in the chatbot and the chatbot does not need to be retrained, unless and until your business grows.
Next, you can look into deploying your chatbot to a Platform-as-a-Service (PaaS) of your choice, which can host and run your web application entirely from the cloud. One of the popular free PaaS’ that you can consider is Heroku.
Thank you for reading this story! Follow me on medium for more tips on how to grow your business using DIY machine learning. | [
{
"code": null,
"e": 364,
"s": 171,
"text": "Are you facing too many standard requests and questions from customers and struggling to cope with them? Are you looking for a way to expand your customer service without incurring much costs?"
},
{
"code": null,
"e": 496,
"s": 364,
"text": "In my previous story, I shared how I tackled data overburden issues by creating a personal text summarizer to summarize a document."
},
{
"code": null,
"e": 710,
"s": 496,
"text": "In this story, I will show you how you can easily create a powerful chatbot to handle your growing customer requests and inquiries. I will also show you how to deploy your chatbot to a web application using Flask."
},
{
"code": null,
"e": 919,
"s": 710,
"text": "The Covid-19 pandemic has hit the world hard. Many businesses have suffered major losses due to lockdown / movement controls. To ride through this tough time, many were forced to move their businesses online."
},
{
"code": null,
"e": 1167,
"s": 919,
"text": "One of the main, common problems faced by online business owners is having to respond to an overwhelming number of questions and requests from customers. For those with limited manpower resources, it’s impossible to deal with all requests in time."
},
{
"code": null,
"e": 1268,
"s": 1167,
"text": "To solve this problem, many business owners have turned to using chatbot for their customer service."
},
{
"code": null,
"e": 1570,
"s": 1268,
"text": "What is a chatbot: a chatbot is AI-powered intelligent software that is capable of having conversations with human and performing human-like tasks. Chatbots are present in many smart devices (e.g. Siri (iOS), Google Assistant (Android), Cortana (Microsoft), Alexa (Amazon)), websites and applications."
},
{
"code": null,
"e": 2038,
"s": 1570,
"text": "Why use a chatbot: According to a research carried out by HubSpot, 71% of users were willing to use quick-to-respond chat apps to receive customer assistance, and many do so because they want their problems to be solved FAST (and efficiently, of course). A chatbot, if configured intelligently, indeed can unlock great values for businesses by allowing manpower resources to be focused on critical operations while maintaining the same level of customer satisfaction."
},
{
"code": null,
"e": 2160,
"s": 2038,
"text": "I will divide this into three major sections — but know that you can go directly to the section that is of your interest:"
},
{
"code": null,
"e": 2206,
"s": 2160,
"text": "(a) Building a chatbot using Jupyter notebook"
},
{
"code": null,
"e": 2238,
"s": 2206,
"text": "(b) Running chatbot in terminal"
},
{
"code": null,
"e": 2283,
"s": 2238,
"text": "(c) Deploying chatbot as web app using Flask"
},
{
"code": null,
"e": 2412,
"s": 2283,
"text": "Thanks to the ChatterBot library in Python, creating a chatbot is no longer a daunting machine learning task that it used to be."
},
{
"code": null,
"e": 2446,
"s": 2412,
"text": "Now, let’s get our hands dirty..."
},
{
"code": null,
"e": 2481,
"s": 2446,
"text": "(1) Install the ChatterBot library"
},
{
"code": null,
"e": 2584,
"s": 2481,
"text": "We will begin by installing the ChatterBot library. Installation commands for terminal are as follows:"
},
{
"code": null,
"e": 2607,
"s": 2584,
"text": "pip install chatterbot"
},
{
"code": null,
"e": 2784,
"s": 2607,
"text": "The ChatterBot text corpus (language resource consisting of a large and structured set of texts) is distributed in its own Python package, so you need to install it separately:"
},
{
"code": null,
"e": 2814,
"s": 2784,
"text": "pip install chatterbot_corpus"
},
{
"code": null,
"e": 3007,
"s": 2814,
"text": "If you have not installed spaCy (an open source library for advanced Natural Language Processing) before, then please install it now because the ChatterBot library needs spaCy library to work:"
},
{
"code": null,
"e": 3025,
"s": 3007,
"text": "pip install spacy"
},
{
"code": null,
"e": 3096,
"s": 3025,
"text": "Install spaCy English (‘en’) model after installing the spaCy library:"
},
{
"code": null,
"e": 3124,
"s": 3096,
"text": "python -m spacy download en"
},
{
"code": null,
"e": 3152,
"s": 3124,
"text": "(2) Create chatbot instance"
},
{
"code": null,
"e": 3304,
"s": 3152,
"text": "We will develop our chatbot using Jupyter Notebook before we package the entire chatbot to Python scripts. Let’s begin by importing the module we need:"
},
{
"code": null,
"e": 3335,
"s": 3304,
"text": "from chatterbot import ChatBot"
},
{
"code": null,
"e": 3498,
"s": 3335,
"text": "We will create a chatbot instance, name our bot as Buddy and specify read_only parameter to True because we only want our chatbot to learn from our training data."
},
{
"code": null,
"e": 3591,
"s": 3498,
"text": "By creating a chatbot instance, a chatbot database named db.sqlite3 will be created for you."
},
{
"code": null,
"e": 3632,
"s": 3591,
"text": "bot = ChatBot('Buddy', read_only = True)"
},
{
"code": null,
"e": 3654,
"s": 3632,
"text": "(3) Train the chatbot"
},
{
"code": null,
"e": 3732,
"s": 3654,
"text": "It’s time to train our chatbot... (What, just like that? Yes — it’s no joke!)"
},
{
"code": null,
"e": 3830,
"s": 3732,
"text": "The training simply means feeding conversations into the chatbot database. See the example below:"
},
{
"code": null,
"e": 4001,
"s": 3830,
"text": "As soon as the chatbot is fed with ‘conversation 1’ and ‘conversation 2’, the chatbot will store the conversations in its ‘knowledge graph’ database in the correct order."
},
{
"code": null,
"e": 4080,
"s": 4001,
"text": "After that, you can initiate a conversation using any of the statements above."
},
{
"code": null,
"e": 4276,
"s": 4080,
"text": "For example, you can start a conversation with statement 6 (“ What payment methods do you accept?”), and the chatbot will respond with statement 7 (“We accept debit cards and major credit cards)."
},
{
"code": null,
"e": 4371,
"s": 4276,
"text": "With this concept in mind, let’s train our chatbot with ‘conversation 1’ and ‘conversation 2’."
},
{
"code": null,
"e": 4532,
"s": 4371,
"text": "We do so by importing the ListTrainer module, instantiating it by passing the chatbot object (Buddy) and calling the train() method to pass a list of sentences."
},
{
"code": null,
"e": 5275,
"s": 4532,
"text": "from chatterbot.trainers import ListTrainertrainer = ListTrainer(bot)trainer.train([ \"Hi, can I help you\", \"Who are you?\", \"I am your virtual assistant. Ask me any questions...\", \"Where do you operate?\", \"We operate from Singapore\", \"What payment methods do you accept?\", \"We accept debit cards and major credit cards\", \"I would like to speak to your customer service agent\", \"please call +65 3333 3333. Our operating hours are from 9am to 5pm, Monday to Friday\" ])trainer.train([ \"What payment methods do you offer?\", \"We accept debit cards and major credit cards\", \"How to contact customer service agent\", \"please call +65 3333 3333. Our operating hours are from 9am to 5pm, Monday to Friday\" ])"
},
{
"code": null,
"e": 5291,
"s": 5275,
"text": "Chatbot Testing"
},
{
"code": null,
"e": 5455,
"s": 5291,
"text": "To check if we have fed our conversations correctly to our chatbot, let’s test it out by feeding the chatbot with just a simple input statement - ‘payment method’."
},
{
"code": null,
"e": 5517,
"s": 5455,
"text": "response = bot.get_response ('payment method')print(response)"
},
{
"code": null,
"e": 5551,
"s": 5517,
"text": "The chatbot responded to us with:"
},
{
"code": null,
"e": 5590,
"s": 5551,
"text": "This response is exactly what we want."
},
{
"code": null,
"e": 5792,
"s": 5590,
"text": "We will create a while loop to enable our chatbot to respond to each of our queries continuously. We will put an end to the loop and stop the program when we get ‘Bye’ or ‘bye’ statement from the user."
},
{
"code": null,
"e": 6103,
"s": 5792,
"text": "name = input('Enter Your Name: ')print ('Welcome to Chatbot Service! Let me know how can I help you')while True: request = input(name+':') if request==\"Bye\" or request=='bye': print('Bot: Bye') break else: response=bot.get_response(request) print('Bot: ', response)"
},
{
"code": null,
"e": 6123,
"s": 6103,
"text": "Let’s try it out..."
},
{
"code": null,
"e": 6196,
"s": 6123,
"text": "Congratulations! You have just created your very first, working chatbot!"
},
{
"code": null,
"e": 6217,
"s": 6196,
"text": "Corpus data training"
},
{
"code": null,
"e": 6387,
"s": 6217,
"text": "Of course you would want your chatbot to be able to have more conversations on top of those that we just fed in (!) — in that case, we need to train our chatbot further."
},
{
"code": null,
"e": 6593,
"s": 6387,
"text": "Fortunately, this task has been simplified for us. We can quickly train our chatbot to communicate in a more ‘human-like’ and smarter way with us, by using the available English corpus data in the package."
},
{
"code": null,
"e": 6748,
"s": 6593,
"text": "Note: If you face problems in running the corpus training, please copy this chatterbot_corpus folder to the file directory specified in the error message."
},
{
"code": null,
"e": 7028,
"s": 6748,
"text": "Just run the codes below, and your chatbot will be trained to have conversations in the following scope: AI, botprofile, computers, conversations, emotion, food, gossip, greetings, health, history, humor, literature, money, movies, politics, psychology, science, sports & trivia."
},
{
"code": null,
"e": 7164,
"s": 7028,
"text": "from chatterbot.trainers import ChatterBotCorpusTrainertrainer = ChatterBotCorpusTrainer(bot)trainer.train('chatterbot.corpus.english')"
},
{
"code": null,
"e": 7217,
"s": 7164,
"text": "Let’s test if our chatbot has become smarter now...."
},
{
"code": null,
"e": 7274,
"s": 7217,
"text": "Yes! It’s become smarter — it can tell you a joke now..."
},
{
"code": null,
"e": 7291,
"s": 7274,
"text": "Preprocess input"
},
{
"code": null,
"e": 7454,
"s": 7291,
"text": "ChatterBot comes with several built-in preprocessors that allow us to clean our input statement, before we get the statement processed by the bot’s logic adapter."
},
{
"code": null,
"e": 7693,
"s": 7454,
"text": "Cleaning makes our input statement more readable and analyzable by our chatbot. It removes ‘noise’ that can interfere with the text analysis from the input statement - e.g. additional space, Unicode characters and escaped html characters."
},
{
"code": null,
"e": 7808,
"s": 7693,
"text": "We will now include the preprocessors in our chatbot instance and rerun the chatbot instance with the codes below."
},
{
"code": null,
"e": 8073,
"s": 7808,
"text": "bot = ChatBot('Buddy', read_only = True, preprocessors=['chatterbot.preprocessors.clean_whitespace', 'chatterbot.preprocessors.unescape_html', 'chatterbot.preprocessors.convert_to_ascii'])"
},
{
"code": null,
"e": 8174,
"s": 8073,
"text": "Then, rerun the chatbot, and you can see we get the same response for who are you and whó are yóu."
},
{
"code": null,
"e": 8198,
"s": 8174,
"text": "Low confidence response"
},
{
"code": null,
"e": 8321,
"s": 8198,
"text": "On top of that, we can also configure our chatbot to inform users if the input is not understood, with a default response:"
},
{
"code": null,
"e": 8428,
"s": 8321,
"text": "‘I am sorry, I do not understand. I am still learning. Please contact [email protected] for further assistance.’"
},
{
"code": null,
"e": 8526,
"s": 8428,
"text": "Let’s include the low confidence response to our chatbot instance and rerun the chatbot instance."
},
{
"code": null,
"e": 9089,
"s": 8526,
"text": "bot = ChatBot('Buddy', logic_adapters = [ { 'import_path': 'chatterbot.logic.BestMatch', 'default_response': 'I am sorry, I do not understand. I am still learning. Please contact [email protected] for further assistance.', 'maximum_similarity_threshold': 0.90 } ], read_only = True, preprocessors=['chatterbot.preprocessors.clean_whitespace','chatterbot.preprocessors.unescape_html','chatterbot.preprocessors.convert_to_ascii'])"
},
{
"code": null,
"e": 9262,
"s": 9089,
"text": "Then, rerun the chatbot, and let’s try to get a response from an unexpected input — our chatbot will reply with the default_response when it doesn’t understand a statement."
},
{
"code": null,
"e": 9341,
"s": 9262,
"text": "Congratulations! You have successfully built a chatbot using Jupyter notebook."
},
{
"code": null,
"e": 9405,
"s": 9341,
"text": "Here is the link to my Github for the Jupyter Notebook on this."
},
{
"code": null,
"e": 9674,
"s": 9405,
"text": "Note: If you have come straight to this section (and skipped section (a) Building a chatbot using Jupyter notebook), then please ensure you have installed all the required library and packages mentioned in that section before proceeding to run the chatbot in terminal."
},
{
"code": null,
"e": 9882,
"s": 9674,
"text": "We will use the Jupyter notebook above to write scripts that run the steps above and perform the chatbot training based on the conversation files specified by the user, and then see our chatbot in action...!"
},
{
"code": null,
"e": 9984,
"s": 9882,
"text": "You can download my complete scripts here which you can use right away to train and run your chatbot!"
},
{
"code": null,
"e": 10170,
"s": 9984,
"text": "Create a training_data folder and store all the conversations you want to train in text file(s). The chatbot_training.py script will read all the text files in the training_data folder."
},
{
"code": null,
"e": 10356,
"s": 10170,
"text": "Create a training_data folder and store all the conversations you want to train in text file(s). The chatbot_training.py script will read all the text files in the training_data folder."
},
{
"code": null,
"e": 10435,
"s": 10356,
"text": "The conversation in the text file should be inputted as one sentence per line:"
},
{
"code": null,
"e": 10566,
"s": 10435,
"text": "2. Run chatbot_training.py. You will be asked to choose if you want to train the chatbot with English corpus data — select Y or N."
},
{
"code": null,
"e": 10827,
"s": 10566,
"text": "Select Y — your chatbot will be trained to have conversations in the following scope: AI, botprofile, computers, conversations, emotion, food, gossip, greetings, health, history, humor, literature, money, movies, politics, psychology, science, sports & trivia."
},
{
"code": null,
"e": 10937,
"s": 10827,
"text": "3. Then, run the chatbot.py to launch the chatbot. Input some conversations and test if it responds properly."
},
{
"code": null,
"e": 11029,
"s": 10937,
"text": "Tadaa... there you go! You have completed your chatbot training and run it in the terminal."
},
{
"code": null,
"e": 11305,
"s": 11029,
"text": "Note: If you have come straight this section (and skipped section (a) Building a chatbot using Jupyter notebook), then please ensure you have installed all the required library and packages mentioned in that section before proceeding to deploy chatbot to web app using Flask."
},
{
"code": null,
"e": 11385,
"s": 11305,
"text": "We deploy our chatbot to a web application so that it can be used by customers."
},
{
"code": null,
"e": 11581,
"s": 11385,
"text": "To run our chatbot on a web application, we need to find a way for our application to receive incoming data and to return data. We can do this in any way we want — HTTP requests, web sockets etc."
},
{
"code": null,
"e": 11742,
"s": 11581,
"text": "There are a few existing examples available on the ChatterBot FAQ page that show us how to do this. I will show you how to deploy a web application using Flask."
},
{
"code": null,
"e": 11968,
"s": 11742,
"text": "Download the example codes from my Github, edit the index.html file in template folder and style.css file in static folder to your liking. Leave the files as they are if you just want to test the chatbot on a web application."
},
{
"code": null,
"e": 12002,
"s": 11968,
"text": "After that, let’s run web_app.py."
},
{
"code": null,
"e": 12071,
"s": 12002,
"text": "This deploys our chatbot to a local server at http://127.0.0.1:5000/"
},
{
"code": null,
"e": 12143,
"s": 12071,
"text": "Launch your web browser and go to the URL above to launch your chatbot."
},
{
"code": null,
"e": 12394,
"s": 12143,
"text": "Congratulations (again)! You’ve successfully built your first business chatbot and deployed it to a web application using Flask. The chatbot, I should hope, did a pretty good job in answering some standard business questions you’ve had it trained on."
},
{
"code": null,
"e": 12615,
"s": 12394,
"text": "One of the things you can do to further improve the performance of your chatbot, is compile a list of FAQs that have been posted by your customers to date, provide answers to the FAQs and then train them on your chatbot."
},
{
"code": null,
"e": 13150,
"s": 12615,
"text": "Why some chatbots failed to live up to expectations? Some chatbots failed simply because the standard questions and requests made to a business had not been analysed sufficiently, and as a result the chatbot did not receive the training it required. Training and improving your chatbot is a continuous process in the beginning and is similar to how humans learn new skills and knowledge. And once the skills are learned, they’re built in the chatbot and the chatbot does not need to be retrained, unless and until your business grows."
},
{
"code": null,
"e": 13379,
"s": 13150,
"text": "Next, you can look into deploying your chatbot to a Platform-as-a-Service (PaaS) of your choice, which can host and run your web application entirely from the cloud. One of the popular free PaaS’ that you can consider is Heroku."
}
]
|
How to remove pagefile on the specific drive using PowerShell? | In this article, we have a pagefile set on E: (System managed) and we need to remove the pagefile from E: So in the below image once we remove it, the pagefile should be “No Paging File”.
To do so using PowerShell, we need to filter the pagefile on a specific drive and need to run the below code.
$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}
$pagefileset.Delete()
You may want to reboot the server after removing pagefile.
To change the above settings on the remote computer, use -ComputerName parameter in the GetWMIObject class. | [
{
"code": null,
"e": 1250,
"s": 1062,
"text": "In this article, we have a pagefile set on E: (System managed) and we need to remove the pagefile from E: So in the below image once we remove it, the pagefile should be “No Paging File”."
},
{
"code": null,
"e": 1360,
"s": 1250,
"text": "To do so using PowerShell, we need to filter the pagefile on a specific drive and need to run the below code."
},
{
"code": null,
"e": 1456,
"s": 1360,
"text": "$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}\n$pagefileset.Delete()"
},
{
"code": null,
"e": 1515,
"s": 1456,
"text": "You may want to reboot the server after removing pagefile."
},
{
"code": null,
"e": 1623,
"s": 1515,
"text": "To change the above settings on the remote computer, use -ComputerName parameter in the GetWMIObject class."
}
]
|
How do I load an ImageView by URL on Android using kotlin? | This example demonstrates how to load an ImageView by URL on Android using kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<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:padding="4dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Load Image From URL in Android ImageView"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="24sp"
android:textStyle="bold" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/text"
android:layout_marginTop="5dp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp" DownloadImageFromInternet(findViewById(R.id.imageView)).execute("https://images.unsplash.com/photo-1535332371349-a5d229f49cb5?ixlib=rb-1.2.1&w=1000&q=80")
}
@SuppressLint("StaticFieldLeak")
@Suppress("DEPRECATION")
private inner class DownloadImageFromInternet(var imageView: ImageView) : AsyncTask<String, Void, Bitmap?>() {
init {
Toast.makeText(applicationContext, "Please wait, it may take a few minute...", Toast.LENGTH_SHORT).show()
}
override fun doInBackground(vararg urls: String): Bitmap? {
val imageURL = urls[0]
var image: Bitmap? = null
try {
val `in` = java.net.URL(imageURL).openStream()
image = BitmapFactory.decodeStream(`in`)
}
catch (e: Exception) {
Log.e("Error Message", e.message.toString())
e.printStackTrace()
}
return image
}
override fun onPostExecute(result: Bitmap?) {
imageView.setImageBitmap(result)
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
Click here to download the project code. | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "This example demonstrates how to load an ImageView by URL on Android using kotlin."
},
{
"code": null,
"e": 1274,
"s": 1145,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1339,
"s": 1274,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2256,
"s": 1339,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<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:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"40dp\"\n android:text=\"Load Image From URL in Android ImageView\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@+id/text\"\n android:layout_marginTop=\"5dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2311,
"s": 2256,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3835,
"s": 2311,
"text": "import android.annotation.SuppressLint\nimport android.graphics.Bitmap\nimport android.graphics.BitmapFactory\nimport android.os.AsyncTask\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.util.Log\nimport android.widget.ImageView\nimport android.widget.Toast\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\" DownloadImageFromInternet(findViewById(R.id.imageView)).execute(\"https://images.unsplash.com/photo-1535332371349-a5d229f49cb5?ixlib=rb-1.2.1&w=1000&q=80\")\n }\n @SuppressLint(\"StaticFieldLeak\")\n @Suppress(\"DEPRECATION\")\n private inner class DownloadImageFromInternet(var imageView: ImageView) : AsyncTask<String, Void, Bitmap?>() {\n init {\n Toast.makeText(applicationContext, \"Please wait, it may take a few minute...\", Toast.LENGTH_SHORT).show()\n }\n override fun doInBackground(vararg urls: String): Bitmap? {\n val imageURL = urls[0]\n var image: Bitmap? = null\n try {\n val `in` = java.net.URL(imageURL).openStream()\n image = BitmapFactory.decodeStream(`in`)\n }\n catch (e: Exception) {\n Log.e(\"Error Message\", e.message.toString())\n e.printStackTrace()\n }\n return image\n }\n override fun onPostExecute(result: Bitmap?) {\n imageView.setImageBitmap(result)\n }\n }\n}"
},
{
"code": null,
"e": 3890,
"s": 3835,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4624,
"s": 3890,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n<uses-permission android:name=\"android.permission.INTERNET\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>\n"
},
{
"code": null,
"e": 4973,
"s": 4624,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
},
{
"code": null,
"e": 5014,
"s": 4973,
"text": "Click here to download the project code."
}
]
|
How to Create a Tab Layout in Android App? | This example demonstrates how do I create a Tab Layout in android app.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 – Add the following dependency to create a tab layout −
implementation 'com.android.support:design:28.0.0'
Step 3 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#1db995">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tabLayout"
android:layout_centerInParent="true"
android:layout_marginTop="100dp"
tools:layout_editor_absoluteX="8dp" />
</RelativeLayout>
Step 4 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Football"));
tabLayout.addTab(tabLayout.newTab().setText("Cricket"));
tabLayout.addTab(tabLayout.newTab().setText("NBA"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
Step 5 – Create a java class(MyAdapter.java) and add the following code −
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentManager;
class MyAdapter extends FragmentPagerAdapter {
Context context;
int totalTabs;
public MyAdapter(Context c, FragmentManager fm, int totalTabs) {
super(fm);
context = c;
this.totalTabs = totalTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Football footballFragment = new Football();
return footballFragment;
case 1:
Cricket cricketFragment = new Cricket();
return cricketFragment;
case 2:
NBA nbaFragment = new NBA();
return nbaFragment;
default:
return null;
}
}
@Override
public int getCount() {
return totalTabs;
}
}
Step 6 – Now create the fragments and the layouts (Right click on the project >> New >> Fragment >> Blank −
a) FootBall.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Football extends Fragment {
public Football() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_football, container, false);
}
}
fragment_football.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Football">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:text="Football Fragment"
android:textSize="16sp"
android:textStyle="bold"/>
</FrameLayout>
b) Cricket.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Cricket extends Fragment {
public Cricket() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_cricket, container, false);
}
}
fragment_cricket.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Cricket">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:text="Cricket Fragment"
android:textSize="16sp"
android:textStyle="bold"/>
</FrameLayout>
c) NBA.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class NBA extends Fragment {
public NBA() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_nb, container, false);
}
}
fragment_nba.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NBA">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:text="NBA Fragment"
android:textSize="16sp"
android:textStyle="bold"/>
</FrameLayout>
Step 7 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "This example demonstrates how do I create a Tab Layout in android app."
},
{
"code": null,
"e": 1262,
"s": 1133,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1325,
"s": 1262,
"text": "Step 2 – Add the following dependency to create a tab layout −"
},
{
"code": null,
"e": 1376,
"s": 1325,
"text": "implementation 'com.android.support:design:28.0.0'"
},
{
"code": null,
"e": 1441,
"s": 1376,
"text": "Step 3 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2311,
"s": 1441,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <android.support.design.widget.TabLayout\n android:id=\"@+id/tabLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:background=\"#1db995\">\n </android.support.design.widget.TabLayout>\n <android.support.v4.view.ViewPager\n android:id=\"@+id/viewPager\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/tabLayout\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"100dp\"\n tools:layout_editor_absoluteX=\"8dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2368,
"s": 2311,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3792,
"s": 2368,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.support.design.widget.TabLayout;\nimport android.support.v4.view.ViewPager;\npublic class MainActivity extends AppCompatActivity {\n TabLayout tabLayout;\n ViewPager viewPager;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n tabLayout = findViewById(R.id.tabLayout);\n viewPager = findViewById(R.id.viewPager);\n tabLayout.addTab(tabLayout.newTab().setText(\"Football\"));\n tabLayout.addTab(tabLayout.newTab().setText(\"Cricket\"));\n tabLayout.addTab(tabLayout.newTab().setText(\"NBA\"));\n tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);\n final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(),\n tabLayout.getTabCount());\n viewPager.setAdapter(adapter);\n viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));\n tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {\n @Override\n public void onTabSelected(TabLayout.Tab tab) {\n viewPager.setCurrentItem(tab.getPosition());\n }\n @Override\n public void onTabUnselected(TabLayout.Tab tab) {\n }\n @Override\n public void onTabReselected(TabLayout.Tab tab) {\n }\n });\n }\n}"
},
{
"code": null,
"e": 3866,
"s": 3792,
"text": "Step 5 – Create a java class(MyAdapter.java) and add the following code −"
},
{
"code": null,
"e": 4768,
"s": 3866,
"text": "import android.content.Context;\nimport android.support.v4.app.Fragment;\nimport android.support.v4.app.FragmentPagerAdapter;\nimport android.support.v4.app.FragmentManager;\nclass MyAdapter extends FragmentPagerAdapter {\n Context context;\n int totalTabs;\n public MyAdapter(Context c, FragmentManager fm, int totalTabs) {\n super(fm);\n context = c;\n this.totalTabs = totalTabs;\n }\n @Override\n public Fragment getItem(int position) {\n switch (position) {\n case 0:\n Football footballFragment = new Football();\n return footballFragment;\n case 1:\n Cricket cricketFragment = new Cricket();\n return cricketFragment;\n case 2:\n NBA nbaFragment = new NBA();\n return nbaFragment;\n default:\n return null;\n }\n }\n @Override\n public int getCount() {\n return totalTabs;\n }\n}"
},
{
"code": null,
"e": 4876,
"s": 4768,
"text": "Step 6 – Now create the fragments and the layouts (Right click on the project >> New >> Fragment >> Blank −"
},
{
"code": null,
"e": 4893,
"s": 4876,
"text": "a) FootBall.java"
},
{
"code": null,
"e": 5368,
"s": 4893,
"text": "import android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\npublic class Football extends Fragment {\n public Football() {\n // Required empty public constructor\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n return inflater.inflate(R.layout.fragment_football, container, false);\n }\n}"
},
{
"code": null,
"e": 5390,
"s": 5368,
"text": "fragment_football.xml"
},
{
"code": null,
"e": 5959,
"s": 5390,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout 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 tools:context=\".Football\">\n <!-- TODO: Update blank fragment layout -->\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:textAlignment=\"center\"\n android:text=\"Football Fragment\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"/>\n</FrameLayout>"
},
{
"code": null,
"e": 5975,
"s": 5959,
"text": "b) Cricket.java"
},
{
"code": null,
"e": 6447,
"s": 5975,
"text": "import android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\npublic class Cricket extends Fragment {\n public Cricket() {\n // Required empty public constructor\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n return inflater.inflate(R.layout.fragment_cricket, container, false);\n }\n}"
},
{
"code": null,
"e": 6468,
"s": 6447,
"text": "fragment_cricket.xml"
},
{
"code": null,
"e": 6988,
"s": 6468,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout 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 tools:context=\".Cricket\">\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:textAlignment=\"center\"\n android:text=\"Cricket Fragment\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"/>\n</FrameLayout>"
},
{
"code": null,
"e": 7000,
"s": 6988,
"text": "c) NBA.java"
},
{
"code": null,
"e": 7459,
"s": 7000,
"text": "import android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\npublic class NBA extends Fragment {\n public NBA() {\n // Required empty public constructor\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n return inflater.inflate(R.layout.fragment_nb, container, false);\n }\n}"
},
{
"code": null,
"e": 7476,
"s": 7459,
"text": "fragment_nba.xml"
},
{
"code": null,
"e": 8035,
"s": 7476,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout 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 tools:context=\".NBA\">\n <!-- TODO: Update blank fragment layout -->\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:textAlignment=\"center\"\n android:text=\"NBA Fragment\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"/>\n</FrameLayout>"
},
{
"code": null,
"e": 8090,
"s": 8035,
"text": "Step 7 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 8763,
"s": 8090,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 9110,
"s": 8763,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 9153,
"s": 9112,
"text": "Click here to download the project code."
}
]
|
Explain how L1 Normalization can be implemented using scikit-learn library in Python? | The process of converting a range of values into standardized range of values is known as normalization. These values could be between -1 to +1 or 0 to 1. Data can be normalized with the help of subtraction and division as well.
Data fed to the learning algorithm as input should remain consistent and structured. All features of the input data should be on a single scale to effectively predict the values. But in real-world, data is unstructured, and most of the times, not on the same scale.
This is when normalization comes into picture. It is one of the most important data-preparation process.
It helps in changing values of the columns of the input dataset to fall on a same scale.
During the process of normalization, the range of values are ensured to be non-distorted.
Note − Not all input dataset fed to machine learning algorithms have to be normalized. Normalization is required only when features in a dataset have completely different scale of values.
There are different kinds of normalization −
Min-Max normalization
Z Normalization
Unit Vector Normalization
Let us understand how L1 normalization works.
Also known as Least Absolute Deviations, it changes the data such that the sum of the absolute values remains as 1 in every row.
Let us see how L1 Normalization can be implemented using scikit learn in Python −
import numpy as np
from sklearn import preprocessing
input_data = np.array(
[[34.78, 31.9, -65.5],[-16.5, 2.45, -83.5],[0.5, -87.98, 45.62],[5.9, 2.38, -55.82]]
)
data_normalized_l1 = preprocessing.normalize(input_data, norm='l1')
print("\nL1 normalized data is \n", data_normalized_l1)
L1 normalized data is
[[ 0.26312604 0.24133757 -0.49553639]
[-0.16105417 0.0239141 -0.81503172]
[ 0.00372856 -0.65607755 0.34019389]
[ 0.09204368 0.03712949 -0.87082683]]
The required packages are imported.
The required packages are imported.
The input data is generated using the Numpy library.
The input data is generated using the Numpy library.
The ‘normalize’ function present in the class ‘preprocessing‘ is used to normalize the data.
The ‘normalize’ function present in the class ‘preprocessing‘ is used to normalize the data.
The type of normalization is specified as ‘l1’.
The type of normalization is specified as ‘l1’.
This way, any data in the array gets normalized and the sum of every row would be 1 only.
This way, any data in the array gets normalized and the sum of every row would be 1 only.
This normalized data is displayed on the console.
This normalized data is displayed on the console. | [
{
"code": null,
"e": 1291,
"s": 1062,
"text": "The process of converting a range of values into standardized range of values is known as normalization. These values could be between -1 to +1 or 0 to 1. Data can be normalized with the help of subtraction and division as well."
},
{
"code": null,
"e": 1557,
"s": 1291,
"text": "Data fed to the learning algorithm as input should remain consistent and structured. All features of the input data should be on a single scale to effectively predict the values. But in real-world, data is unstructured, and most of the times, not on the same scale."
},
{
"code": null,
"e": 1662,
"s": 1557,
"text": "This is when normalization comes into picture. It is one of the most important data-preparation process."
},
{
"code": null,
"e": 1751,
"s": 1662,
"text": "It helps in changing values of the columns of the input dataset to fall on a same scale."
},
{
"code": null,
"e": 1841,
"s": 1751,
"text": "During the process of normalization, the range of values are ensured to be non-distorted."
},
{
"code": null,
"e": 2029,
"s": 1841,
"text": "Note − Not all input dataset fed to machine learning algorithms have to be normalized. Normalization is required only when features in a dataset have completely different scale of values."
},
{
"code": null,
"e": 2074,
"s": 2029,
"text": "There are different kinds of normalization −"
},
{
"code": null,
"e": 2096,
"s": 2074,
"text": "Min-Max normalization"
},
{
"code": null,
"e": 2112,
"s": 2096,
"text": "Z Normalization"
},
{
"code": null,
"e": 2138,
"s": 2112,
"text": "Unit Vector Normalization"
},
{
"code": null,
"e": 2184,
"s": 2138,
"text": "Let us understand how L1 normalization works."
},
{
"code": null,
"e": 2313,
"s": 2184,
"text": "Also known as Least Absolute Deviations, it changes the data such that the sum of the absolute values remains as 1 in every row."
},
{
"code": null,
"e": 2395,
"s": 2313,
"text": "Let us see how L1 Normalization can be implemented using scikit learn in Python −"
},
{
"code": null,
"e": 2685,
"s": 2395,
"text": "import numpy as np\nfrom sklearn import preprocessing\ninput_data = np.array(\n [[34.78, 31.9, -65.5],[-16.5, 2.45, -83.5],[0.5, -87.98, 45.62],[5.9, 2.38, -55.82]]\n)\ndata_normalized_l1 = preprocessing.normalize(input_data, norm='l1')\nprint(\"\\nL1 normalized data is \\n\", data_normalized_l1)"
},
{
"code": null,
"e": 2856,
"s": 2685,
"text": "L1 normalized data is\n[[ 0.26312604 0.24133757 -0.49553639]\n[-0.16105417 0.0239141 -0.81503172]\n[ 0.00372856 -0.65607755 0.34019389]\n[ 0.09204368 0.03712949 -0.87082683]]"
},
{
"code": null,
"e": 2892,
"s": 2856,
"text": "The required packages are imported."
},
{
"code": null,
"e": 2928,
"s": 2892,
"text": "The required packages are imported."
},
{
"code": null,
"e": 2981,
"s": 2928,
"text": "The input data is generated using the Numpy library."
},
{
"code": null,
"e": 3034,
"s": 2981,
"text": "The input data is generated using the Numpy library."
},
{
"code": null,
"e": 3127,
"s": 3034,
"text": "The ‘normalize’ function present in the class ‘preprocessing‘ is used to normalize the data."
},
{
"code": null,
"e": 3220,
"s": 3127,
"text": "The ‘normalize’ function present in the class ‘preprocessing‘ is used to normalize the data."
},
{
"code": null,
"e": 3268,
"s": 3220,
"text": "The type of normalization is specified as ‘l1’."
},
{
"code": null,
"e": 3316,
"s": 3268,
"text": "The type of normalization is specified as ‘l1’."
},
{
"code": null,
"e": 3406,
"s": 3316,
"text": "This way, any data in the array gets normalized and the sum of every row would be 1 only."
},
{
"code": null,
"e": 3496,
"s": 3406,
"text": "This way, any data in the array gets normalized and the sum of every row would be 1 only."
},
{
"code": null,
"e": 3546,
"s": 3496,
"text": "This normalized data is displayed on the console."
},
{
"code": null,
"e": 3596,
"s": 3546,
"text": "This normalized data is displayed on the console."
}
]
|
Find largest document size in MongoDB? | To find the largest document size in MongoDB, you need to write a script in the shell.
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.largestDocumentDemo.insertOne({"StudentName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ed2e32f684a30fbdfd57d")
}
> db.largestDocumentDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentCountryName":"US","TechnicalSubject":["C","C++","Java","MySQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ed3282f684a30fbdfd57e")
}
> db.largestDocumentDemo.insertOne({"StudentName":"Mike","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ed3382f684a30fbdfd57f")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.largestDocumentDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8ed2e32f684a30fbdfd57d"), "StudentName" : "John" }
{
"_id" : ObjectId("5c8ed3282f684a30fbdfd57e"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentCountryName" : "US",
"TechnicalSubject" : [
"C",
"C++",
"Java",
"MySQL"
]
}
{
"_id" : ObjectId("5c8ed3382f684a30fbdfd57f"),
"StudentName" : "Mike",
"StudentAge" : 22
}
Here is the query to find the largest document size in MongoDB −
> var largestDocumentSize = 0;
> db.largestDocumentDemo.find().forEach(function(myObject) {
... var currentDocumentSize = Object.bsonsize(myObject);
... if(largestDocumentSize < currentDocumentSize ) {
... largestDocumentSize = currentDocumentSize ;
... }
... });
> print('The Largest Document Size =' + ' ' +largestDocumentSize);
The following is the output displaying the largest document size −
The Largest Document Size = 160 | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To find the largest document size in MongoDB, you need to write a script in the shell."
},
{
"code": null,
"e": 1287,
"s": 1149,
"text": "To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 1827,
"s": 1287,
"text": "> db.largestDocumentDemo.insertOne({\"StudentName\":\"John\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ed2e32f684a30fbdfd57d\")\n}\n> db.largestDocumentDemo.insertOne({\"StudentName\":\"Carol\",\"StudentAge\":22,\"StudentCountryName\":\"US\",\"TechnicalSubject\":[\"C\",\"C++\",\"Java\",\"MySQL\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ed3282f684a30fbdfd57e\")\n}\n> db.largestDocumentDemo.insertOne({\"StudentName\":\"Mike\",\"StudentAge\":22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ed3382f684a30fbdfd57f\")\n}"
},
{
"code": null,
"e": 1925,
"s": 1827,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 1967,
"s": 1925,
"text": "> db.largestDocumentDemo.find().pretty();"
},
{
"code": null,
"e": 1997,
"s": 1967,
"text": "The following is the output −"
},
{
"code": null,
"e": 2389,
"s": 1997,
"text": "{ \"_id\" : ObjectId(\"5c8ed2e32f684a30fbdfd57d\"), \"StudentName\" : \"John\" }\n{\n \"_id\" : ObjectId(\"5c8ed3282f684a30fbdfd57e\"),\n \"StudentName\" : \"Carol\",\n \"StudentAge\" : 22,\n \"StudentCountryName\" : \"US\",\n \"TechnicalSubject\" : [\n \"C\",\n \"C++\",\n \"Java\",\n \"MySQL\"\n ]\n}\n{\n \"_id\" : ObjectId(\"5c8ed3382f684a30fbdfd57f\"),\n \"StudentName\" : \"Mike\",\n \"StudentAge\" : 22\n}"
},
{
"code": null,
"e": 2454,
"s": 2389,
"text": "Here is the query to find the largest document size in MongoDB −"
},
{
"code": null,
"e": 2800,
"s": 2454,
"text": "> var largestDocumentSize = 0;\n> db.largestDocumentDemo.find().forEach(function(myObject) {\n ... var currentDocumentSize = Object.bsonsize(myObject);\n ... if(largestDocumentSize < currentDocumentSize ) {\n ... largestDocumentSize = currentDocumentSize ;\n ... }\n... });\n> print('The Largest Document Size =' + ' ' +largestDocumentSize);"
},
{
"code": null,
"e": 2867,
"s": 2800,
"text": "The following is the output displaying the largest document size −"
},
{
"code": null,
"e": 2899,
"s": 2867,
"text": "The Largest Document Size = 160"
}
]
|
Building a Rock Paper Scissors AI using Tensorflow and OpenCV with Python | by Manas Acharya | Towards Data Science | Code for this project can be found at my Github
github.com
The basis of this project was to experiment with Deep Learning and Image Classification with the aim of building a simple yet fun iteration of the infamous Rock Paper Scissors game. I’d like to start off by saying this project is a product of my boredom through the COVID19 Quarantine Period in May, hopefully, by the time you’re reading this, things are back to normal. Through the course of this explanation, my aim is to explain the fundamentals of this project in simple terms aimed towards beginners. So let's begin...
While building any sort of Deep Learning application there are 3 major steps :
1. Collecting and Processing Data
2. Building a suitable AI Model
3. Deployment for use
The entire project refers to and goes hand in hand with my Github repo so do keep this ready for reference.
The basis of any Deep Learning model is DATA. Any Machine Learning Engineer would agree that in ML the data is far more crucial than the algorithm itself. We need to collect images for the symbols Rock, Paper and Scissor. Instead of downloading somebody else’s data and training on it, I made my own dataset and encourage you to build your own too. Later on try changing the data and re-training the model to see the grave impact data has on a Deep Learning model.
I have used Python’s OpenCV library for all camera related operations. So label here refers to what class the image belongs too ie. RPS and depending on the label the image is saved in the appropriate directory. ct and maxCt refers to the start and final index to save images with. Remaining is standard OpenCV code to get webcam feed and save images to a directory. A key point to note is that all my images are of 300 x 300 dimensions. After running this my directory tree looks like this.
C:.├───paper │ paper0.jpg │ paper1.jpg │ paper2.jpg│├───rock │ rock0.jpg │ rock1.jpg │ rock2.jpg│└───scissor scissor0.jpg scissor1.jpg scissor2.jpg
If you are referring the Github repo getData.py does the job for you !!
A computer understands numbers and we have images at our disposal. Thus, we will convert all the images into their respective vector representations. Also, our labels are yet to be generated and as established labels can’t be text, so I’ve manually built One-Hot-Encoded representations for each class using the shape_to_label dictionary.
As we have saved our images in directories based on their classes the directory name serves as the label which is converted to One-Hot representation using the shape_to_label dictionary. Following that we iterate over the files in our system to access images, the cv2.imread() function returns a vector representation of image. We do some manual Data Augmentation by flipping the image and zooming into it. This increases our dataset size without having the need to take new photos. Data Augmentation is a crucial part to generating datasets. Finally the images and labels are stored in separate numpy arrays.
More on Data Augmentation here.
When it comes to working with image data there are many pre-trained models available that have been trained on datasets with thousands of labels that are available at our disposal thanks to Tensorflow and Keras distributions of these models via their applications api. This makes including these pre-trained models in our applications seem like a breeze!
In a gist, Transfer learning takes a pre-trained model and does not include its final layers that make the final prediction thereby leaving us with the powerful part of the model that can distinguish features in images for this case and pass this information to our own Dense Neural Network.
Why not train your own model? Its totally up to you!! However using transfer learning can at many times make your progress a lot faster, in a sense you’re avoiding re-inventing the wheel.
Some other popular pre-trained models:
InceptionV3
VGG16/19
ResNet
MobileNet
Here’s an interesting article on Transfer Learning!
Note : Whenever we work with image data the use of Data Convolutional Neural Layers is almost a given. The transfer Learning model used here has these layers. For more info on CNNs visit.
I’ve used the DenseNet121 model for feature extraction whose outputs will eventually be entered in my own Dense Neural Network.
Key Points :
As our images are 300x300 the input shape specified is the same. The additional 3 stands for the RGB layers, so this layer has enough neurons to process the entire image.
We’ve used the DenseNet layer as our base/first layer followed by our own Dense Neural Network.
I’ve set the trainable parameter to True which will retrain the weights of the DenseNet too. This gave me better results though twas quite time consuming. I’d suggest that in your own implementations try different iterations by changing such parameters also know as hyperparameters.
As we have 3 classes Rock-Paper-Scissor the final layer is a Dense layer with 3 neurons and softmax activation.
This final layer returns the probability of the image belonging to a particular class among the 3 classes.
If you’re referring the GitHub repo train.py takes care of Data Preparation and model training!
By this point, we have gathered our data, built and trained our model. The only part left is deployment using OpenCV.
The flow for this implementation is simple:
Start webcam feed and read each frame
Pass this frame to model for classification ie. predict class
Make a random move by computer
Calculate Score
Above snippet contains the rather important blocks of code, remaining part is just making the game user-friendly, RPS rules and scoring.
So we begin with loading our trained model. Next comes a stone age for-loop implementation that shows a countdown before beginning the prediction part of the program. After prediction the scores are updated based on the players moves.
We explicitly draw a target zone using cv2.rectangle(). Only this part of the frame is passed to the model for predictions after it is pre-processed using the prepImg() function.
The entire play.py code is available here on my repo.
We’ve successfully implemented and understood the workings of this project. So go ahead and fork my implementation and experiment with it. A major improvement would probably be adding hand detection so we don’t need to explicitly draw a target zone and model would first detect hand position then make a prediction. I’ve tried to keep my language as beginner-friendly as possible if you still have any questions do comment. I encourage you to improve the project and send me your suggestions. Excelsior! | [
{
"code": null,
"e": 220,
"s": 172,
"text": "Code for this project can be found at my Github"
},
{
"code": null,
"e": 231,
"s": 220,
"text": "github.com"
},
{
"code": null,
"e": 755,
"s": 231,
"text": "The basis of this project was to experiment with Deep Learning and Image Classification with the aim of building a simple yet fun iteration of the infamous Rock Paper Scissors game. I’d like to start off by saying this project is a product of my boredom through the COVID19 Quarantine Period in May, hopefully, by the time you’re reading this, things are back to normal. Through the course of this explanation, my aim is to explain the fundamentals of this project in simple terms aimed towards beginners. So let's begin..."
},
{
"code": null,
"e": 834,
"s": 755,
"text": "While building any sort of Deep Learning application there are 3 major steps :"
},
{
"code": null,
"e": 868,
"s": 834,
"text": "1. Collecting and Processing Data"
},
{
"code": null,
"e": 900,
"s": 868,
"text": "2. Building a suitable AI Model"
},
{
"code": null,
"e": 922,
"s": 900,
"text": "3. Deployment for use"
},
{
"code": null,
"e": 1030,
"s": 922,
"text": "The entire project refers to and goes hand in hand with my Github repo so do keep this ready for reference."
},
{
"code": null,
"e": 1495,
"s": 1030,
"text": "The basis of any Deep Learning model is DATA. Any Machine Learning Engineer would agree that in ML the data is far more crucial than the algorithm itself. We need to collect images for the symbols Rock, Paper and Scissor. Instead of downloading somebody else’s data and training on it, I made my own dataset and encourage you to build your own too. Later on try changing the data and re-training the model to see the grave impact data has on a Deep Learning model."
},
{
"code": null,
"e": 1987,
"s": 1495,
"text": "I have used Python’s OpenCV library for all camera related operations. So label here refers to what class the image belongs too ie. RPS and depending on the label the image is saved in the appropriate directory. ct and maxCt refers to the start and final index to save images with. Remaining is standard OpenCV code to get webcam feed and save images to a directory. A key point to note is that all my images are of 300 x 300 dimensions. After running this my directory tree looks like this."
},
{
"code": null,
"e": 2165,
"s": 1987,
"text": "C:.├───paper │ paper0.jpg │ paper1.jpg │ paper2.jpg│├───rock │ rock0.jpg │ rock1.jpg │ rock2.jpg│└───scissor scissor0.jpg scissor1.jpg scissor2.jpg"
},
{
"code": null,
"e": 2237,
"s": 2165,
"text": "If you are referring the Github repo getData.py does the job for you !!"
},
{
"code": null,
"e": 2576,
"s": 2237,
"text": "A computer understands numbers and we have images at our disposal. Thus, we will convert all the images into their respective vector representations. Also, our labels are yet to be generated and as established labels can’t be text, so I’ve manually built One-Hot-Encoded representations for each class using the shape_to_label dictionary."
},
{
"code": null,
"e": 3186,
"s": 2576,
"text": "As we have saved our images in directories based on their classes the directory name serves as the label which is converted to One-Hot representation using the shape_to_label dictionary. Following that we iterate over the files in our system to access images, the cv2.imread() function returns a vector representation of image. We do some manual Data Augmentation by flipping the image and zooming into it. This increases our dataset size without having the need to take new photos. Data Augmentation is a crucial part to generating datasets. Finally the images and labels are stored in separate numpy arrays."
},
{
"code": null,
"e": 3218,
"s": 3186,
"text": "More on Data Augmentation here."
},
{
"code": null,
"e": 3573,
"s": 3218,
"text": "When it comes to working with image data there are many pre-trained models available that have been trained on datasets with thousands of labels that are available at our disposal thanks to Tensorflow and Keras distributions of these models via their applications api. This makes including these pre-trained models in our applications seem like a breeze!"
},
{
"code": null,
"e": 3865,
"s": 3573,
"text": "In a gist, Transfer learning takes a pre-trained model and does not include its final layers that make the final prediction thereby leaving us with the powerful part of the model that can distinguish features in images for this case and pass this information to our own Dense Neural Network."
},
{
"code": null,
"e": 4053,
"s": 3865,
"text": "Why not train your own model? Its totally up to you!! However using transfer learning can at many times make your progress a lot faster, in a sense you’re avoiding re-inventing the wheel."
},
{
"code": null,
"e": 4092,
"s": 4053,
"text": "Some other popular pre-trained models:"
},
{
"code": null,
"e": 4104,
"s": 4092,
"text": "InceptionV3"
},
{
"code": null,
"e": 4113,
"s": 4104,
"text": "VGG16/19"
},
{
"code": null,
"e": 4120,
"s": 4113,
"text": "ResNet"
},
{
"code": null,
"e": 4130,
"s": 4120,
"text": "MobileNet"
},
{
"code": null,
"e": 4182,
"s": 4130,
"text": "Here’s an interesting article on Transfer Learning!"
},
{
"code": null,
"e": 4370,
"s": 4182,
"text": "Note : Whenever we work with image data the use of Data Convolutional Neural Layers is almost a given. The transfer Learning model used here has these layers. For more info on CNNs visit."
},
{
"code": null,
"e": 4498,
"s": 4370,
"text": "I’ve used the DenseNet121 model for feature extraction whose outputs will eventually be entered in my own Dense Neural Network."
},
{
"code": null,
"e": 4511,
"s": 4498,
"text": "Key Points :"
},
{
"code": null,
"e": 4682,
"s": 4511,
"text": "As our images are 300x300 the input shape specified is the same. The additional 3 stands for the RGB layers, so this layer has enough neurons to process the entire image."
},
{
"code": null,
"e": 4778,
"s": 4682,
"text": "We’ve used the DenseNet layer as our base/first layer followed by our own Dense Neural Network."
},
{
"code": null,
"e": 5061,
"s": 4778,
"text": "I’ve set the trainable parameter to True which will retrain the weights of the DenseNet too. This gave me better results though twas quite time consuming. I’d suggest that in your own implementations try different iterations by changing such parameters also know as hyperparameters."
},
{
"code": null,
"e": 5173,
"s": 5061,
"text": "As we have 3 classes Rock-Paper-Scissor the final layer is a Dense layer with 3 neurons and softmax activation."
},
{
"code": null,
"e": 5280,
"s": 5173,
"text": "This final layer returns the probability of the image belonging to a particular class among the 3 classes."
},
{
"code": null,
"e": 5376,
"s": 5280,
"text": "If you’re referring the GitHub repo train.py takes care of Data Preparation and model training!"
},
{
"code": null,
"e": 5494,
"s": 5376,
"text": "By this point, we have gathered our data, built and trained our model. The only part left is deployment using OpenCV."
},
{
"code": null,
"e": 5538,
"s": 5494,
"text": "The flow for this implementation is simple:"
},
{
"code": null,
"e": 5576,
"s": 5538,
"text": "Start webcam feed and read each frame"
},
{
"code": null,
"e": 5638,
"s": 5576,
"text": "Pass this frame to model for classification ie. predict class"
},
{
"code": null,
"e": 5669,
"s": 5638,
"text": "Make a random move by computer"
},
{
"code": null,
"e": 5685,
"s": 5669,
"text": "Calculate Score"
},
{
"code": null,
"e": 5822,
"s": 5685,
"text": "Above snippet contains the rather important blocks of code, remaining part is just making the game user-friendly, RPS rules and scoring."
},
{
"code": null,
"e": 6057,
"s": 5822,
"text": "So we begin with loading our trained model. Next comes a stone age for-loop implementation that shows a countdown before beginning the prediction part of the program. After prediction the scores are updated based on the players moves."
},
{
"code": null,
"e": 6236,
"s": 6057,
"text": "We explicitly draw a target zone using cv2.rectangle(). Only this part of the frame is passed to the model for predictions after it is pre-processed using the prepImg() function."
},
{
"code": null,
"e": 6290,
"s": 6236,
"text": "The entire play.py code is available here on my repo."
}
]
|
C# Program to Print the Employees Whose Salary is Between 6000 and 8000 Using LINQ - GeeksforGeeks | 18 Oct, 2021
LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will get the employee details whose salary is between 6000 and 8000 using LINQ.
Example:
Input:
List of employees:
{{emp_id = 101, emp_name = "bobby", emp_age = 12, emp_salary = 2000}}
Output:
No Output
Input:
List of employees:
{{emp_id = 101, emp_name = "bobby", emp_age = 12, emp_salary = 8900},
{emp_id = 102, emp_name = "deepu", emp_age = 15, emp_salary = 7000},
{emp_id = 103, emp_name = "manoja", emp_age = 13, emp_salary = 6700}}
Output:
{{emp_id = 102, emp_name = "deepu", emp_age = 15, emp_salary = 7000},
{emp_id = 103, emp_name = "manoja", emp_age = 13, emp_salary = 6700}}
Approach:
To display the employee details whose salary is between 6000 and 8000 follow the following approach:
Create a list of employees with four variables (Id, name, department, and salary)Iterate through the employee details by using where function and get the employee details by choosing employee salary between 6000 and 8000.Select the details which are between 6000 and 8000Call the ToString methodDisplay the employee details
Create a list of employees with four variables (Id, name, department, and salary)
Iterate through the employee details by using where function and get the employee details by choosing employee salary between 6000 and 8000.
Select the details which are between 6000 and 8000
Call the ToString method
Display the employee details
Example:
C#
// C# program to display the details of the employee's// whose salary is between 6000 and 8000 // using LINQ.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class Employee{ // Declare 4 variables - id,age, name and salaryint emp_id; string emp_dept;string emp_name;int emp_salary; // Get the to string method that returns id,// name, age and salarypublic override string ToString(){ return emp_id + " " + emp_name + " " + emp_dept + " " + emp_salary;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Employee> emp = new List<Employee>() { // Create 3 employee details new Employee{ emp_id = 101, emp_name = "bobby", emp_dept = "HR", emp_salary = 8900 }, new Employee{ emp_id = 102, emp_name = "deepu", emp_dept = "Development", emp_salary = 7000 }, new Employee{ emp_id = 103, emp_name = "manoja", emp_dept = "HR", emp_salary = 6700 }}; // Iterate the Employee by selecting Employee id // greater than 101 using where function IEnumerable<Employee> Query = from employee in emp where employee.emp_salary >= 6000 && employee.emp_salary <= 8000 select employee; // Display employee details Console.WriteLine("ID Name Department Salary"); Console.WriteLine("+++++++++++++++++++++++++++"); foreach (Employee e in Query) { // Call the to string method Console.WriteLine(e.ToString()); }}}
Output:
ID Name Department Salary
+++++++++++++++++++++++++++
102 deepu Development 7000
103 manoja HR 6700
CSharp LINQ
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 24740,
"s": 24302,
"text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will get the employee details whose salary is between 6000 and 8000 using LINQ."
},
{
"code": null,
"e": 24749,
"s": 24740,
"text": "Example:"
},
{
"code": null,
"e": 25292,
"s": 24749,
"text": "Input:\nList of employees:\n {{emp_id = 101, emp_name = \"bobby\", emp_age = 12, emp_salary = 2000}}\nOutput:\nNo Output\n \nInput:\nList of employees:\n {{emp_id = 101, emp_name = \"bobby\", emp_age = 12, emp_salary = 8900},\n {emp_id = 102, emp_name = \"deepu\", emp_age = 15, emp_salary = 7000},\n {emp_id = 103, emp_name = \"manoja\", emp_age = 13, emp_salary = 6700}}\nOutput:\n {{emp_id = 102, emp_name = \"deepu\", emp_age = 15, emp_salary = 7000},\n {emp_id = 103, emp_name = \"manoja\", emp_age = 13, emp_salary = 6700}}"
},
{
"code": null,
"e": 25302,
"s": 25292,
"text": "Approach:"
},
{
"code": null,
"e": 25403,
"s": 25302,
"text": "To display the employee details whose salary is between 6000 and 8000 follow the following approach:"
},
{
"code": null,
"e": 25727,
"s": 25403,
"text": "Create a list of employees with four variables (Id, name, department, and salary)Iterate through the employee details by using where function and get the employee details by choosing employee salary between 6000 and 8000.Select the details which are between 6000 and 8000Call the ToString methodDisplay the employee details"
},
{
"code": null,
"e": 25809,
"s": 25727,
"text": "Create a list of employees with four variables (Id, name, department, and salary)"
},
{
"code": null,
"e": 25950,
"s": 25809,
"text": "Iterate through the employee details by using where function and get the employee details by choosing employee salary between 6000 and 8000."
},
{
"code": null,
"e": 26001,
"s": 25950,
"text": "Select the details which are between 6000 and 8000"
},
{
"code": null,
"e": 26026,
"s": 26001,
"text": "Call the ToString method"
},
{
"code": null,
"e": 26055,
"s": 26026,
"text": "Display the employee details"
},
{
"code": null,
"e": 26064,
"s": 26055,
"text": "Example:"
},
{
"code": null,
"e": 26067,
"s": 26064,
"text": "C#"
},
{
"code": "// C# program to display the details of the employee's// whose salary is between 6000 and 8000 // using LINQ.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class Employee{ // Declare 4 variables - id,age, name and salaryint emp_id; string emp_dept;string emp_name;int emp_salary; // Get the to string method that returns id,// name, age and salarypublic override string ToString(){ return emp_id + \" \" + emp_name + \" \" + emp_dept + \" \" + emp_salary;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Employee> emp = new List<Employee>() { // Create 3 employee details new Employee{ emp_id = 101, emp_name = \"bobby\", emp_dept = \"HR\", emp_salary = 8900 }, new Employee{ emp_id = 102, emp_name = \"deepu\", emp_dept = \"Development\", emp_salary = 7000 }, new Employee{ emp_id = 103, emp_name = \"manoja\", emp_dept = \"HR\", emp_salary = 6700 }}; // Iterate the Employee by selecting Employee id // greater than 101 using where function IEnumerable<Employee> Query = from employee in emp where employee.emp_salary >= 6000 && employee.emp_salary <= 8000 select employee; // Display employee details Console.WriteLine(\"ID Name Department Salary\"); Console.WriteLine(\"+++++++++++++++++++++++++++\"); foreach (Employee e in Query) { // Call the to string method Console.WriteLine(e.ToString()); }}}",
"e": 27675,
"s": 26067,
"text": null
},
{
"code": null,
"e": 27683,
"s": 27675,
"text": "Output:"
},
{
"code": null,
"e": 27785,
"s": 27683,
"text": "ID Name Department Salary\n+++++++++++++++++++++++++++\n102 deepu Development 7000\n103 manoja HR 6700"
},
{
"code": null,
"e": 27797,
"s": 27785,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 27813,
"s": 27797,
"text": "CSharp-programs"
},
{
"code": null,
"e": 27820,
"s": 27813,
"text": "Picked"
},
{
"code": null,
"e": 27823,
"s": 27820,
"text": "C#"
},
{
"code": null,
"e": 27921,
"s": 27823,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27939,
"s": 27921,
"text": "Destructors in C#"
},
{
"code": null,
"e": 27962,
"s": 27939,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27990,
"s": 27962,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28030,
"s": 27990,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28073,
"s": 28030,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28095,
"s": 28073,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28112,
"s": 28095,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28128,
"s": 28112,
"text": "C# | List Class"
},
{
"code": null,
"e": 28178,
"s": 28128,
"text": "Difference between Hashtable and Dictionary in C#"
}
]
|
Natural Language Processing (NLP) for Beginners | by Behic Guven | Towards Data Science | In this post, I will introduce you to one of the most known artificial intelligence field called Natural Language Processing. After the introduction, I will walk you through a hands-on exercise where we will extract some valuable information from a specific website. For the hands-on project, we will use a specific NLP module called NLTK (Natural Language Toolkit), which will be covered after the introduction section. After reading this article, you will have a better understanding of natural language processing applications and how they work. Without losing any time, let’s get started!
Introduction
NLTK (Natural Language Toolkit)
BS4 (Beautiful Soup 4)
Step 1 — Import Libraries
Step 2— Reading the Page
Step 3— Data Cleaning
Step 4— Tokenization
Step 5— Data Visualization
Video Demonstration
Natural language refers to the language we use in our daily life. This field has been around for a long time, but artificial intelligence connected research about this field has increased with the growth of computer science and programming. The internet has changed the way we live, and how we communicate with each other. For example, instead of sending paper mails and letters, we started using text messages, emails, voice messages, etc. You can learn more about this field by doing some research online.
To give you a better understanding of how Natural Language Processing is being used in machine learning and artificial intelligence fields, I would like to share some real-life applications with you:
Google Translate: The machine intelligence behind Google Translate understands the words and translates them word by word to the language you want. And it does the translation without losing the meaning of the sentence.
Grammarly: The machine intelligence behind this service is good with grammar and words. It is a great example of how language processing has evolved in the last couple of years. It checks the grammar of the sentences, and it even gives some recommendations on how to increase the quality of the article.
Voice Assistants: This field is also in most of the areas where language processing has improved a lot. Mainly speech recognition technology is being used with the processing of words. Currently, the most known ones are Apple Siri, Google Assistant, and Amazon Alexa.
Chatbots: Another great example of language processing is chatbots. They are very much like virtual assistants but with more specific goals. They are most commonly used on websites where customers visit. They help you to get the information you need without talking to any real person. First, they try to understand your need and then bring the results in front of you.
Web Scraping: Web scraping is another field where language processing is commonly used. It is used to extract information from a web page without even spending time to copy each paragraph one by one. Web scraping is a great way to collect valuable data and train your machine learning model. Web scraping is also a very helpful tool when working with search engine optimization.
NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning, wrappers for industrial-strength NLP libraries.
Reference: http://www.nltk.org
We have to install NLTK module so that we can use it in our project. Running the following line in your terminal will do the installation for you:
pip install nltk
Beautiful Soup is a Python library for getting data out of HTML, XML, and other markup languages. Beautiful Soup helps you pull particular content from a webpage, remove the HTML markup, and save the information. It is a tool for web scraping that helps you clean up and parse the documents you have pulled down from the web.
Reference: https://programminghistorian.org/en/lessons/intro-to-beautiful-soup
Now, let’s install the latest edition of the beautiful soup library using pip:
pip install beautifulsoup4
After the installation of the libraries is completed, we can start working on the programming. For this project, I will be using Jupyter Notebook. Ok, first thing first, let’s import the libraries into the notebook.
import nltkfrom nltk.corpus import stopwordsfrom bs4 import BeautifulSoupimport urllib.requestimport plotly.io as pio
In this step, we will open the webpage using the urllib request method. After opening it, we will read the whole code of the webpage. As you know, the webpages have a code running in the background. You can right-click on any webpage and click on the ‘inspect element’ to have some idea of the code.
I chose the wikipedia page about Natural Language Processing.
page = urllib.request.urlopen('https://en.wikipedia.org/wiki/Natural_language_processing')html_plain = page.read()print(html_plain)
This is how it looks like when we print the plain html code:
As you can see from the screenshot, the plain html code needs some cleaning. BeautifulSoup will help us in this data cleaning process. We have to get rid of lots of unnecessary characters such as double quotes, slashes, bigger than and smaller than signs, and many more. Don’t worry, it also cleans the HTML syntax words 😊
Let’s see the magical power of BS4 (Beautiful Soup 4) after running the following lines:
soup = BeautifulSoup(html_plain,'html.parser')soup_text = soup.get_text(strip = True)
Great! One more thing before we move to split the words: to increase the quality of the processing I recommend lower casing all the characters. It will be helpful when we start counting the frequency of words. Otherwise, the machine will see “Natural” and “natural” as different words due to their different Ascii values.
ready_text = soup_text.lower()print(ready_text)
Looks much better! Now, let’s move to the next step where will be splitting each word into a list item. This process is known as Tokenization.
This step is crucial when working on a natural language processing project. First, we will tokenize each word by splitting them into list items. After that, we will do some word cleaning. NLTK (Natural Language Toolkit) will use to clean the stop words. This will leave us with the keywords which give us a better idea about the page. This way we don’t count the stop words, such as a, and, of, that, the, with, etc.
tokens = []for t in ready_text.split(): tokens.append(t)print(tokens)
#Run this line if you get an error message in the next code blocknltk.download()
Now, let’s clean the stop words in our tokens list.
stop_words = stopwords.words('english')clean_tokens = tokens[:]for token in tokens: if token in stop_words: clean_tokens.remove(token)print(clean_tokens)
In this step, firstly we will count the frequency of the tokens and then we will filter the high-frequency ones. After filtering, it’s time to visualize the most frequently used words in the natural language processing Wikipedia page. Visualization will help us to see them in order with their frequency.
Let’s calculate the frequency of words using FreqDist function by NLTK.
freq = nltk.FreqDist(clean_tokens)for key, val in freq.items(): print('Word: ' + str(key) + ', Quantity:' + str(val))
Now, we will define a new dictionary and get the tokens that has been used more than 10 times in the page. These keywords are more valuable than others:
high_freq = dict()for key, val in freq.items(): if (val > 10): high_freq[key] = val
Perfect! Now we have a new dictionary called high_freq. Let’s move to the final step and create a bar chart. I think a bar chart will work better with quantitative data representation. I’ve also sorted by descending order so that the word with highest frequency comes first. Here is the visualization code:
#Note: to pass keys and values of high_freq dictionary, I had to convert them to list when passing themfig = dict({ "data": [{"type": "bar", "x": list(high_freq.keys()), "y": list(high_freq.values())}], "layout": {"title": {"text": "Most frequently used words in the page"}, "xaxis": {"categoryorder":"total descending"}}})pio.show(fig)
Congrats!! You have created a program that detects the keywords inside a page. Now, without reading the whole page you can still have an idea about the page using natural language processing. Hoping that you enjoyed reading this hands-on guide. I would be glad if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. Feel free to contact me if you have any questions while implementing the code.
Follow my blog and youtube channel to stay inspired. Thank you, | [
{
"code": null,
"e": 764,
"s": 171,
"text": "In this post, I will introduce you to one of the most known artificial intelligence field called Natural Language Processing. After the introduction, I will walk you through a hands-on exercise where we will extract some valuable information from a specific website. For the hands-on project, we will use a specific NLP module called NLTK (Natural Language Toolkit), which will be covered after the introduction section. After reading this article, you will have a better understanding of natural language processing applications and how they work. Without losing any time, let’s get started!"
},
{
"code": null,
"e": 777,
"s": 764,
"text": "Introduction"
},
{
"code": null,
"e": 809,
"s": 777,
"text": "NLTK (Natural Language Toolkit)"
},
{
"code": null,
"e": 832,
"s": 809,
"text": "BS4 (Beautiful Soup 4)"
},
{
"code": null,
"e": 858,
"s": 832,
"text": "Step 1 — Import Libraries"
},
{
"code": null,
"e": 883,
"s": 858,
"text": "Step 2— Reading the Page"
},
{
"code": null,
"e": 905,
"s": 883,
"text": "Step 3— Data Cleaning"
},
{
"code": null,
"e": 926,
"s": 905,
"text": "Step 4— Tokenization"
},
{
"code": null,
"e": 953,
"s": 926,
"text": "Step 5— Data Visualization"
},
{
"code": null,
"e": 973,
"s": 953,
"text": "Video Demonstration"
},
{
"code": null,
"e": 1481,
"s": 973,
"text": "Natural language refers to the language we use in our daily life. This field has been around for a long time, but artificial intelligence connected research about this field has increased with the growth of computer science and programming. The internet has changed the way we live, and how we communicate with each other. For example, instead of sending paper mails and letters, we started using text messages, emails, voice messages, etc. You can learn more about this field by doing some research online."
},
{
"code": null,
"e": 1681,
"s": 1481,
"text": "To give you a better understanding of how Natural Language Processing is being used in machine learning and artificial intelligence fields, I would like to share some real-life applications with you:"
},
{
"code": null,
"e": 1901,
"s": 1681,
"text": "Google Translate: The machine intelligence behind Google Translate understands the words and translates them word by word to the language you want. And it does the translation without losing the meaning of the sentence."
},
{
"code": null,
"e": 2205,
"s": 1901,
"text": "Grammarly: The machine intelligence behind this service is good with grammar and words. It is a great example of how language processing has evolved in the last couple of years. It checks the grammar of the sentences, and it even gives some recommendations on how to increase the quality of the article."
},
{
"code": null,
"e": 2473,
"s": 2205,
"text": "Voice Assistants: This field is also in most of the areas where language processing has improved a lot. Mainly speech recognition technology is being used with the processing of words. Currently, the most known ones are Apple Siri, Google Assistant, and Amazon Alexa."
},
{
"code": null,
"e": 2843,
"s": 2473,
"text": "Chatbots: Another great example of language processing is chatbots. They are very much like virtual assistants but with more specific goals. They are most commonly used on websites where customers visit. They help you to get the information you need without talking to any real person. First, they try to understand your need and then bring the results in front of you."
},
{
"code": null,
"e": 3222,
"s": 2843,
"text": "Web Scraping: Web scraping is another field where language processing is commonly used. It is used to extract information from a web page without even spending time to copy each paragraph one by one. Web scraping is a great way to collect valuable data and train your machine learning model. Web scraping is also a very helpful tool when working with search engine optimization."
},
{
"code": null,
"e": 3587,
"s": 3222,
"text": "NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning, wrappers for industrial-strength NLP libraries."
},
{
"code": null,
"e": 3618,
"s": 3587,
"text": "Reference: http://www.nltk.org"
},
{
"code": null,
"e": 3765,
"s": 3618,
"text": "We have to install NLTK module so that we can use it in our project. Running the following line in your terminal will do the installation for you:"
},
{
"code": null,
"e": 3782,
"s": 3765,
"text": "pip install nltk"
},
{
"code": null,
"e": 4108,
"s": 3782,
"text": "Beautiful Soup is a Python library for getting data out of HTML, XML, and other markup languages. Beautiful Soup helps you pull particular content from a webpage, remove the HTML markup, and save the information. It is a tool for web scraping that helps you clean up and parse the documents you have pulled down from the web."
},
{
"code": null,
"e": 4187,
"s": 4108,
"text": "Reference: https://programminghistorian.org/en/lessons/intro-to-beautiful-soup"
},
{
"code": null,
"e": 4266,
"s": 4187,
"text": "Now, let’s install the latest edition of the beautiful soup library using pip:"
},
{
"code": null,
"e": 4293,
"s": 4266,
"text": "pip install beautifulsoup4"
},
{
"code": null,
"e": 4509,
"s": 4293,
"text": "After the installation of the libraries is completed, we can start working on the programming. For this project, I will be using Jupyter Notebook. Ok, first thing first, let’s import the libraries into the notebook."
},
{
"code": null,
"e": 4627,
"s": 4509,
"text": "import nltkfrom nltk.corpus import stopwordsfrom bs4 import BeautifulSoupimport urllib.requestimport plotly.io as pio"
},
{
"code": null,
"e": 4927,
"s": 4627,
"text": "In this step, we will open the webpage using the urllib request method. After opening it, we will read the whole code of the webpage. As you know, the webpages have a code running in the background. You can right-click on any webpage and click on the ‘inspect element’ to have some idea of the code."
},
{
"code": null,
"e": 4989,
"s": 4927,
"text": "I chose the wikipedia page about Natural Language Processing."
},
{
"code": null,
"e": 5122,
"s": 4989,
"text": "page = urllib.request.urlopen('https://en.wikipedia.org/wiki/Natural_language_processing')html_plain = page.read()print(html_plain)"
},
{
"code": null,
"e": 5183,
"s": 5122,
"text": "This is how it looks like when we print the plain html code:"
},
{
"code": null,
"e": 5506,
"s": 5183,
"text": "As you can see from the screenshot, the plain html code needs some cleaning. BeautifulSoup will help us in this data cleaning process. We have to get rid of lots of unnecessary characters such as double quotes, slashes, bigger than and smaller than signs, and many more. Don’t worry, it also cleans the HTML syntax words 😊"
},
{
"code": null,
"e": 5595,
"s": 5506,
"text": "Let’s see the magical power of BS4 (Beautiful Soup 4) after running the following lines:"
},
{
"code": null,
"e": 5681,
"s": 5595,
"text": "soup = BeautifulSoup(html_plain,'html.parser')soup_text = soup.get_text(strip = True)"
},
{
"code": null,
"e": 6003,
"s": 5681,
"text": "Great! One more thing before we move to split the words: to increase the quality of the processing I recommend lower casing all the characters. It will be helpful when we start counting the frequency of words. Otherwise, the machine will see “Natural” and “natural” as different words due to their different Ascii values."
},
{
"code": null,
"e": 6051,
"s": 6003,
"text": "ready_text = soup_text.lower()print(ready_text)"
},
{
"code": null,
"e": 6194,
"s": 6051,
"text": "Looks much better! Now, let’s move to the next step where will be splitting each word into a list item. This process is known as Tokenization."
},
{
"code": null,
"e": 6611,
"s": 6194,
"text": "This step is crucial when working on a natural language processing project. First, we will tokenize each word by splitting them into list items. After that, we will do some word cleaning. NLTK (Natural Language Toolkit) will use to clean the stop words. This will leave us with the keywords which give us a better idea about the page. This way we don’t count the stop words, such as a, and, of, that, the, with, etc."
},
{
"code": null,
"e": 6684,
"s": 6611,
"text": "tokens = []for t in ready_text.split(): tokens.append(t)print(tokens)"
},
{
"code": null,
"e": 6765,
"s": 6684,
"text": "#Run this line if you get an error message in the next code blocknltk.download()"
},
{
"code": null,
"e": 6817,
"s": 6765,
"text": "Now, let’s clean the stop words in our tokens list."
},
{
"code": null,
"e": 6981,
"s": 6817,
"text": "stop_words = stopwords.words('english')clean_tokens = tokens[:]for token in tokens: if token in stop_words: clean_tokens.remove(token)print(clean_tokens)"
},
{
"code": null,
"e": 7286,
"s": 6981,
"text": "In this step, firstly we will count the frequency of the tokens and then we will filter the high-frequency ones. After filtering, it’s time to visualize the most frequently used words in the natural language processing Wikipedia page. Visualization will help us to see them in order with their frequency."
},
{
"code": null,
"e": 7358,
"s": 7286,
"text": "Let’s calculate the frequency of words using FreqDist function by NLTK."
},
{
"code": null,
"e": 7479,
"s": 7358,
"text": "freq = nltk.FreqDist(clean_tokens)for key, val in freq.items(): print('Word: ' + str(key) + ', Quantity:' + str(val))"
},
{
"code": null,
"e": 7632,
"s": 7479,
"text": "Now, we will define a new dictionary and get the tokens that has been used more than 10 times in the page. These keywords are more valuable than others:"
},
{
"code": null,
"e": 7726,
"s": 7632,
"text": "high_freq = dict()for key, val in freq.items(): if (val > 10): high_freq[key] = val"
},
{
"code": null,
"e": 8033,
"s": 7726,
"text": "Perfect! Now we have a new dictionary called high_freq. Let’s move to the final step and create a bar chart. I think a bar chart will work better with quantitative data representation. I’ve also sorted by descending order so that the word with highest frequency comes first. Here is the visualization code:"
},
{
"code": null,
"e": 8402,
"s": 8033,
"text": "#Note: to pass keys and values of high_freq dictionary, I had to convert them to list when passing themfig = dict({ \"data\": [{\"type\": \"bar\", \"x\": list(high_freq.keys()), \"y\": list(high_freq.values())}], \"layout\": {\"title\": {\"text\": \"Most frequently used words in the page\"}, \"xaxis\": {\"categoryorder\":\"total descending\"}}})pio.show(fig)"
},
{
"code": null,
"e": 8880,
"s": 8402,
"text": "Congrats!! You have created a program that detects the keywords inside a page. Now, without reading the whole page you can still have an idea about the page using natural language processing. Hoping that you enjoyed reading this hands-on guide. I would be glad if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. Feel free to contact me if you have any questions while implementing the code."
}
]
|
Arduino - Pulse Width Modulation | Pulse Width Modulation or PWM is a common technique used to vary the width of the pulses in a pulse-train. PWM has many applications such as controlling servos and speed controllers, limiting the effective power of motors and LEDs.
Pulse width modulation is basically, a square wave with a varying high and low time. A basic PWM signal is shown in the following figure.
There are various terms associated with PWM −
On-Time − Duration of time signal is high.
On-Time − Duration of time signal is high.
Off-Time − Duration of time signal is low.
Off-Time − Duration of time signal is low.
Period − It is represented as the sum of on-time and off-time of PWM signal.
Period − It is represented as the sum of on-time and off-time of PWM signal.
Duty Cycle − It is represented as the percentage of time signal that remains on during the period of the PWM signal.
Duty Cycle − It is represented as the percentage of time signal that remains on during the period of the PWM signal.
As shown in the figure, Ton denotes the on-time and Toff denotes the off-time of signal. Period is the sum of both on and off times and is calculated as shown in the following equation −
Duty cycle is calculated as the on-time of the period of time. Using the period calculated above, duty cycle is calculated as −
The analogWrite() function writes an analog value (PWM wave) to a pin. It can be used to light a LED at varying brightness or drive a motor at various speeds. After a call of the analogWrite() function, the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() or a call to digitalRead() or digitalWrite() on the same pin. The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.
On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.
The Arduino Due supports analogWrite() on pins 2 through 13, and pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.
You do not need to call pinMode() to set the pin as an output before calling analogWrite().
analogWrite ( pin , value ) ;
value − the duty cycle: between 0 (always off) and 255 (always on).
Example
int ledPin = 9; // LED connected to digital pin 9
int analogPin = 3; // potentiometer connected to analog pin 3
int val = 0; // variable to store the read value
void setup() {
pinMode(ledPin, OUTPUT); // sets the pin as output
}
void loop() {
val = analogRead(analogPin); // read the input pin
analogWrite(ledPin, (val / 4)); // analogRead values go from 0 to 1023,
// analogWrite values from 0 to 255
}
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3102,
"s": 2870,
"text": "Pulse Width Modulation or PWM is a common technique used to vary the width of the pulses in a pulse-train. PWM has many applications such as controlling servos and speed controllers, limiting the effective power of motors and LEDs."
},
{
"code": null,
"e": 3240,
"s": 3102,
"text": "Pulse width modulation is basically, a square wave with a varying high and low time. A basic PWM signal is shown in the following figure."
},
{
"code": null,
"e": 3286,
"s": 3240,
"text": "There are various terms associated with PWM −"
},
{
"code": null,
"e": 3329,
"s": 3286,
"text": "On-Time − Duration of time signal is high."
},
{
"code": null,
"e": 3372,
"s": 3329,
"text": "On-Time − Duration of time signal is high."
},
{
"code": null,
"e": 3415,
"s": 3372,
"text": "Off-Time − Duration of time signal is low."
},
{
"code": null,
"e": 3458,
"s": 3415,
"text": "Off-Time − Duration of time signal is low."
},
{
"code": null,
"e": 3535,
"s": 3458,
"text": "Period − It is represented as the sum of on-time and off-time of PWM signal."
},
{
"code": null,
"e": 3612,
"s": 3535,
"text": "Period − It is represented as the sum of on-time and off-time of PWM signal."
},
{
"code": null,
"e": 3729,
"s": 3612,
"text": "Duty Cycle − It is represented as the percentage of time signal that remains on during the period of the PWM signal."
},
{
"code": null,
"e": 3846,
"s": 3729,
"text": "Duty Cycle − It is represented as the percentage of time signal that remains on during the period of the PWM signal."
},
{
"code": null,
"e": 4033,
"s": 3846,
"text": "As shown in the figure, Ton denotes the on-time and Toff denotes the off-time of signal. Period is the sum of both on and off times and is calculated as shown in the following equation −"
},
{
"code": null,
"e": 4161,
"s": 4033,
"text": "Duty cycle is calculated as the on-time of the period of time. Using the period calculated above, duty cycle is calculated as −"
},
{
"code": null,
"e": 4740,
"s": 4161,
"text": "The analogWrite() function writes an analog value (PWM wave) to a pin. It can be used to light a LED at varying brightness or drive a motor at various speeds. After a call of the analogWrite() function, the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() or a call to digitalRead() or digitalWrite() on the same pin. The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz."
},
{
"code": null,
"e": 5001,
"s": 4740,
"text": "On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11."
},
{
"code": null,
"e": 5187,
"s": 5001,
"text": "The Arduino Due supports analogWrite() on pins 2 through 13, and pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs."
},
{
"code": null,
"e": 5279,
"s": 5187,
"text": "You do not need to call pinMode() to set the pin as an output before calling analogWrite()."
},
{
"code": null,
"e": 5310,
"s": 5279,
"text": "analogWrite ( pin , value ) ;\n"
},
{
"code": null,
"e": 5378,
"s": 5310,
"text": "value − the duty cycle: between 0 (always off) and 255 (always on)."
},
{
"code": null,
"e": 5386,
"s": 5378,
"text": "Example"
},
{
"code": null,
"e": 5808,
"s": 5386,
"text": "int ledPin = 9; // LED connected to digital pin 9\nint analogPin = 3; // potentiometer connected to analog pin 3\nint val = 0; // variable to store the read value\n\nvoid setup() {\n pinMode(ledPin, OUTPUT); // sets the pin as output\n}\n\nvoid loop() {\n val = analogRead(analogPin); // read the input pin\n analogWrite(ledPin, (val / 4)); // analogRead values go from 0 to 1023, \n // analogWrite values from 0 to 255\n}"
},
{
"code": null,
"e": 5843,
"s": 5808,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5854,
"s": 5843,
"text": " Amit Rana"
},
{
"code": null,
"e": 5887,
"s": 5854,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5898,
"s": 5887,
"text": " Amit Rana"
},
{
"code": null,
"e": 5931,
"s": 5898,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5944,
"s": 5931,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5979,
"s": 5944,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5992,
"s": 5979,
"text": " Ashraf Said"
},
{
"code": null,
"e": 6024,
"s": 5992,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 6037,
"s": 6024,
"text": " Ashraf Said"
},
{
"code": null,
"e": 6068,
"s": 6037,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 6081,
"s": 6068,
"text": " Ashraf Said"
},
{
"code": null,
"e": 6088,
"s": 6081,
"text": " Print"
},
{
"code": null,
"e": 6099,
"s": 6088,
"text": " Add Notes"
}
]
|
How to setup MongoDB Java environment? | Visit the MongoDB home page, in the Software (dropdown), select Community Server.
Visit the MongoDB home page, in the Software (dropdown), select Community Server.
In the MongoDB Community Server page, specify the platform details and download the MongoDB server compatible to your platform.
In the MongoDB Community Server page, specify the platform details and download the MongoDB server compatible to your platform.
Install the downloaded software and create a folder/directory named data in the C drive to store the database files.
Install the downloaded software and create a folder/directory named data in the C drive to store the database files.
Set the path (environmental variable) for the bin directory of MongoDB i.e. C:\Program Files\MongoDB\Server\4.2\bin>
Set the path (environmental variable) for the bin directory of MongoDB i.e. C:\Program Files\MongoDB\Server\4.2\bin>
Open a command prompt and run the MongoDB server by executing the mongod command as shown below −
Open a command prompt and run the MongoDB server by executing the mongod command as shown below −
C:\Users\Tutorialspoint>mongod --dbpath "C:\data"
Open another command prompt connect to the server by running the mongo command this will give you MongoDB shell and from this, you can
Open another command prompt connect to the server by running the mongo command this will give you MongoDB shell and from this, you can
From MongoDB shell, you can manipulate data in the database.
From MongoDB shell, you can manipulate data in the database.
For testing the setup, try connecting to a database named my database using the use command. If your setup is successful you will get the following result.
> use myDatabase;
switched to db myDatabase
To set up a MongoDB java environment in eclipse you need to create a Java – Maven project and, add the following dependency to its pom.xml file.
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.2</version>
</dependency>
Following JDBC program connects with a database on MongoDB, try executing it −
import com.mongodb.MongoClient;
public class ConnectToDB {
public static void main( String args[] ) {
//Creating a MongoDB client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//Accessing the database
mongo.getDatabase("myDatabase");
System.out.println("Connected to the database successfully");
}
}
If everything goes fine the above program generates the following output −
Connected to the database successfully | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Visit the MongoDB home page, in the Software (dropdown), select Community Server."
},
{
"code": null,
"e": 1226,
"s": 1144,
"text": "Visit the MongoDB home page, in the Software (dropdown), select Community Server."
},
{
"code": null,
"e": 1354,
"s": 1226,
"text": "In the MongoDB Community Server page, specify the platform details and download the MongoDB server compatible to your platform."
},
{
"code": null,
"e": 1482,
"s": 1354,
"text": "In the MongoDB Community Server page, specify the platform details and download the MongoDB server compatible to your platform."
},
{
"code": null,
"e": 1599,
"s": 1482,
"text": "Install the downloaded software and create a folder/directory named data in the C drive to store the database files."
},
{
"code": null,
"e": 1716,
"s": 1599,
"text": "Install the downloaded software and create a folder/directory named data in the C drive to store the database files."
},
{
"code": null,
"e": 1833,
"s": 1716,
"text": "Set the path (environmental variable) for the bin directory of MongoDB i.e. C:\\Program Files\\MongoDB\\Server\\4.2\\bin>"
},
{
"code": null,
"e": 1950,
"s": 1833,
"text": "Set the path (environmental variable) for the bin directory of MongoDB i.e. C:\\Program Files\\MongoDB\\Server\\4.2\\bin>"
},
{
"code": null,
"e": 2048,
"s": 1950,
"text": "Open a command prompt and run the MongoDB server by executing the mongod command as shown below −"
},
{
"code": null,
"e": 2146,
"s": 2048,
"text": "Open a command prompt and run the MongoDB server by executing the mongod command as shown below −"
},
{
"code": null,
"e": 2196,
"s": 2146,
"text": "C:\\Users\\Tutorialspoint>mongod --dbpath \"C:\\data\""
},
{
"code": null,
"e": 2331,
"s": 2196,
"text": "Open another command prompt connect to the server by running the mongo command this will give you MongoDB shell and from this, you can"
},
{
"code": null,
"e": 2466,
"s": 2331,
"text": "Open another command prompt connect to the server by running the mongo command this will give you MongoDB shell and from this, you can"
},
{
"code": null,
"e": 2527,
"s": 2466,
"text": "From MongoDB shell, you can manipulate data in the database."
},
{
"code": null,
"e": 2588,
"s": 2527,
"text": "From MongoDB shell, you can manipulate data in the database."
},
{
"code": null,
"e": 2744,
"s": 2588,
"text": "For testing the setup, try connecting to a database named my database using the use command. If your setup is successful you will get the following result."
},
{
"code": null,
"e": 2788,
"s": 2744,
"text": "> use myDatabase;\nswitched to db myDatabase"
},
{
"code": null,
"e": 2933,
"s": 2788,
"text": "To set up a MongoDB java environment in eclipse you need to create a Java – Maven project and, add the following dependency to its pom.xml file."
},
{
"code": null,
"e": 3069,
"s": 2933,
"text": "<dependency>\n <groupId>org.mongodb</groupId>\n <artifactId>mongo-java-driver</artifactId>\n <version>3.12.2</version>\n</dependency>"
},
{
"code": null,
"e": 3148,
"s": 3069,
"text": "Following JDBC program connects with a database on MongoDB, try executing it −"
},
{
"code": null,
"e": 3498,
"s": 3148,
"text": "import com.mongodb.MongoClient;\npublic class ConnectToDB {\n public static void main( String args[] ) {\n //Creating a MongoDB client\n MongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n //Accessing the database\n mongo.getDatabase(\"myDatabase\");\n System.out.println(\"Connected to the database successfully\");\n }\n}"
},
{
"code": null,
"e": 3573,
"s": 3498,
"text": "If everything goes fine the above program generates the following output −"
},
{
"code": null,
"e": 3612,
"s": 3573,
"text": "Connected to the database successfully"
}
]
|
Surprisingly Effective Way To Name Matching In Python | by Mala Deep | Towards Data Science | Recently I came across this dataset, where I needed to analyze the sales recording of digital products. I got the dataset of having almost 572000 rows and 12 columns. I was so excited to work on such big data. With great enthusiasm, I gave a quick view of data, and I found the same name repeatedly taking different rows. (Ah! Much time for data cleaning!).
On some product column, it contains iphone while on other it was written Iphone, or iphone 7 + and iphone 7 Plus, and for some regular customer list, some have Pushpa Yadav while on other Puspa Yadav (the name is Pseudo).
These are the same product name and customer name but were taken as different forms, i.e., deal with different versions of the same name. These sorts of problems are common scenarios for data scientists to tackle during data analysis. This scenario has a name called data matching or fuzzy matching (probabilistic data matching) or simply data deduplication or string/ name matching.
A common reason might be:
Typing error during data entry.
Abbreviations usages.
System data entry is not well validated to check for such errors.
Others.
Whatsoever, as a data scientist or analyst, it is our responsibility to match those data to create a master record for further analysis.
So, I jotted out the action to solve the problem:
1. Manually check and solve.
2. Look for useful libraries/ resources that the great mind of the community has shared.
The first choice was truly cumbersome for such an extended dataset (572000* 12 ), so I started looking into different libraries and tried thee approaches with a fuzzy matcher (not available on conda Now), fuzzywuzzy which on core uses Levenshtein distance and difflib.
However, on using them, I found that for such big data, it is more time-consuming. Thus, I need to look for a faster and effective method.
After many days of frustration, I finally came to know about the solution shared by Chris van den Berg.
ngram
Vectorization
TF-IDF
Cosine similarity with sparse_dot_topn: The leading juice
Working demo ( Code-work)
As our goal here is not just to match the strings but also match it in a faster way. Thus the concept of ngram, TF-IDF with cosine similarity, comes into play.
Before going into the working demo (code-work), let’s understand the basics.
N-grams are extensively used in text mining and natural language processing, which are a set of co-occurring words within a given sentence or (word file).To find n-gram, we move one word forward( can move any step as per need).
For example, for the room type “Standard Room Ocean View Waikiki Tower”
If N=3 (known as Trigrams), then the n-grams (3-grams) would be:
Standard Room Ocean
Room Ocean View
Ocean View Waikiki
View Waikiki Tower
Explore more about ngrams from the research paper
Why n=3?
Question might arises why n = 3, can be taken as n= 1(unigrams ) or n=2 (bi-grams).
The intuition here is that bi-grams and tri-grams can capture contextual information compared to just unigrams. For example, “Room Ocean View” carries more meaning than only “Room,” “Ocean,” and “View” when observed independently.
TF-IDF stands for term frequency-inverse document frequency, and the TF-IDF weight is a weight often used in information retrieval and text mining two prime concerns.
1. Used to evaluate how important a word is to a document in a collection
2. The importance increases proportionally to the number of times a word appears
Two ideas behind TF-IDF
Term Frequency (TF), aka. The number of times a word appears in a document, divided by the total number of words in that document, i.e., it measures how frequently a term occurs in a document.
Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears, i.e., it measures how important a term is.
While computing TF, all terms are considered equally important. However, it is known that specific words, such as “is,” “of,” and “that,” may appear a lot of times but have little importance.
After having each word split, there is need to convert each of those token(lemmas) into a vector that SciKit Learns algorithm models can work with, as these algorithms only understand the concept of numerical features irrespective of its underlying type (text, image, and numbers, etc.) allowing us to perform complex machine learning tasks on different types of data.
Scikit-learn’s Tfidfvectorizer aims to convert a collection of raw documents to a matrix of TF-IDF features, and it can compute the word counts, IDF, and TF-IDF values all at once.
With this, we generate tf_idf_matrix, which is a sparse matrix as with Tfidfvectorizer, we are converting raw text to a numerical vector representation of words and n-grams. This makes it easy to directly use as already said; algorithms only understand the concept of numerical features irrespective of its underlying type (text, image, numbers, etc.).
How the two text documents are close to each other in terms of their context(surface closeness) and meaning, i.e., lexical similarity and semantic similarity respectively is called Text Similarity and there is a various method to calculate text similarities such as Cosine similarity, Euclidean distance, Jaccard coefficient, and Dice.
Cosine similarity measures the text-similarity between two documents irrespective of their size. Mathematically, the Cosine similarity metric measures the cosine of the angle between two n-dimensional vectors projected in a multi-dimensional space, and value ranges from 0 to 1,
where,
1 means more similarity
0 means less similarity.
Mathematically:
However, the Data Scientists at ING Wholesale Banking Advanced Analytics team found out Cosine Similarity has some disadvantages:
The sklearn version does a lot of type checking and error handling.
The sklearn version calculates and stores all similarities in one go, while we are only interested in the most similar ones.
Therefore both results in the use of more memory consumption and time.
To optimize for these disadvantages, they created their library, which stores only the top N highest matches in each row, and only the similarities above the threshold.
Get more about library: sparse_dot_topn
They proudly claim that this approach improves the speed by about 40% and reduces memory consumption.
With these basic foundational knowledge, we start our code-work.
I assume you are familiar with Jupyter notebook and downloading libraries. If not, please check my previous post, where I have shared the beginners’ guide for exploratory data analysis.
Working environment: Jupyter Notebook from Anaconda
Dataset: Room Types
Snapshot of Dataset
Now let’s import the needed libraries/methods and read our dataset and save it to “df,” you can name “df” as anything with a quick look to the dataset.
# Importing libraries and module and some setting for notebookimport pandas as pd import refrom sklearn.feature_extraction.text import TfidfVectorizerimport numpy as npfrom scipy.sparse import csr_matriximport sparse_dot_topn.sparse_dot_topn as ct # Leading Juice for usimport timepd.set_option('display.max_colwidth', -1)# reading dataset as dfdf = pd.read_csv('room_type.csv')# printing first five rowsdf.head(5)
Here, we are taking n = 3 thus 3-gram or trigrams as most room types contain two or three words, and we split sentences into tokens with removing all special characters, punctuation and single characters (,-./). And collect those 3-grams.
def ngrams(string, n=3):string = re.sub(r'[,-./]|\sBD',r'', string) ngrams = zip(*[string[i:] for i in range(n)]) return [''.join(ngram) for ngram in ngrams]# Testing ngrams work for verificationprint('All 3-grams in "Deluxroom":')ngrams('Deluxroom')
For verification, we test the 3-gram result for “Deluxroom” and we have output as:
Looks good!
Now, After having each word split (token or lemmas (n-gram generated items) ), we need to count the word occurs in each document for which we use Tfidfvectorizer, provided by Scikit-Learn library and convert a collection of raw materials to a matrix of TF-IDF features.
room_types = df['RoomTypes']vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)tf_idf_matrix = vectorizer.fit_transform(room_types)
Let’s view the generated sparse CSR matrix.
print(tf_idf_matrix[0])
Looks good!
We are dealing with a CSR matrix with sparse_dot_topn library.
def awesome_cossim_top(A, B, ntop, lower_bound=0): # force A and B as a CSR matrix. # If they have already been CSR, there is no overhead A = A.tocsr() B = B.tocsr() M, _ = A.shape _, N = B.shape idx_dtype = np.int32 nnz_max = M*ntop indptr = np.zeros(M+1, dtype=idx_dtype) indices = np.zeros(nnz_max, dtype=idx_dtype) data = np.zeros(nnz_max, dtype=A.dtype)ct.sparse_dot_topn( M, N, np.asarray(A.indptr, dtype=idx_dtype), np.asarray(A.indices, dtype=idx_dtype), A.data, np.asarray(B.indptr, dtype=idx_dtype), np.asarray(B.indices, dtype=idx_dtype), B.data, ntop, lower_bound, indptr, indices, data)return csr_matrix((data,indices,indptr),shape=(M,N))
We store the top 10 most similar items and only items with a similarity above 0.8 and show the time taken by the model.
# Top 10 with similarity above 0.8t1 = time.time()matches = awesome_cossim_top(tf_idf_matrix, tf_idf_matrix.transpose(), 10, 0.8)t = time.time()-t1print("SELFTIMED:", t)
Then, we unpack the resulting sparse matrix;
# unpacks the resulting sparse matrixdef get_matches_df(sparse_matrix, name_vector, top=100): non_zeros = sparse_matrix.nonzero() sparserows = non_zeros[0] sparsecols = non_zeros[1] if top: nr_matches = top else: nr_matches = sparsecols.size left_side = np.empty([nr_matches], dtype=object) right_side = np.empty([nr_matches], dtype=object) similairity = np.zeros(nr_matches) for index in range(0, nr_matches): left_side[index] = name_vector[sparserows[index]] right_side[index] = name_vector[sparsecols[index]] similairity[index] = sparse_matrix.data[index] return pd.DataFrame({'left_side': left_side, 'right_side': right_side, 'similairity': similairity})
We view our matches.
# store the matches into new dataframe called matched_df and # printing 10 samplesmatches_df = get_matches_df(matches, room_types, top=200)matches_df = matches_df[matches_df['similairity'] < 0.99999] # For removing all exact matchesmatches_df.sample(10)
Suite, 1 Bedroom and Deluxe Suite, 1 Bedroom is probably not the same room type, and we got the similarity measure of 0.81. Looks good!
In sorted order, we view our matches.
# printing the matches in sorted ordermatches_df.sort_values(['similairity'], ascending=False).head(10)
The matches look pretty satisfying! The cosine similarity gives a good indication of the similarity between the two room types.Grand Corner King Room 1 King Bed and Grand Corner King Room are probably the same room type, and we got the similarity measure of 0.93.
Thus, the correct visual assessment and the matches made with this strategy are very fulfilling.
So, by using the ngram for tokenization, TF-IDF for vector matrix, and TfidfVectorizer to count the word occurs in each document and using cosine similarity with sparse_dot_topn, we matched the strings most quickly even for the large dataset (Got good result with 572000*12 ).
Get the entire working Jupyter notebook in my GitHub.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
If you have any queries regarding the article or want to work together on your next data science project, ping me on LinkedIn.
Stay tuned for next Data Science related post.
Using TF-IDF to identify the signal from the noise
Boosting the selection of the most similar entities in large scale datasets
Cosine Similarity — Text Similarity Metric
An Introduction to N-grams: What Are They and Why Do We Need Them?
Quick Exploratory Data Analysis: Pandas Profiling | [
{
"code": null,
"e": 530,
"s": 172,
"text": "Recently I came across this dataset, where I needed to analyze the sales recording of digital products. I got the dataset of having almost 572000 rows and 12 columns. I was so excited to work on such big data. With great enthusiasm, I gave a quick view of data, and I found the same name repeatedly taking different rows. (Ah! Much time for data cleaning!)."
},
{
"code": null,
"e": 752,
"s": 530,
"text": "On some product column, it contains iphone while on other it was written Iphone, or iphone 7 + and iphone 7 Plus, and for some regular customer list, some have Pushpa Yadav while on other Puspa Yadav (the name is Pseudo)."
},
{
"code": null,
"e": 1136,
"s": 752,
"text": "These are the same product name and customer name but were taken as different forms, i.e., deal with different versions of the same name. These sorts of problems are common scenarios for data scientists to tackle during data analysis. This scenario has a name called data matching or fuzzy matching (probabilistic data matching) or simply data deduplication or string/ name matching."
},
{
"code": null,
"e": 1162,
"s": 1136,
"text": "A common reason might be:"
},
{
"code": null,
"e": 1194,
"s": 1162,
"text": "Typing error during data entry."
},
{
"code": null,
"e": 1216,
"s": 1194,
"text": "Abbreviations usages."
},
{
"code": null,
"e": 1282,
"s": 1216,
"text": "System data entry is not well validated to check for such errors."
},
{
"code": null,
"e": 1290,
"s": 1282,
"text": "Others."
},
{
"code": null,
"e": 1427,
"s": 1290,
"text": "Whatsoever, as a data scientist or analyst, it is our responsibility to match those data to create a master record for further analysis."
},
{
"code": null,
"e": 1477,
"s": 1427,
"text": "So, I jotted out the action to solve the problem:"
},
{
"code": null,
"e": 1506,
"s": 1477,
"text": "1. Manually check and solve."
},
{
"code": null,
"e": 1595,
"s": 1506,
"text": "2. Look for useful libraries/ resources that the great mind of the community has shared."
},
{
"code": null,
"e": 1864,
"s": 1595,
"text": "The first choice was truly cumbersome for such an extended dataset (572000* 12 ), so I started looking into different libraries and tried thee approaches with a fuzzy matcher (not available on conda Now), fuzzywuzzy which on core uses Levenshtein distance and difflib."
},
{
"code": null,
"e": 2003,
"s": 1864,
"text": "However, on using them, I found that for such big data, it is more time-consuming. Thus, I need to look for a faster and effective method."
},
{
"code": null,
"e": 2107,
"s": 2003,
"text": "After many days of frustration, I finally came to know about the solution shared by Chris van den Berg."
},
{
"code": null,
"e": 2113,
"s": 2107,
"text": "ngram"
},
{
"code": null,
"e": 2127,
"s": 2113,
"text": "Vectorization"
},
{
"code": null,
"e": 2134,
"s": 2127,
"text": "TF-IDF"
},
{
"code": null,
"e": 2192,
"s": 2134,
"text": "Cosine similarity with sparse_dot_topn: The leading juice"
},
{
"code": null,
"e": 2218,
"s": 2192,
"text": "Working demo ( Code-work)"
},
{
"code": null,
"e": 2378,
"s": 2218,
"text": "As our goal here is not just to match the strings but also match it in a faster way. Thus the concept of ngram, TF-IDF with cosine similarity, comes into play."
},
{
"code": null,
"e": 2455,
"s": 2378,
"text": "Before going into the working demo (code-work), let’s understand the basics."
},
{
"code": null,
"e": 2683,
"s": 2455,
"text": "N-grams are extensively used in text mining and natural language processing, which are a set of co-occurring words within a given sentence or (word file).To find n-gram, we move one word forward( can move any step as per need)."
},
{
"code": null,
"e": 2755,
"s": 2683,
"text": "For example, for the room type “Standard Room Ocean View Waikiki Tower”"
},
{
"code": null,
"e": 2820,
"s": 2755,
"text": "If N=3 (known as Trigrams), then the n-grams (3-grams) would be:"
},
{
"code": null,
"e": 2840,
"s": 2820,
"text": "Standard Room Ocean"
},
{
"code": null,
"e": 2856,
"s": 2840,
"text": "Room Ocean View"
},
{
"code": null,
"e": 2875,
"s": 2856,
"text": "Ocean View Waikiki"
},
{
"code": null,
"e": 2894,
"s": 2875,
"text": "View Waikiki Tower"
},
{
"code": null,
"e": 2944,
"s": 2894,
"text": "Explore more about ngrams from the research paper"
},
{
"code": null,
"e": 2953,
"s": 2944,
"text": "Why n=3?"
},
{
"code": null,
"e": 3037,
"s": 2953,
"text": "Question might arises why n = 3, can be taken as n= 1(unigrams ) or n=2 (bi-grams)."
},
{
"code": null,
"e": 3268,
"s": 3037,
"text": "The intuition here is that bi-grams and tri-grams can capture contextual information compared to just unigrams. For example, “Room Ocean View” carries more meaning than only “Room,” “Ocean,” and “View” when observed independently."
},
{
"code": null,
"e": 3435,
"s": 3268,
"text": "TF-IDF stands for term frequency-inverse document frequency, and the TF-IDF weight is a weight often used in information retrieval and text mining two prime concerns."
},
{
"code": null,
"e": 3509,
"s": 3435,
"text": "1. Used to evaluate how important a word is to a document in a collection"
},
{
"code": null,
"e": 3590,
"s": 3509,
"text": "2. The importance increases proportionally to the number of times a word appears"
},
{
"code": null,
"e": 3614,
"s": 3590,
"text": "Two ideas behind TF-IDF"
},
{
"code": null,
"e": 3807,
"s": 3614,
"text": "Term Frequency (TF), aka. The number of times a word appears in a document, divided by the total number of words in that document, i.e., it measures how frequently a term occurs in a document."
},
{
"code": null,
"e": 4023,
"s": 3807,
"text": "Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears, i.e., it measures how important a term is."
},
{
"code": null,
"e": 4215,
"s": 4023,
"text": "While computing TF, all terms are considered equally important. However, it is known that specific words, such as “is,” “of,” and “that,” may appear a lot of times but have little importance."
},
{
"code": null,
"e": 4584,
"s": 4215,
"text": "After having each word split, there is need to convert each of those token(lemmas) into a vector that SciKit Learns algorithm models can work with, as these algorithms only understand the concept of numerical features irrespective of its underlying type (text, image, and numbers, etc.) allowing us to perform complex machine learning tasks on different types of data."
},
{
"code": null,
"e": 4765,
"s": 4584,
"text": "Scikit-learn’s Tfidfvectorizer aims to convert a collection of raw documents to a matrix of TF-IDF features, and it can compute the word counts, IDF, and TF-IDF values all at once."
},
{
"code": null,
"e": 5118,
"s": 4765,
"text": "With this, we generate tf_idf_matrix, which is a sparse matrix as with Tfidfvectorizer, we are converting raw text to a numerical vector representation of words and n-grams. This makes it easy to directly use as already said; algorithms only understand the concept of numerical features irrespective of its underlying type (text, image, numbers, etc.)."
},
{
"code": null,
"e": 5454,
"s": 5118,
"text": "How the two text documents are close to each other in terms of their context(surface closeness) and meaning, i.e., lexical similarity and semantic similarity respectively is called Text Similarity and there is a various method to calculate text similarities such as Cosine similarity, Euclidean distance, Jaccard coefficient, and Dice."
},
{
"code": null,
"e": 5733,
"s": 5454,
"text": "Cosine similarity measures the text-similarity between two documents irrespective of their size. Mathematically, the Cosine similarity metric measures the cosine of the angle between two n-dimensional vectors projected in a multi-dimensional space, and value ranges from 0 to 1,"
},
{
"code": null,
"e": 5740,
"s": 5733,
"text": "where,"
},
{
"code": null,
"e": 5764,
"s": 5740,
"text": "1 means more similarity"
},
{
"code": null,
"e": 5789,
"s": 5764,
"text": "0 means less similarity."
},
{
"code": null,
"e": 5805,
"s": 5789,
"text": "Mathematically:"
},
{
"code": null,
"e": 5935,
"s": 5805,
"text": "However, the Data Scientists at ING Wholesale Banking Advanced Analytics team found out Cosine Similarity has some disadvantages:"
},
{
"code": null,
"e": 6003,
"s": 5935,
"text": "The sklearn version does a lot of type checking and error handling."
},
{
"code": null,
"e": 6128,
"s": 6003,
"text": "The sklearn version calculates and stores all similarities in one go, while we are only interested in the most similar ones."
},
{
"code": null,
"e": 6199,
"s": 6128,
"text": "Therefore both results in the use of more memory consumption and time."
},
{
"code": null,
"e": 6368,
"s": 6199,
"text": "To optimize for these disadvantages, they created their library, which stores only the top N highest matches in each row, and only the similarities above the threshold."
},
{
"code": null,
"e": 6408,
"s": 6368,
"text": "Get more about library: sparse_dot_topn"
},
{
"code": null,
"e": 6510,
"s": 6408,
"text": "They proudly claim that this approach improves the speed by about 40% and reduces memory consumption."
},
{
"code": null,
"e": 6575,
"s": 6510,
"text": "With these basic foundational knowledge, we start our code-work."
},
{
"code": null,
"e": 6761,
"s": 6575,
"text": "I assume you are familiar with Jupyter notebook and downloading libraries. If not, please check my previous post, where I have shared the beginners’ guide for exploratory data analysis."
},
{
"code": null,
"e": 6813,
"s": 6761,
"text": "Working environment: Jupyter Notebook from Anaconda"
},
{
"code": null,
"e": 6833,
"s": 6813,
"text": "Dataset: Room Types"
},
{
"code": null,
"e": 6853,
"s": 6833,
"text": "Snapshot of Dataset"
},
{
"code": null,
"e": 7005,
"s": 6853,
"text": "Now let’s import the needed libraries/methods and read our dataset and save it to “df,” you can name “df” as anything with a quick look to the dataset."
},
{
"code": null,
"e": 7423,
"s": 7005,
"text": "# Importing libraries and module and some setting for notebookimport pandas as pd import refrom sklearn.feature_extraction.text import TfidfVectorizerimport numpy as npfrom scipy.sparse import csr_matriximport sparse_dot_topn.sparse_dot_topn as ct # Leading Juice for usimport timepd.set_option('display.max_colwidth', -1)# reading dataset as dfdf = pd.read_csv('room_type.csv')# printing first five rowsdf.head(5)"
},
{
"code": null,
"e": 7662,
"s": 7423,
"text": "Here, we are taking n = 3 thus 3-gram or trigrams as most room types contain two or three words, and we split sentences into tokens with removing all special characters, punctuation and single characters (,-./). And collect those 3-grams."
},
{
"code": null,
"e": 7919,
"s": 7662,
"text": "def ngrams(string, n=3):string = re.sub(r'[,-./]|\\sBD',r'', string) ngrams = zip(*[string[i:] for i in range(n)]) return [''.join(ngram) for ngram in ngrams]# Testing ngrams work for verificationprint('All 3-grams in \"Deluxroom\":')ngrams('Deluxroom')"
},
{
"code": null,
"e": 8002,
"s": 7919,
"text": "For verification, we test the 3-gram result for “Deluxroom” and we have output as:"
},
{
"code": null,
"e": 8014,
"s": 8002,
"text": "Looks good!"
},
{
"code": null,
"e": 8284,
"s": 8014,
"text": "Now, After having each word split (token or lemmas (n-gram generated items) ), we need to count the word occurs in each document for which we use Tfidfvectorizer, provided by Scikit-Learn library and convert a collection of raw materials to a matrix of TF-IDF features."
},
{
"code": null,
"e": 8420,
"s": 8284,
"text": "room_types = df['RoomTypes']vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)tf_idf_matrix = vectorizer.fit_transform(room_types)"
},
{
"code": null,
"e": 8464,
"s": 8420,
"text": "Let’s view the generated sparse CSR matrix."
},
{
"code": null,
"e": 8488,
"s": 8464,
"text": "print(tf_idf_matrix[0])"
},
{
"code": null,
"e": 8500,
"s": 8488,
"text": "Looks good!"
},
{
"code": null,
"e": 8563,
"s": 8500,
"text": "We are dealing with a CSR matrix with sparse_dot_topn library."
},
{
"code": null,
"e": 9314,
"s": 8563,
"text": "def awesome_cossim_top(A, B, ntop, lower_bound=0): # force A and B as a CSR matrix. # If they have already been CSR, there is no overhead A = A.tocsr() B = B.tocsr() M, _ = A.shape _, N = B.shape idx_dtype = np.int32 nnz_max = M*ntop indptr = np.zeros(M+1, dtype=idx_dtype) indices = np.zeros(nnz_max, dtype=idx_dtype) data = np.zeros(nnz_max, dtype=A.dtype)ct.sparse_dot_topn( M, N, np.asarray(A.indptr, dtype=idx_dtype), np.asarray(A.indices, dtype=idx_dtype), A.data, np.asarray(B.indptr, dtype=idx_dtype), np.asarray(B.indices, dtype=idx_dtype), B.data, ntop, lower_bound, indptr, indices, data)return csr_matrix((data,indices,indptr),shape=(M,N))"
},
{
"code": null,
"e": 9434,
"s": 9314,
"text": "We store the top 10 most similar items and only items with a similarity above 0.8 and show the time taken by the model."
},
{
"code": null,
"e": 9605,
"s": 9434,
"text": "# Top 10 with similarity above 0.8t1 = time.time()matches = awesome_cossim_top(tf_idf_matrix, tf_idf_matrix.transpose(), 10, 0.8)t = time.time()-t1print(\"SELFTIMED:\", t)"
},
{
"code": null,
"e": 9650,
"s": 9605,
"text": "Then, we unpack the resulting sparse matrix;"
},
{
"code": null,
"e": 10445,
"s": 9650,
"text": "# unpacks the resulting sparse matrixdef get_matches_df(sparse_matrix, name_vector, top=100): non_zeros = sparse_matrix.nonzero() sparserows = non_zeros[0] sparsecols = non_zeros[1] if top: nr_matches = top else: nr_matches = sparsecols.size left_side = np.empty([nr_matches], dtype=object) right_side = np.empty([nr_matches], dtype=object) similairity = np.zeros(nr_matches) for index in range(0, nr_matches): left_side[index] = name_vector[sparserows[index]] right_side[index] = name_vector[sparsecols[index]] similairity[index] = sparse_matrix.data[index] return pd.DataFrame({'left_side': left_side, 'right_side': right_side, 'similairity': similairity})"
},
{
"code": null,
"e": 10466,
"s": 10445,
"text": "We view our matches."
},
{
"code": null,
"e": 10721,
"s": 10466,
"text": "# store the matches into new dataframe called matched_df and # printing 10 samplesmatches_df = get_matches_df(matches, room_types, top=200)matches_df = matches_df[matches_df['similairity'] < 0.99999] # For removing all exact matchesmatches_df.sample(10)"
},
{
"code": null,
"e": 10857,
"s": 10721,
"text": "Suite, 1 Bedroom and Deluxe Suite, 1 Bedroom is probably not the same room type, and we got the similarity measure of 0.81. Looks good!"
},
{
"code": null,
"e": 10895,
"s": 10857,
"text": "In sorted order, we view our matches."
},
{
"code": null,
"e": 10999,
"s": 10895,
"text": "# printing the matches in sorted ordermatches_df.sort_values(['similairity'], ascending=False).head(10)"
},
{
"code": null,
"e": 11263,
"s": 10999,
"text": "The matches look pretty satisfying! The cosine similarity gives a good indication of the similarity between the two room types.Grand Corner King Room 1 King Bed and Grand Corner King Room are probably the same room type, and we got the similarity measure of 0.93."
},
{
"code": null,
"e": 11360,
"s": 11263,
"text": "Thus, the correct visual assessment and the matches made with this strategy are very fulfilling."
},
{
"code": null,
"e": 11637,
"s": 11360,
"text": "So, by using the ngram for tokenization, TF-IDF for vector matrix, and TfidfVectorizer to count the word occurs in each document and using cosine similarity with sparse_dot_topn, we matched the strings most quickly even for the large dataset (Got good result with 572000*12 )."
},
{
"code": null,
"e": 11691,
"s": 11637,
"text": "Get the entire working Jupyter notebook in my GitHub."
},
{
"code": null,
"e": 11874,
"s": 11691,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 12001,
"s": 11874,
"text": "If you have any queries regarding the article or want to work together on your next data science project, ping me on LinkedIn."
},
{
"code": null,
"e": 12048,
"s": 12001,
"text": "Stay tuned for next Data Science related post."
},
{
"code": null,
"e": 12099,
"s": 12048,
"text": "Using TF-IDF to identify the signal from the noise"
},
{
"code": null,
"e": 12175,
"s": 12099,
"text": "Boosting the selection of the most similar entities in large scale datasets"
},
{
"code": null,
"e": 12218,
"s": 12175,
"text": "Cosine Similarity — Text Similarity Metric"
},
{
"code": null,
"e": 12285,
"s": 12218,
"text": "An Introduction to N-grams: What Are They and Why Do We Need Them?"
}
]
|
MFC - Standard I/O | The MFC library provides its own version of file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile. It can handle the reading and writing of Unicode text files as well as ordinary multi-byte text files.
Here is the list of constructors, which can initialize a CStdioFile object −
CStdioFile();
CStdioFile(CAtlTransactionManager* pTM);
CStdioFile(FILE* pOpenStream);
CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags);
CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM);
Here is the list of methods in CStdioFile −
Open
Overloaded. Open is designed for use with the default CStdioFile constructor (Overrides CFile::Open).
ReadString
Reads a single line of text.
Seek
Positions the current file pointer.
WriteString
Writes a single line of text.
Let us look into a simple example again by creating a new MFC dialog based application.
Step 1 − Drag one edit control and two buttons as shown in the following snapshot.
Step 2 − Add value variable m_strEditCtrl for edit control.
Step 3 − Add click event handler for Open and Save buttons.
Step 4 − Here is the implementation of event handlers.
void CMFCStandardIODlg::OnBnClickedButtonOpen() {
// TODO: Add your control notification handler code here
UpdateData(TRUE);
CStdioFile file;
file.Open(L"D:\\MFCDirectoryDEMO\\test.txt", CFile::modeRead | CFile::typeText);
file.ReadString(m_strEditCtrl);
file.Close();
UpdateData(FALSE);
}
void CMFCStandardIODlg::OnBnClickedButtonSave() {
// TODO: Add your control notification handler code here
UpdateData(TRUE);
CStdioFile file;
if (m_strEditCtrl.GetLength() == 0) {
AfxMessageBox(L"You must specify the text.");
return;
}
file.Open(L"D:\\MFCDirectoryDEMO\\test.txt", CFile::modeCreate |
CFile::modeWrite | CFile::typeText);
file.WriteString(m_strEditCtrl);
file.Close();
}
Step 5 − When the above code is compiled and executed, you will see the following output.
Step 6 − Write something and click Save. It will save the data in *.txt file.
Step 7 − If you look at the location of the file, you will see that it contains the test.txt file.
Step 8 − Now, close the application. Run the same application. When you click Open, the same text loads again.
Step 9 − It starts by opening the file, reading the file, followed by updating the Edit Control.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2322,
"s": 2067,
"text": "The MFC library provides its own version of file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile. It can handle the reading and writing of Unicode text files as well as ordinary multi-byte text files."
},
{
"code": null,
"e": 2399,
"s": 2322,
"text": "Here is the list of constructors, which can initialize a CStdioFile object −"
},
{
"code": null,
"e": 2616,
"s": 2399,
"text": "CStdioFile();\nCStdioFile(CAtlTransactionManager* pTM);\nCStdioFile(FILE* pOpenStream);\nCStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags);\nCStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM);"
},
{
"code": null,
"e": 2660,
"s": 2616,
"text": "Here is the list of methods in CStdioFile −"
},
{
"code": null,
"e": 2665,
"s": 2660,
"text": "Open"
},
{
"code": null,
"e": 2767,
"s": 2665,
"text": "Overloaded. Open is designed for use with the default CStdioFile constructor (Overrides CFile::Open)."
},
{
"code": null,
"e": 2778,
"s": 2767,
"text": "ReadString"
},
{
"code": null,
"e": 2807,
"s": 2778,
"text": "Reads a single line of text."
},
{
"code": null,
"e": 2812,
"s": 2807,
"text": "Seek"
},
{
"code": null,
"e": 2848,
"s": 2812,
"text": "Positions the current file pointer."
},
{
"code": null,
"e": 2860,
"s": 2848,
"text": "WriteString"
},
{
"code": null,
"e": 2890,
"s": 2860,
"text": "Writes a single line of text."
},
{
"code": null,
"e": 2978,
"s": 2890,
"text": "Let us look into a simple example again by creating a new MFC dialog based application."
},
{
"code": null,
"e": 3061,
"s": 2978,
"text": "Step 1 − Drag one edit control and two buttons as shown in the following snapshot."
},
{
"code": null,
"e": 3121,
"s": 3061,
"text": "Step 2 − Add value variable m_strEditCtrl for edit control."
},
{
"code": null,
"e": 3181,
"s": 3121,
"text": "Step 3 − Add click event handler for Open and Save buttons."
},
{
"code": null,
"e": 3236,
"s": 3181,
"text": "Step 4 − Here is the implementation of event handlers."
},
{
"code": null,
"e": 3991,
"s": 3236,
"text": "void CMFCStandardIODlg::OnBnClickedButtonOpen() {\n \n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n\n CStdioFile file;\n file.Open(L\"D:\\\\MFCDirectoryDEMO\\\\test.txt\", CFile::modeRead | CFile::typeText);\n \n file.ReadString(m_strEditCtrl);\n file.Close();\n UpdateData(FALSE);\n}\n\nvoid CMFCStandardIODlg::OnBnClickedButtonSave() {\n \n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n CStdioFile file;\n if (m_strEditCtrl.GetLength() == 0) {\n\n AfxMessageBox(L\"You must specify the text.\");\n return;\n }\n file.Open(L\"D:\\\\MFCDirectoryDEMO\\\\test.txt\", CFile::modeCreate |\n CFile::modeWrite | CFile::typeText);\n file.WriteString(m_strEditCtrl);\n file.Close();\n}"
},
{
"code": null,
"e": 4081,
"s": 3991,
"text": "Step 5 − When the above code is compiled and executed, you will see the following output."
},
{
"code": null,
"e": 4159,
"s": 4081,
"text": "Step 6 − Write something and click Save. It will save the data in *.txt file."
},
{
"code": null,
"e": 4258,
"s": 4159,
"text": "Step 7 − If you look at the location of the file, you will see that it contains the test.txt file."
},
{
"code": null,
"e": 4369,
"s": 4258,
"text": "Step 8 − Now, close the application. Run the same application. When you click Open, the same text loads again."
},
{
"code": null,
"e": 4466,
"s": 4369,
"text": "Step 9 − It starts by opening the file, reading the file, followed by updating the Edit Control."
},
{
"code": null,
"e": 4473,
"s": 4466,
"text": " Print"
},
{
"code": null,
"e": 4484,
"s": 4473,
"text": " Add Notes"
}
]
|
SQLAlchemy ORM - Working with Joins | Now that we have two tables, we will see how to create queries on both tables at the same time. To construct a simple implicit join between Customer and Invoice, we can use Query.filter() to equate their related columns together. Below, we load the Customer and Invoice entities at once using this method −
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()
for c, i in session.query(Customer, Invoice).filter(Customer.id == Invoice.custid).all():
print ("ID: {} Name: {} Invoice No: {} Amount: {}".format(c.id,c.name, i.invno, i.amount))
The SQL expression emitted by SQLAlchemy is as follows −
SELECT customers.id
AS customers_id, customers.name
AS customers_name, customers.address
AS customers_address, customers.email
AS customers_email, invoices.id
AS invoices_id, invoices.custid
AS invoices_custid, invoices.invno
AS invoices_invno, invoices.amount
AS invoices_amount
FROM customers, invoices
WHERE customers.id = invoices.custid
And the result of the above lines of code is as follows −
ID: 2 Name: Gopal Krishna Invoice No: 10 Amount: 15000
ID: 2 Name: Gopal Krishna Invoice No: 14 Amount: 3850
ID: 3 Name: Govind Pant Invoice No: 3 Amount: 10000
ID: 3 Name: Govind Pant Invoice No: 4 Amount: 5000
ID: 4 Name: Govind Kala Invoice No: 7 Amount: 12000
ID: 4 Name: Govind Kala Invoice No: 8 Amount: 8500
ID: 5 Name: Abdul Rahman Invoice No: 9 Amount: 15000
ID: 5 Name: Abdul Rahman Invoice No: 11 Amount: 6000
The actual SQL JOIN syntax is easily achieved using the Query.join() method as follows −
session.query(Customer).join(Invoice).filter(Invoice.amount == 8500).all()
The SQL expression for join will be displayed on the console −
SELECT customers.id
AS customers_id, customers.name
AS customers_name, customers.address
AS customers_address, customers.email
AS customers_email
FROM customers JOIN invoices ON customers.id = invoices.custid
WHERE invoices.amount = ?
We can iterate through the result using for loop −
result = session.query(Customer).join(Invoice).filter(Invoice.amount == 8500)
for row in result:
for inv in row.invoices:
print (row.id, row.name, inv.invno, inv.amount)
With 8500 as the bind parameter, following output is displayed −
4 Govind Kala 8 8500
Query.join() knows how to join between these tables because there’s only one foreign key between them. If there were no foreign keys, or more foreign keys, Query.join() works better when one of the following forms are used −
Similarly outerjoin() function is available to achieve left outer join.
query.outerjoin(Customer.invoices)
The subquery() method produces a SQL expression representing SELECT statement embedded within an alias.
from sqlalchemy.sql import func
stmt = session.query(
Invoice.custid, func.count('*').label('invoice_count')
).group_by(Invoice.custid).subquery()
The stmt object will contain a SQL statement as below −
SELECT invoices.custid, count(:count_1) AS invoice_count FROM invoices GROUP BY invoices.custid
Once we have our statement, it behaves like a Table construct. The columns on the statement are accessible through an attribute called c as shown in the below code −
for u, count in session.query(Customer, stmt.c.invoice_count).outerjoin(stmt, Customer.id == stmt.c.custid).order_by(Customer.id):
print(u.name, count)
The above for loop displays name-wise count of invoices as follows −
Arjun Pandit None
Gopal Krishna 2
Govind Pant 2
Govind Kala 2
Abdul Rahman 2
21 Lectures
1.5 hours
Jack Chan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2647,
"s": 2340,
"text": "Now that we have two tables, we will see how to create queries on both tables at the same time. To construct a simple implicit join between Customer and Invoice, we can use Query.filter() to equate their related columns together. Below, we load the Customer and Invoice entities at once using this method −"
},
{
"code": null,
"e": 2930,
"s": 2647,
"text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\n\nfor c, i in session.query(Customer, Invoice).filter(Customer.id == Invoice.custid).all():\n print (\"ID: {} Name: {} Invoice No: {} Amount: {}\".format(c.id,c.name, i.invno, i.amount))"
},
{
"code": null,
"e": 2987,
"s": 2930,
"text": "The SQL expression emitted by SQLAlchemy is as follows −"
},
{
"code": null,
"e": 3337,
"s": 2987,
"text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email, invoices.id \nAS invoices_id, invoices.custid \nAS invoices_custid, invoices.invno \nAS invoices_invno, invoices.amount \nAS invoices_amount\nFROM customers, invoices\nWHERE customers.id = invoices.custid"
},
{
"code": null,
"e": 3395,
"s": 3337,
"text": "And the result of the above lines of code is as follows −"
},
{
"code": null,
"e": 3817,
"s": 3395,
"text": "ID: 2 Name: Gopal Krishna Invoice No: 10 Amount: 15000\nID: 2 Name: Gopal Krishna Invoice No: 14 Amount: 3850\nID: 3 Name: Govind Pant Invoice No: 3 Amount: 10000\nID: 3 Name: Govind Pant Invoice No: 4 Amount: 5000\nID: 4 Name: Govind Kala Invoice No: 7 Amount: 12000\nID: 4 Name: Govind Kala Invoice No: 8 Amount: 8500\nID: 5 Name: Abdul Rahman Invoice No: 9 Amount: 15000\nID: 5 Name: Abdul Rahman Invoice No: 11 Amount: 6000\n"
},
{
"code": null,
"e": 3906,
"s": 3817,
"text": "The actual SQL JOIN syntax is easily achieved using the Query.join() method as follows −"
},
{
"code": null,
"e": 3981,
"s": 3906,
"text": "session.query(Customer).join(Invoice).filter(Invoice.amount == 8500).all()"
},
{
"code": null,
"e": 4044,
"s": 3981,
"text": "The SQL expression for join will be displayed on the console −"
},
{
"code": null,
"e": 4283,
"s": 4044,
"text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers JOIN invoices ON customers.id = invoices.custid\nWHERE invoices.amount = ?"
},
{
"code": null,
"e": 4334,
"s": 4283,
"text": "We can iterate through the result using for loop −"
},
{
"code": null,
"e": 4513,
"s": 4334,
"text": "result = session.query(Customer).join(Invoice).filter(Invoice.amount == 8500)\nfor row in result:\n for inv in row.invoices:\n print (row.id, row.name, inv.invno, inv.amount)"
},
{
"code": null,
"e": 4578,
"s": 4513,
"text": "With 8500 as the bind parameter, following output is displayed −"
},
{
"code": null,
"e": 4602,
"s": 4578,
"text": "4 Govind Kala 8 8500 \n"
},
{
"code": null,
"e": 4827,
"s": 4602,
"text": "Query.join() knows how to join between these tables because there’s only one foreign key between them. If there were no foreign keys, or more foreign keys, Query.join() works better when one of the following forms are used −"
},
{
"code": null,
"e": 4899,
"s": 4827,
"text": "Similarly outerjoin() function is available to achieve left outer join."
},
{
"code": null,
"e": 4934,
"s": 4899,
"text": "query.outerjoin(Customer.invoices)"
},
{
"code": null,
"e": 5038,
"s": 4934,
"text": "The subquery() method produces a SQL expression representing SELECT statement embedded within an alias."
},
{
"code": null,
"e": 5189,
"s": 5038,
"text": "from sqlalchemy.sql import func\n\nstmt = session.query(\n Invoice.custid, func.count('*').label('invoice_count')\n).group_by(Invoice.custid).subquery()"
},
{
"code": null,
"e": 5245,
"s": 5189,
"text": "The stmt object will contain a SQL statement as below −"
},
{
"code": null,
"e": 5341,
"s": 5245,
"text": "SELECT invoices.custid, count(:count_1) AS invoice_count FROM invoices GROUP BY invoices.custid"
},
{
"code": null,
"e": 5507,
"s": 5341,
"text": "Once we have our statement, it behaves like a Table construct. The columns on the statement are accessible through an attribute called c as shown in the below code −"
},
{
"code": null,
"e": 5662,
"s": 5507,
"text": "for u, count in session.query(Customer, stmt.c.invoice_count).outerjoin(stmt, Customer.id == stmt.c.custid).order_by(Customer.id):\n print(u.name, count)"
},
{
"code": null,
"e": 5731,
"s": 5662,
"text": "The above for loop displays name-wise count of invoices as follows −"
},
{
"code": null,
"e": 5809,
"s": 5731,
"text": "Arjun Pandit None\nGopal Krishna 2\nGovind Pant 2\nGovind Kala 2\nAbdul Rahman 2\n"
},
{
"code": null,
"e": 5844,
"s": 5809,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5855,
"s": 5844,
"text": " Jack Chan"
},
{
"code": null,
"e": 5862,
"s": 5855,
"text": " Print"
},
{
"code": null,
"e": 5873,
"s": 5862,
"text": " Add Notes"
}
]
|
How to track the current location (Latitude and Longitude) in an android device using Kotlin?
| This example demonstrates how to track the current location (Latitude and Longitude) in an android device using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="Current Location in Latitude and Longitude:"
android:textAlignment="center"
android:textColor="@color/common_google_signin_btn_text_dark_focused"
android:textIsSelectable="true"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/latitudeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="@color/common_google_signin_btn_text_dark_focused"
android:textIsSelectable="true"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/longitudeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:textColor="@color/common_google_signin_btn_text_dark_focused"
android:textIsSelectable="true"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
package app.com.kotlipapp
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
class MainActivity : AppCompatActivity() {
private var fusedLocationClient: FusedLocationProviderClient? = null
private var lastLocation: Location? = null
private var latitudeLabel: String? = null
private var longitudeLabel: String? = null
private var latitudeText: TextView? = null
private var longitudeText: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
latitudeLabel = resources.getString(R.string.latitudeBabel)
longitudeLabel = resources.getString(R.string.longitudeBabel)
latitudeText = findViewById<View>(R.id.latitudeText) as TextView
longitudeText = findViewById<View>(R.id.longitudeText) as TextView
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
public override fun onStart() {
super.onStart()
if (!checkPermissions()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions()
}
}
else {
getLastLocation()
}
}
private fun getLastLocation() {
fusedLocationClient?.lastLocation!!.addOnCompleteListener(this) { task ->
if (task.isSuccessful && task.result != null) {
lastLocation = task.result
latitudeText!!.text = latitudeLabel + ": " + (lastLocation)!!.latitude
longitudeText!!.text = longitudeLabel + ": " + (lastLocation)!!.longitude
}
else {
Log.w(TAG, "getLastLocation:exception", task.exception)
showMessage("No location detected. Make sure location is enabled on the device.")
}
}
}
private fun showMessage(string: String) {
val container = findViewById<View>(R.id.linearLayout)
if (container != null) {
Toast.makeText(this@MainActivity, string, Toast.LENGTH_LONG).show()
}
}
private fun showSnackbar(
mainTextStringId: String, actionStringId: String,
listener: View.OnClickListener
) {
Toast.makeText(this@MainActivity, mainTextStringId, Toast.LENGTH_LONG).show()
}
private fun checkPermissions(): Boolean {
val permissionState = ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
)
return permissionState == PackageManager.PERMISSION_GRANTED
}
private fun startLocationPermissionRequest() {
ActivityCompat.requestPermissions(
this@MainActivity,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
REQUEST_PERMISSIONS_REQUEST_CODE
)
}
private fun requestPermissions() {
val shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
)
if (shouldProvideRationale) {
Log.i(TAG, "Displaying permission rationale to provide additional context.")
showSnackbar("Location permission is needed for core functionality", "Okay",
View.OnClickListener {
startLocationPermissionRequest()
})
}
else {
Log.i(TAG, "Requesting permission")
startLocationPermissionRequest()
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>,
grantResults: IntArray
) {
Log.i(TAG, "onRequestPermissionResult")
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
when {
grantResults.isEmpty() -> {
// If user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.")
}
grantResults[0] == PackageManager.PERMISSION_GRANTED -> {
// Permission granted.
getLastLocation()
}
else -> {
showSnackbar("Permission was denied", "Settings",
View.OnClickListener {
// Build intent that displays the App settings screen.
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts(
"package",
Build.DISPLAY, null
)
intent.data = uri
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
)
}
}
}
}
companion object {
private val TAG = "LocationProvider"
private val REQUEST_PERMISSIONS_REQUEST_CODE = 34
}
}
Step 4 − Add the following code to res/strings.xml
<resources>
<string name="app_name">KotlipApp</string>
<string name="latitudeBabel">Latitude</string>
<string name="longitudeBabel">Longitude</string>
</resources>
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.kotlipapp">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme>
<activity android:name=".MainActivity>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1182,
"s": 1062,
"text": "This example demonstrates how to track the current location (Latitude and Longitude) in an android device using Kotlin."
},
{
"code": null,
"e": 1310,
"s": 1182,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1375,
"s": 1310,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2925,
"s": 1375,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/linearLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"10dp\"\n android:text=\"Current Location in Latitude and Longitude:\"\n android:textAlignment=\"center\"\n android:textColor=\"@color/common_google_signin_btn_text_dark_focused\"\n android:textIsSelectable=\"true\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/latitudeText\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"10dp\"\n android:textColor=\"@color/common_google_signin_btn_text_dark_focused\"\n android:textIsSelectable=\"true\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/longitudeText\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"10dp\"\n android:layout_marginTop=\"20dp\"\n android:textColor=\"@color/common_google_signin_btn_text_dark_focused\"\n android:textIsSelectable=\"true\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2980,
"s": 2925,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 8133,
"s": 2980,
"text": "package app.com.kotlipapp\nimport android.Manifest\nimport android.content.Intent\nimport android.content.pm.PackageManager\nimport android.location.Location\nimport android.net.Uri\nimport android.os.Build\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.provider.Settings\nimport android.util.Log\nimport android.view.View\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.core.app.ActivityCompat\nimport com.google.android.gms.location.FusedLocationProviderClient\nimport com.google.android.gms.location.LocationServices\nclass MainActivity : AppCompatActivity() {\n private var fusedLocationClient: FusedLocationProviderClient? = null\n private var lastLocation: Location? = null\n private var latitudeLabel: String? = null\n private var longitudeLabel: String? = null\n private var latitudeText: TextView? = null\n private var longitudeText: TextView? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n latitudeLabel = resources.getString(R.string.latitudeBabel)\n longitudeLabel = resources.getString(R.string.longitudeBabel)\n latitudeText = findViewById<View>(R.id.latitudeText) as TextView\n longitudeText = findViewById<View>(R.id.longitudeText) as TextView\n fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)\n }\n public override fun onStart() {\n super.onStart()\n if (!checkPermissions()) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n requestPermissions()\n }\n }\n else {\n getLastLocation()\n }\n }\n private fun getLastLocation() {\n fusedLocationClient?.lastLocation!!.addOnCompleteListener(this) { task ->\n if (task.isSuccessful && task.result != null) {\n lastLocation = task.result\n latitudeText!!.text = latitudeLabel + \": \" + (lastLocation)!!.latitude\n longitudeText!!.text = longitudeLabel + \": \" + (lastLocation)!!.longitude\n }\n else {\n Log.w(TAG, \"getLastLocation:exception\", task.exception)\n showMessage(\"No location detected. Make sure location is enabled on the device.\")\n }\n }\n }\n private fun showMessage(string: String) {\n val container = findViewById<View>(R.id.linearLayout)\n if (container != null) {\n Toast.makeText(this@MainActivity, string, Toast.LENGTH_LONG).show()\n }\n }\n private fun showSnackbar(\n mainTextStringId: String, actionStringId: String,\n listener: View.OnClickListener\n ) {\n Toast.makeText(this@MainActivity, mainTextStringId, Toast.LENGTH_LONG).show()\n }\n private fun checkPermissions(): Boolean {\n val permissionState = ActivityCompat.checkSelfPermission(\n this,\n Manifest.permission.ACCESS_COARSE_LOCATION\n )\n return permissionState == PackageManager.PERMISSION_GRANTED\n}\nprivate fun startLocationPermissionRequest() {\n ActivityCompat.requestPermissions(\n this@MainActivity,\n arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),\n REQUEST_PERMISSIONS_REQUEST_CODE\n )\n}\nprivate fun requestPermissions() {\n val shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(\n this,\n Manifest.permission.ACCESS_COARSE_LOCATION\n )\n if (shouldProvideRationale) {\n Log.i(TAG, \"Displaying permission rationale to provide additional context.\")\n showSnackbar(\"Location permission is needed for core functionality\", \"Okay\",\n View.OnClickListener {\n startLocationPermissionRequest()\n })\n }\n else {\n Log.i(TAG, \"Requesting permission\")\n startLocationPermissionRequest()\n }\n}\noverride fun onRequestPermissionsResult(\n requestCode: Int, permissions: Array<String>,\n grantResults: IntArray\n) {\n Log.i(TAG, \"onRequestPermissionResult\")\n if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {\n when {\n grantResults.isEmpty() -> {\n // If user interaction was interrupted, the permission request is cancelled and you\n // receive empty arrays.\n Log.i(TAG, \"User interaction was cancelled.\")\n }\n grantResults[0] == PackageManager.PERMISSION_GRANTED -> {\n // Permission granted.\n getLastLocation()\n }\n else -> {\n showSnackbar(\"Permission was denied\", \"Settings\",\n View.OnClickListener {\n // Build intent that displays the App settings screen.\n val intent = Intent()\n intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS\n val uri = Uri.fromParts(\n \"package\",\n Build.DISPLAY, null\n )\n intent.data = uri\n intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK\n startActivity(intent)\n }\n )\n }\n }\n }\n }\n companion object {\n private val TAG = \"LocationProvider\"\n private val REQUEST_PERMISSIONS_REQUEST_CODE = 34\n }\n}"
},
{
"code": null,
"e": 8184,
"s": 8133,
"text": "Step 4 − Add the following code to res/strings.xml"
},
{
"code": null,
"e": 8357,
"s": 8184,
"text": "<resources>\n <string name=\"app_name\">KotlipApp</string>\n <string name=\"latitudeBabel\">Latitude</string>\n <string name=\"longitudeBabel\">Longitude</string>\n</resources>"
},
{
"code": null,
"e": 8412,
"s": 8357,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 9307,
"s": 8412,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>\n <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme>\n <activity android:name=\".MainActivity>\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 9658,
"s": 9307,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 9699,
"s": 9658,
"text": "Click here to download the project code."
}
]
|
Image processing using scikit image | by Antony Paulson Chazhoor | Towards Data Science | One of the positive sides of the data science job hunt process is the exposure to challenges and problems in the real world. One such challenge was that of detecting object locations in an image. The project could be approached using two methods.
Computer Vision without using Neural Networks
Computer Vision with Convolutional Neural Networks
For a guy who had no idea on how to do basic image analysis without neural networks, I ended up completing the project successfully within 4 days. The most crucial component in doing so was to make sense of what images actually are and how to process them.
The main focus of the post is to do just that, simply understand images with scikit image. Following along these points will do a world of good for budding data scientists interested in computer vision.
1. What are Images?
They are just numpy arrays. Getting this straight reduces half of the complexity in this field for a data scientist.
Don’t believe me, try this out. You’ll be drawing an image of how your Television set looked like without any signal reception in the 80's.
import numpy as npimport matplotlib.pyplot as pltrandom_image = np.random.random([500,500])plt.imshow(random_image, cmap = 'gray')plt.colorbar();
2. Broadly there are three layers to images Red, Blue and Green
Images are just a collection of numbers. You can change these on a real image by playing with the values and edit images. Here is a demo which will show the scale of the image and also the shape of it.
#Checking out a color imagefrom skimage import datacat = data.chelsea()print(f'Shape: {cat.shape}')print("Values min/max", cat.min(), cat.max())plt.imshow(cat)
Pay attention to the 3 in the shape. These signify a the red, blue and green layers. Editing the values in these arrays should edit the image. Let’s put this to the test. Lets draw a square on the image.
#Drawing a red square on the imagecat[10:110, 10:110, :] = [255, 0, 0] #{red, green, blue }plt.imshow(cat)
Just like a student bored in class, I just defaced an image using python code. If anyone’s interested try making the cat cooler with some shades and a gold chain(An entire side project). Let’s move on.
3. Working with images on your system
Learning to upload images from your system to a python environment is essential and can be done using the following code
from skimage import ioimage = io.imread('image path')
4. Converting images to greyscale
Most of the time image processing is less complex on grayscale images, in lay man terms Black and white images. Skimage can convert a colored(red, blue, green) image to a grayscale images in the following way:
gray_image = color.rgb2gray(image)plt.imshow(gray_image, cmap = 'gray');
5. Finding the edges of an image
A very crucial element in object detection and localization in an image is the ability to detect its edges. Lets take this image of a man operating a camera.
skimage filters and blurs this image to not go into much detail but find the outline of the man. This is called pixelation.
####Code for smooth pixelation####from skimage import filters, img_as_floatimport scipy.ndimage as ndi#Convolution step(Like in CNN's)smooth_mean = ndi.convolve(image, mean_kernel)image = data.camera()pixelated = image[::10, ::10]pixelated_float = img_as_float(pixelated)sigma =1smooth = filters.gaussian(pixelated_float, sigma)plt.imshow(smooth);
Using sobel filteration from the filter, the edges of this image can be easily found. Use the code below:
#Using the Sobel filterplt.imshow(filters.sobel(pixelated_float))
Building on these basic knowledge points will definitely be a great start to enter into computer vision. The methods can be ventured into much more practical detail by watching and learning from the SciPy conference 2019. It is freely available on youtube and is exactly what taught me the basics.
Follow this link to get there
https://www.youtube.com/watch?v=d1CIV9irQAY
My final intention for every reader going through this post is to remove the fear and intimidation over any image analysis task. Images are just basic numbers and thats one thing every data scientist is comfortable with. | [
{
"code": null,
"e": 419,
"s": 172,
"text": "One of the positive sides of the data science job hunt process is the exposure to challenges and problems in the real world. One such challenge was that of detecting object locations in an image. The project could be approached using two methods."
},
{
"code": null,
"e": 465,
"s": 419,
"text": "Computer Vision without using Neural Networks"
},
{
"code": null,
"e": 516,
"s": 465,
"text": "Computer Vision with Convolutional Neural Networks"
},
{
"code": null,
"e": 773,
"s": 516,
"text": "For a guy who had no idea on how to do basic image analysis without neural networks, I ended up completing the project successfully within 4 days. The most crucial component in doing so was to make sense of what images actually are and how to process them."
},
{
"code": null,
"e": 976,
"s": 773,
"text": "The main focus of the post is to do just that, simply understand images with scikit image. Following along these points will do a world of good for budding data scientists interested in computer vision."
},
{
"code": null,
"e": 996,
"s": 976,
"text": "1. What are Images?"
},
{
"code": null,
"e": 1113,
"s": 996,
"text": "They are just numpy arrays. Getting this straight reduces half of the complexity in this field for a data scientist."
},
{
"code": null,
"e": 1253,
"s": 1113,
"text": "Don’t believe me, try this out. You’ll be drawing an image of how your Television set looked like without any signal reception in the 80's."
},
{
"code": null,
"e": 1399,
"s": 1253,
"text": "import numpy as npimport matplotlib.pyplot as pltrandom_image = np.random.random([500,500])plt.imshow(random_image, cmap = 'gray')plt.colorbar();"
},
{
"code": null,
"e": 1463,
"s": 1399,
"text": "2. Broadly there are three layers to images Red, Blue and Green"
},
{
"code": null,
"e": 1665,
"s": 1463,
"text": "Images are just a collection of numbers. You can change these on a real image by playing with the values and edit images. Here is a demo which will show the scale of the image and also the shape of it."
},
{
"code": null,
"e": 1825,
"s": 1665,
"text": "#Checking out a color imagefrom skimage import datacat = data.chelsea()print(f'Shape: {cat.shape}')print(\"Values min/max\", cat.min(), cat.max())plt.imshow(cat)"
},
{
"code": null,
"e": 2029,
"s": 1825,
"text": "Pay attention to the 3 in the shape. These signify a the red, blue and green layers. Editing the values in these arrays should edit the image. Let’s put this to the test. Lets draw a square on the image."
},
{
"code": null,
"e": 2136,
"s": 2029,
"text": "#Drawing a red square on the imagecat[10:110, 10:110, :] = [255, 0, 0] #{red, green, blue }plt.imshow(cat)"
},
{
"code": null,
"e": 2338,
"s": 2136,
"text": "Just like a student bored in class, I just defaced an image using python code. If anyone’s interested try making the cat cooler with some shades and a gold chain(An entire side project). Let’s move on."
},
{
"code": null,
"e": 2376,
"s": 2338,
"text": "3. Working with images on your system"
},
{
"code": null,
"e": 2497,
"s": 2376,
"text": "Learning to upload images from your system to a python environment is essential and can be done using the following code"
},
{
"code": null,
"e": 2551,
"s": 2497,
"text": "from skimage import ioimage = io.imread('image path')"
},
{
"code": null,
"e": 2585,
"s": 2551,
"text": "4. Converting images to greyscale"
},
{
"code": null,
"e": 2795,
"s": 2585,
"text": "Most of the time image processing is less complex on grayscale images, in lay man terms Black and white images. Skimage can convert a colored(red, blue, green) image to a grayscale images in the following way:"
},
{
"code": null,
"e": 2868,
"s": 2795,
"text": "gray_image = color.rgb2gray(image)plt.imshow(gray_image, cmap = 'gray');"
},
{
"code": null,
"e": 2901,
"s": 2868,
"text": "5. Finding the edges of an image"
},
{
"code": null,
"e": 3059,
"s": 2901,
"text": "A very crucial element in object detection and localization in an image is the ability to detect its edges. Lets take this image of a man operating a camera."
},
{
"code": null,
"e": 3183,
"s": 3059,
"text": "skimage filters and blurs this image to not go into much detail but find the outline of the man. This is called pixelation."
},
{
"code": null,
"e": 3532,
"s": 3183,
"text": "####Code for smooth pixelation####from skimage import filters, img_as_floatimport scipy.ndimage as ndi#Convolution step(Like in CNN's)smooth_mean = ndi.convolve(image, mean_kernel)image = data.camera()pixelated = image[::10, ::10]pixelated_float = img_as_float(pixelated)sigma =1smooth = filters.gaussian(pixelated_float, sigma)plt.imshow(smooth);"
},
{
"code": null,
"e": 3638,
"s": 3532,
"text": "Using sobel filteration from the filter, the edges of this image can be easily found. Use the code below:"
},
{
"code": null,
"e": 3704,
"s": 3638,
"text": "#Using the Sobel filterplt.imshow(filters.sobel(pixelated_float))"
},
{
"code": null,
"e": 4002,
"s": 3704,
"text": "Building on these basic knowledge points will definitely be a great start to enter into computer vision. The methods can be ventured into much more practical detail by watching and learning from the SciPy conference 2019. It is freely available on youtube and is exactly what taught me the basics."
},
{
"code": null,
"e": 4032,
"s": 4002,
"text": "Follow this link to get there"
},
{
"code": null,
"e": 4076,
"s": 4032,
"text": "https://www.youtube.com/watch?v=d1CIV9irQAY"
}
]
|
Socket.IO - Chat Application | Now that we are well acquainted with Socket.IO, let us write a chat application, which we can use to chat on different chat rooms. We will allow users to choose a username and allow them to chat using them. So first, let us set up our HTML file to request for a username −
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
<body>
<input type="text" name="name" value="" placeholder="Enter your name!">
<button type="button" name="button">Let me chat!</button>
</body>
</html>
Now that we have set up our HTML to request for a username, let us create the server to accept connections from the client. We will allow people to send their chosen usernames using the setUsername event. If a user exists, we will respond by a userExists event, else using a userSet event.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile('E:/test/index.html');});
users = [];
io.on('connection', function(socket){
console.log('A user connected');
socket.on('setUsername', function(data){
if(users.indexOf(data) > -1){
users.push(data);
socket.emit('userSet', {username: data});
} else {
socket.emit('userExists', data + ' username is taken! Try some other username.');
}
})
});
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
We need to send the username to the server when people click on the button. If user exists, we show an error message; else, we show a messaging screen −
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
function setUsername(){
socket.emit('setUsername', document.getElementById('name').value);
};
var user;
socket.on('userExists', function(data){
document.getElementById('error-container').innerHTML = data;
});
socket.on('userSet', function(data){
user = data.username;
document.body.innerHTML = '<input type="text" id="message">\
<button type="button" name="button" onclick="sendMessage()">Send</button>\
<div id="message-container"></div>';
});
function sendMessage(){
var msg = document.getElementById('message').value;
if(msg){
socket.emit('msg', {message: msg, user: user});
}
}
socket.on('newmsg', function(data){
if(user){
document.getElementById('message-container').innerHTML +='<div><b>' + data.user + '</b>: ' + data.message + '</div>'
}
})
</script>
<body>
<div id="error-container"></div>
<input id="name" type="text" name="name" value="" placeholder="Enter your name!">
<button type="button" name="button" onclick="setUsername()">Let me chat!</button>
</body>
</html>
Now if you connect two clients with same username, it will give you an error as shown in the screenshot below −
Once you have provided an acceptable username, you will be taken to a screen with a message box and a button to send messages. Now, we have to handle and direct the messages to the connected client. For that, modify your app.js file to include the following changes −
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile('E:/test/index.html');});
users = [];
io.on('connection', function(socket){
console.log('A user connected');
socket.on('setUsername', function(data){
console.log(data);
if(users.indexOf(data) > -1){
socket.emit('userExists', data + ' username is taken! Try some other username.');
} else {
users.push(data);
socket.emit('userSet', {username: data});
}
});
socket.on('msg', function(data){
//Send message to everyone
io.sockets.emit('newmsg', data);
})
});
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
Now connect any number of clients to your server, provide them a username and start chatting! In the following example, we have connected two clients with names Ayush and Harshit and sent some messages from both the clients −
35 Lectures
2.5 hours
Nicholas Lever
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2138,
"s": 1865,
"text": "Now that we are well acquainted with Socket.IO, let us write a chat application, which we can use to chat on different chat rooms. We will allow users to choose a username and allow them to chat using them. So first, let us set up our HTML file to request for a username −"
},
{
"code": null,
"e": 2476,
"s": 2138,
"text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n </script>\n <body>\n <input type=\"text\" name=\"name\" value=\"\" placeholder=\"Enter your name!\">\n <button type=\"button\" name=\"button\">Let me chat!</button>\n </body>\n</html>"
},
{
"code": null,
"e": 2766,
"s": 2476,
"text": "Now that we have set up our HTML to request for a username, let us create the server to accept connections from the client. We will allow people to send their chosen usernames using the setUsername event. If a user exists, we will respond by a userExists event, else using a userSet event."
},
{
"code": null,
"e": 3399,
"s": 2766,
"text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');});\nusers = [];\nio.on('connection', function(socket){\n console.log('A user connected');\n socket.on('setUsername', function(data){\n if(users.indexOf(data) > -1){\n users.push(data);\n socket.emit('userSet', {username: data});\n } else {\n socket.emit('userExists', data + ' username is taken! Try some other username.');\n }\n })\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});"
},
{
"code": null,
"e": 3552,
"s": 3399,
"text": "We need to send the username to the server when people click on the button. If user exists, we show an error message; else, we show a messaging screen −"
},
{
"code": null,
"e": 4908,
"s": 3552,
"text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n function setUsername(){\n socket.emit('setUsername', document.getElementById('name').value);\n };\n var user;\n socket.on('userExists', function(data){\n document.getElementById('error-container').innerHTML = data;\n });\n socket.on('userSet', function(data){\n user = data.username;\n document.body.innerHTML = '<input type=\"text\" id=\"message\">\\\n <button type=\"button\" name=\"button\" onclick=\"sendMessage()\">Send</button>\\\n <div id=\"message-container\"></div>';\n });\n function sendMessage(){\n var msg = document.getElementById('message').value;\n if(msg){\n socket.emit('msg', {message: msg, user: user});\n }\n }\n socket.on('newmsg', function(data){\n if(user){\n document.getElementById('message-container').innerHTML +='<div><b>' + data.user + '</b>: ' + data.message + '</div>'\n }\n })\n </script>\n <body>\n <div id=\"error-container\"></div>\n <input id=\"name\" type=\"text\" name=\"name\" value=\"\" placeholder=\"Enter your name!\">\n <button type=\"button\" name=\"button\" onclick=\"setUsername()\">Let me chat!</button>\n </body>\n </html>"
},
{
"code": null,
"e": 5020,
"s": 4908,
"text": "Now if you connect two clients with same username, it will give you an error as shown in the screenshot below −"
},
{
"code": null,
"e": 5288,
"s": 5020,
"text": "Once you have provided an acceptable username, you will be taken to a screen with a message box and a button to send messages. Now, we have to handle and direct the messages to the connected client. For that, modify your app.js file to include the following changes −"
},
{
"code": null,
"e": 6062,
"s": 5288,
"text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');});\nusers = [];\nio.on('connection', function(socket){\n console.log('A user connected');\n socket.on('setUsername', function(data){\n console.log(data);\n if(users.indexOf(data) > -1){\n socket.emit('userExists', data + ' username is taken! Try some other username.');\n } else {\n users.push(data);\n socket.emit('userSet', {username: data});\n }\n });\n socket.on('msg', function(data){\n //Send message to everyone\n io.sockets.emit('newmsg', data);\n })\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});"
},
{
"code": null,
"e": 6288,
"s": 6062,
"text": "Now connect any number of clients to your server, provide them a username and start chatting! In the following example, we have connected two clients with names Ayush and Harshit and sent some messages from both the clients −"
},
{
"code": null,
"e": 6323,
"s": 6288,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6339,
"s": 6323,
"text": " Nicholas Lever"
},
{
"code": null,
"e": 6346,
"s": 6339,
"text": " Print"
},
{
"code": null,
"e": 6357,
"s": 6346,
"text": " Add Notes"
}
]
|
Java Cryptography - Creating a MAC | MAC (Message Authentication Code) algorithm is a symmetric key cryptographic technique to provide message authentication. For establishing MAC process, the sender and receiver share a symmetric key K.
Essentially, a MAC is an encrypted checksum generated on the underlying message that is sent along with a message to ensure message authentication.
The process of using MAC for authentication is depicted in the following illustration −
In Java the Mac class of the javax.crypto package provides the functionality of message authentication code. Follow the steps given below to create message authentication code using this class.
The KeyGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyGenerator object that generates secret keys.
Create KeyGenerator object using the getInstance() method as shown below.
//Creating a KeyGenerator object
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
The SecureRandom class of the java.Security package provides a strong random number generator which is used to generate random numbers in Java. Instantiate this class as shown below.
//Creating a SecureRandom object
SecureRandom secRandom = new SecureRandom();
The KeyGenerator class provides a method named init() this method accepts the SecureRandom object and initializes the current KeyGenerator.
Initialize the KeyGenerator object created in the previous step using this method.
//Initializing the KeyGenerator
keyGen.init(secRandom);
Generate key using generateKey() method of the KeyGenerator class as shown below.
//Creating/Generating a key
Key key = keyGen.generateKey();
The init() method of the Mac class accepts an Key object and initializes the current Mac object using the given key.
//Initializing the Mac object
mac.init(key);
The doFinal() method of the Mac class is used to finish the Mac operation. Pass the required data in the form of byte array to this method and finsh the operation as shown below.
//Computing the Mac
String msg = new String("Hi how are you");
byte[] bytes = msg.getBytes();
byte[] macResult = mac.doFinal(bytes);
The following example demonstrates the generation of Message Authentication Code (MAC) using JCA. Here, we take a simple message "Hi how are you" and, generate a Mac for that message.
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
public class MacSample {
public static void main(String args[]) throws Exception{
//Creating a KeyGenerator object
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
//Creating a SecureRandom object
SecureRandom secRandom = new SecureRandom();
//Initializing the KeyGenerator
keyGen.init(secRandom);
//Creating/Generating a key
Key key = keyGen.generateKey();
//Creating a Mac object
Mac mac = Mac.getInstance("HmacSHA256");
//Initializing the Mac object
mac.init(key);
//Computing the Mac
String msg = new String("Hi how are you");
byte[] bytes = msg.getBytes();
byte[] macResult = mac.doFinal(bytes);
System.out.println("Mac result:");
System.out.println(new String(macResult));
}
}
The above program will generate the following output −
Mac result:
HÖ„^ǃÎ_Utbh...?š_üzØSSÜh_ž_œa0ŽV?
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2254,
"s": 2053,
"text": "MAC (Message Authentication Code) algorithm is a symmetric key cryptographic technique to provide message authentication. For establishing MAC process, the sender and receiver share a symmetric key K."
},
{
"code": null,
"e": 2402,
"s": 2254,
"text": "Essentially, a MAC is an encrypted checksum generated on the underlying message that is sent along with a message to ensure message authentication."
},
{
"code": null,
"e": 2490,
"s": 2402,
"text": "The process of using MAC for authentication is depicted in the following illustration −"
},
{
"code": null,
"e": 2684,
"s": 2490,
"text": "In Java the Mac class of the javax.crypto package provides the functionality of message authentication code. Follow the steps given below to create message authentication code using this class."
},
{
"code": null,
"e": 2882,
"s": 2684,
"text": "The KeyGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyGenerator object that generates secret keys."
},
{
"code": null,
"e": 2956,
"s": 2882,
"text": "Create KeyGenerator object using the getInstance() method as shown below."
},
{
"code": null,
"e": 3045,
"s": 2956,
"text": "//Creating a KeyGenerator object\nKeyGenerator keyGen = KeyGenerator.getInstance(\"DES\");\n"
},
{
"code": null,
"e": 3228,
"s": 3045,
"text": "The SecureRandom class of the java.Security package provides a strong random number generator which is used to generate random numbers in Java. Instantiate this class as shown below."
},
{
"code": null,
"e": 3307,
"s": 3228,
"text": "//Creating a SecureRandom object\nSecureRandom secRandom = new SecureRandom();\n"
},
{
"code": null,
"e": 3447,
"s": 3307,
"text": "The KeyGenerator class provides a method named init() this method accepts the SecureRandom object and initializes the current KeyGenerator."
},
{
"code": null,
"e": 3530,
"s": 3447,
"text": "Initialize the KeyGenerator object created in the previous step using this method."
},
{
"code": null,
"e": 3587,
"s": 3530,
"text": "//Initializing the KeyGenerator\nkeyGen.init(secRandom);\n"
},
{
"code": null,
"e": 3669,
"s": 3587,
"text": "Generate key using generateKey() method of the KeyGenerator class as shown below."
},
{
"code": null,
"e": 3730,
"s": 3669,
"text": "//Creating/Generating a key\nKey key = keyGen.generateKey();\n"
},
{
"code": null,
"e": 3847,
"s": 3730,
"text": "The init() method of the Mac class accepts an Key object and initializes the current Mac object using the given key."
},
{
"code": null,
"e": 3893,
"s": 3847,
"text": "//Initializing the Mac object\nmac.init(key);\n"
},
{
"code": null,
"e": 4072,
"s": 3893,
"text": "The doFinal() method of the Mac class is used to finish the Mac operation. Pass the required data in the form of byte array to this method and finsh the operation as shown below."
},
{
"code": null,
"e": 4206,
"s": 4072,
"text": "//Computing the Mac\nString msg = new String(\"Hi how are you\");\nbyte[] bytes = msg.getBytes();\nbyte[] macResult = mac.doFinal(bytes);\n"
},
{
"code": null,
"e": 4390,
"s": 4206,
"text": "The following example demonstrates the generation of Message Authentication Code (MAC) using JCA. Here, we take a simple message \"Hi how are you\" and, generate a Mac for that message."
},
{
"code": null,
"e": 5335,
"s": 4390,
"text": "import java.security.Key;\nimport java.security.SecureRandom;\n\nimport javax.crypto.KeyGenerator;\nimport javax.crypto.Mac;\n\npublic class MacSample {\n public static void main(String args[]) throws Exception{\n //Creating a KeyGenerator object\n KeyGenerator keyGen = KeyGenerator.getInstance(\"DES\");\n\n //Creating a SecureRandom object\n SecureRandom secRandom = new SecureRandom();\n\n //Initializing the KeyGenerator\n keyGen.init(secRandom);\n\n //Creating/Generating a key\n Key key = keyGen.generateKey();\t \n\n //Creating a Mac object\n Mac mac = Mac.getInstance(\"HmacSHA256\");\n\n //Initializing the Mac object\n mac.init(key);\n\n //Computing the Mac\n String msg = new String(\"Hi how are you\");\n byte[] bytes = msg.getBytes(); \n byte[] macResult = mac.doFinal(bytes);\n\n System.out.println(\"Mac result:\");\n System.out.println(new String(macResult)); \n }\n}"
},
{
"code": null,
"e": 5390,
"s": 5335,
"text": "The above program will generate the following output −"
},
{
"code": null,
"e": 5446,
"s": 5390,
"text": "Mac result:\nHÖ„^ǃÎ_Utbh...?š_üzØSSÜh_ž_œa0ŽV?\n"
},
{
"code": null,
"e": 5479,
"s": 5446,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5495,
"s": 5479,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5528,
"s": 5495,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5544,
"s": 5528,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5579,
"s": 5544,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5593,
"s": 5579,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5627,
"s": 5593,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5641,
"s": 5627,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5678,
"s": 5641,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5693,
"s": 5678,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5726,
"s": 5693,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5745,
"s": 5726,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5752,
"s": 5745,
"text": " Print"
},
{
"code": null,
"e": 5763,
"s": 5752,
"text": " Add Notes"
}
]
|
How to create boxplot for multiple categories with long names in base R? | In base R, we use boxplot function to create the boxplots but if we have categorical vector and the corresponding numerical vector then the boxplot can be easily created. For this purpose, we should save those vectors in a data frame and use the $ operator and las = 2 argument to create the boxplot as shown in the below example.
Consider the below vectors:
Countries<−sample(c("China","India","Canada","USA","Russia","Indonesia","Nepal"),5000,replace=TRUE)
> Rate<−rnorm(5000,10,1)
Create the data frame using above vectors −
df<−data.frame(Countries,Rate)
> head(df,20)
Countries Rate
1 Russia 9.885246
2 Nepal 9.895285
3 USA 11.524113
4 Nepal 10.133226
5 Indonesia 9.711389
6 Russia 10.017597
7 Nepal 9.204832
8 Russia 8.436829
9 Russia 10.579013
10 Canada 7.984238
11 Canada 9.407908
12 Indonesia 9.047598
13 China 9.193126
14 India 8.524555
15 China 10.398155
16 India 6.926581
17 China 10.104521
18 Canada 10.178826
19 India 12.006973
20 Canada 10.371956
Creating boxplot for countries −
boxplot(df$Rate~df$Countries)
Creating boxplot for countries by changing the printing direction of country’s name −
boxplot(df$Rate~df$Countries,las=2,xlab="") | [
{
"code": null,
"e": 1393,
"s": 1062,
"text": "In base R, we use boxplot function to create the boxplots but if we have categorical vector and the corresponding numerical vector then the boxplot can be easily created. For this purpose, we should save those vectors in a data frame and use the $ operator and las = 2 argument to create the boxplot as shown in the below example."
},
{
"code": null,
"e": 1421,
"s": 1393,
"text": "Consider the below vectors:"
},
{
"code": null,
"e": 1546,
"s": 1421,
"text": "Countries<−sample(c(\"China\",\"India\",\"Canada\",\"USA\",\"Russia\",\"Indonesia\",\"Nepal\"),5000,replace=TRUE)\n> Rate<−rnorm(5000,10,1)"
},
{
"code": null,
"e": 1590,
"s": 1546,
"text": "Create the data frame using above vectors −"
},
{
"code": null,
"e": 1635,
"s": 1590,
"text": "df<−data.frame(Countries,Rate)\n> head(df,20)"
},
{
"code": null,
"e": 2088,
"s": 1635,
"text": "Countries Rate\n1 Russia 9.885246\n2 Nepal 9.895285\n3 USA 11.524113\n4 Nepal 10.133226\n5 Indonesia 9.711389\n6 Russia 10.017597\n7 Nepal 9.204832\n8 Russia 8.436829\n9 Russia 10.579013\n10 Canada 7.984238\n11 Canada 9.407908\n12 Indonesia 9.047598\n13 China 9.193126\n14 India 8.524555\n15 China 10.398155\n16 India 6.926581\n17 China 10.104521\n18 Canada 10.178826\n19 India 12.006973\n20 Canada 10.371956"
},
{
"code": null,
"e": 2121,
"s": 2088,
"text": "Creating boxplot for countries −"
},
{
"code": null,
"e": 2151,
"s": 2121,
"text": "boxplot(df$Rate~df$Countries)"
},
{
"code": null,
"e": 2237,
"s": 2151,
"text": "Creating boxplot for countries by changing the printing direction of country’s name −"
},
{
"code": null,
"e": 2281,
"s": 2237,
"text": "boxplot(df$Rate~df$Countries,las=2,xlab=\"\")"
}
]
|
Data Types in Go - GeeksforGeeks | 07 Mar, 2022
Data types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows:
Basic type: Numbers, strings, and booleans come under this category.Aggregate type: Array and structs come under this category.Reference type: Pointers, slices, maps, functions, and channels come under this category.Interface type
Basic type: Numbers, strings, and booleans come under this category.
Aggregate type: Array and structs come under this category.
Reference type: Pointers, slices, maps, functions, and channels come under this category.
Interface type
Here, we will discuss Basic Data Types in the Go language. The Basic Data Types are further categorized into three subcategories which are:
Numbers
Booleans
Strings
In Go language, numbers are divided into three sub-categories that are:
Integers: In Go language, both signed and unsigned integers are available in four different sizes as shown in the below table. The signed int is represented by int and the unsigned integer is represented by uint.
Data Type
Description
Example:
Go
// Go program to illustrate// the use of integerspackage mainimport "fmt" func main() { // Using 8-bit unsigned int var X uint8 = 225 fmt.Println(X, X-3) // Using 16-bit signed int var Y int16 = 32767 fmt.Println(Y+2, Y-2)}
Output:
225 222
-32767 32765
Floating-Point Numbers: In Go language, floating-point numbers are divided into two categories as shown in the below table:
Description
Example:
Go
// Go program to illustrate// the use of floating-point// numberspackage mainimport "fmt" func main() { a := 20.45 b := 34.89 // Subtraction of two // floating-point number c := b-a // Display the result fmt.Printf("Result is: %f", c) // Display the type of c variable fmt.Printf("\nThe type of c is : %T", c) }
Output:
Result is: 14.440000
The type of c is : float64
Complex Numbers: The complex numbers are divided into two parts are shown in the below table. float32 and float64 are also part of these complex numbers. The in-built function creates a complex number from its imaginary and real part and in-built imaginary and real function extract those parts.
Description
Example:
Go
// Go program to illustrate// the use of complex numberspackage mainimport "fmt" func main() { var a complex128 = complex(6, 2) var b complex64 = complex(9, 2) fmt.Println(a) fmt.Println(b) // Display the type fmt.Printf("The type of a is %T and "+ "the type of b is %T", a, b)}
Output:
(6+2i)
(9+2i)
The type of a is complex128 and the type of b is complex64
The boolean data type represents only one bit of information either true or false. The values of type boolean are not converted implicitly or explicitly to any other type.
Example:
Go
// Go program to illustrate// the use of booleanspackage mainimport "fmt" func main() { // variables str1 := "GeeksforGeeks" str2:= "geeksForgeeks" str3:= "GeeksforGeeks" result1:= str1 == str2 result2:= str1 == str3 // Display the result fmt.Println( result1) fmt.Println( result2) // Display the type of // result1 and result2 fmt.Printf("The type of result1 is %T and "+ "the type of result2 is %T", result1, result2) }
Output:
false
true
The type of result1 is bool and the type of result2 is bool
The string data type represents a sequence of Unicode code points. Or in other words, we can say a string is a sequence of immutable bytes, means once a string is created you cannot change that string. A string may contain arbitrary data, including bytes with zero value in the human-readable form.
Example:
Go
// Go program to illustrate// the use of stringspackage mainimport "fmt" func main() { // str variable which stores strings str := "GeeksforGeeks" // Display the length of the string fmt.Printf("Length of the string is:%d", len(str)) // Display the string fmt.Printf("\nString is: %s", str) // Display the type of str variable fmt.Printf("\nType of str is: %T", str)}
Output:
Length of the string is:13
String is: GeeksforGeeks
Type of str is: string
sudipghimire533
utkarshsinghskt
seanbecker15
Go-Basics
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
Time Formatting in Golang
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
How to convert a string in lower case in Golang?
How to compare times in Golang?
Inheritance in GoLang | [
{
"code": null,
"e": 24906,
"s": 24878,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 25056,
"s": 24906,
"text": "Data types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows:"
},
{
"code": null,
"e": 25287,
"s": 25056,
"text": "Basic type: Numbers, strings, and booleans come under this category.Aggregate type: Array and structs come under this category.Reference type: Pointers, slices, maps, functions, and channels come under this category.Interface type"
},
{
"code": null,
"e": 25356,
"s": 25287,
"text": "Basic type: Numbers, strings, and booleans come under this category."
},
{
"code": null,
"e": 25416,
"s": 25356,
"text": "Aggregate type: Array and structs come under this category."
},
{
"code": null,
"e": 25506,
"s": 25416,
"text": "Reference type: Pointers, slices, maps, functions, and channels come under this category."
},
{
"code": null,
"e": 25521,
"s": 25506,
"text": "Interface type"
},
{
"code": null,
"e": 25662,
"s": 25521,
"text": "Here, we will discuss Basic Data Types in the Go language. The Basic Data Types are further categorized into three subcategories which are: "
},
{
"code": null,
"e": 25670,
"s": 25662,
"text": "Numbers"
},
{
"code": null,
"e": 25679,
"s": 25670,
"text": "Booleans"
},
{
"code": null,
"e": 25687,
"s": 25679,
"text": "Strings"
},
{
"code": null,
"e": 25759,
"s": 25687,
"text": "In Go language, numbers are divided into three sub-categories that are:"
},
{
"code": null,
"e": 25972,
"s": 25759,
"text": "Integers: In Go language, both signed and unsigned integers are available in four different sizes as shown in the below table. The signed int is represented by int and the unsigned integer is represented by uint."
},
{
"code": null,
"e": 25982,
"s": 25972,
"text": "Data Type"
},
{
"code": null,
"e": 25994,
"s": 25982,
"text": "Description"
},
{
"code": null,
"e": 26003,
"s": 25994,
"text": "Example:"
},
{
"code": null,
"e": 26006,
"s": 26003,
"text": "Go"
},
{
"code": "// Go program to illustrate// the use of integerspackage mainimport \"fmt\" func main() { // Using 8-bit unsigned int var X uint8 = 225 fmt.Println(X, X-3) // Using 16-bit signed int var Y int16 = 32767 fmt.Println(Y+2, Y-2)}",
"e": 26265,
"s": 26006,
"text": null
},
{
"code": null,
"e": 26274,
"s": 26265,
"text": "Output: "
},
{
"code": null,
"e": 26295,
"s": 26274,
"text": "225 222\n-32767 32765"
},
{
"code": null,
"e": 26419,
"s": 26295,
"text": "Floating-Point Numbers: In Go language, floating-point numbers are divided into two categories as shown in the below table:"
},
{
"code": null,
"e": 26431,
"s": 26419,
"text": "Description"
},
{
"code": null,
"e": 26440,
"s": 26431,
"text": "Example:"
},
{
"code": null,
"e": 26443,
"s": 26440,
"text": "Go"
},
{
"code": "// Go program to illustrate// the use of floating-point// numberspackage mainimport \"fmt\" func main() { a := 20.45 b := 34.89 // Subtraction of two // floating-point number c := b-a // Display the result fmt.Printf(\"Result is: %f\", c) // Display the type of c variable fmt.Printf(\"\\nThe type of c is : %T\", c) }",
"e": 26804,
"s": 26443,
"text": null
},
{
"code": null,
"e": 26813,
"s": 26804,
"text": "Output: "
},
{
"code": null,
"e": 26861,
"s": 26813,
"text": "Result is: 14.440000\nThe type of c is : float64"
},
{
"code": null,
"e": 27157,
"s": 26861,
"text": "Complex Numbers: The complex numbers are divided into two parts are shown in the below table. float32 and float64 are also part of these complex numbers. The in-built function creates a complex number from its imaginary and real part and in-built imaginary and real function extract those parts."
},
{
"code": null,
"e": 27169,
"s": 27157,
"text": "Description"
},
{
"code": null,
"e": 27178,
"s": 27169,
"text": "Example:"
},
{
"code": null,
"e": 27181,
"s": 27178,
"text": "Go"
},
{
"code": "// Go program to illustrate// the use of complex numberspackage mainimport \"fmt\" func main() { var a complex128 = complex(6, 2) var b complex64 = complex(9, 2) fmt.Println(a) fmt.Println(b) // Display the type fmt.Printf(\"The type of a is %T and \"+ \"the type of b is %T\", a, b)}",
"e": 27491,
"s": 27181,
"text": null
},
{
"code": null,
"e": 27500,
"s": 27491,
"text": "Output: "
},
{
"code": null,
"e": 27573,
"s": 27500,
"text": "(6+2i)\n(9+2i)\nThe type of a is complex128 and the type of b is complex64"
},
{
"code": null,
"e": 27746,
"s": 27573,
"text": "The boolean data type represents only one bit of information either true or false. The values of type boolean are not converted implicitly or explicitly to any other type. "
},
{
"code": null,
"e": 27756,
"s": 27746,
"text": "Example: "
},
{
"code": null,
"e": 27759,
"s": 27756,
"text": "Go"
},
{
"code": "// Go program to illustrate// the use of booleanspackage mainimport \"fmt\" func main() { // variables str1 := \"GeeksforGeeks\" str2:= \"geeksForgeeks\" str3:= \"GeeksforGeeks\" result1:= str1 == str2 result2:= str1 == str3 // Display the result fmt.Println( result1) fmt.Println( result2) // Display the type of // result1 and result2 fmt.Printf(\"The type of result1 is %T and \"+ \"the type of result2 is %T\", result1, result2) }",
"e": 28269,
"s": 27759,
"text": null
},
{
"code": null,
"e": 28277,
"s": 28269,
"text": "Output:"
},
{
"code": null,
"e": 28348,
"s": 28277,
"text": "false\ntrue\nThe type of result1 is bool and the type of result2 is bool"
},
{
"code": null,
"e": 28647,
"s": 28348,
"text": "The string data type represents a sequence of Unicode code points. Or in other words, we can say a string is a sequence of immutable bytes, means once a string is created you cannot change that string. A string may contain arbitrary data, including bytes with zero value in the human-readable form."
},
{
"code": null,
"e": 28657,
"s": 28647,
"text": "Example: "
},
{
"code": null,
"e": 28660,
"s": 28657,
"text": "Go"
},
{
"code": "// Go program to illustrate// the use of stringspackage mainimport \"fmt\" func main() { // str variable which stores strings str := \"GeeksforGeeks\" // Display the length of the string fmt.Printf(\"Length of the string is:%d\", len(str)) // Display the string fmt.Printf(\"\\nString is: %s\", str) // Display the type of str variable fmt.Printf(\"\\nType of str is: %T\", str)}",
"e": 29095,
"s": 28660,
"text": null
},
{
"code": null,
"e": 29104,
"s": 29095,
"text": "Output: "
},
{
"code": null,
"e": 29179,
"s": 29104,
"text": "Length of the string is:13\nString is: GeeksforGeeks\nType of str is: string"
},
{
"code": null,
"e": 29197,
"s": 29181,
"text": "sudipghimire533"
},
{
"code": null,
"e": 29213,
"s": 29197,
"text": "utkarshsinghskt"
},
{
"code": null,
"e": 29226,
"s": 29213,
"text": "seanbecker15"
},
{
"code": null,
"e": 29236,
"s": 29226,
"text": "Go-Basics"
},
{
"code": null,
"e": 29243,
"s": 29236,
"text": "Golang"
},
{
"code": null,
"e": 29255,
"s": 29243,
"text": "Go Language"
},
{
"code": null,
"e": 29353,
"s": 29255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29405,
"s": 29353,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 29451,
"s": 29405,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 29477,
"s": 29451,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 29527,
"s": 29477,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 29578,
"s": 29527,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 29625,
"s": 29578,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 29637,
"s": 29625,
"text": "Golang Maps"
},
{
"code": null,
"e": 29686,
"s": 29637,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 29718,
"s": 29686,
"text": "How to compare times in Golang?"
}
]
|
MATLAB - Butterworth Lowpass Filter in Image Processing - GeeksforGeeks | 10 May, 2020
In the field of Image Processing, Butterworth Lowpass Filter (BLPF) is used for image smoothing in the frequency domain. It removes high-frequency noise from a digital image and preserves low-frequency components. The transfer function of BLPF of order is defined as-Where,
is a positive constant. BLPF passes all the frequencies less than value without attenuation and cuts off all the frequencies greater than it.
This is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed as cutoff frequency. But instead of making a sharp cut-off (like, Ideal Lowpass Filter (ILPF)), it introduces a smooth transition from 1 to 0 to reduce ringing artifacts.
is the Euclidean Distance from any point (u, v) to the origin of the frequency plane, i.e,
Approach:Step 1: Input – Read an imageStep 2: Saving the size of the input image in pixelsStep 3: Get the Fourier Transform of the input_imageStep 4: Assign the order and cut-off frequency Step 5: Designing filter: Butterworth Low Pass FilterStep 6: Convolution between the Fourier Transformed input image and the filtering maskStep 7: Take Inverse Fourier Transform of the convoluted imageStep 8: Display the resultant image as output
Implementation in MATLAB:
% MATLAB Code | Butterworth Low Pass Filter % Reading input image : input_imageinput_image = imread('[name of input image file].[file format]'); % Saving the size of the input_image in pixels-% M : no of rows (height of the image)% N : no of columns (width of the image)[M, N] = size(input_image); % Getting Fourier Transform of the input_image% using MATLAB library function fft2 (2D fast fourier transform)FT_img = fft2(double(input_image)); % Assign the order valuen = 2; % one can change this value accordingly % Assign Cut-off FrequencyD0 = 20; % one can change this value accordingly % Designing filteru = 0:(M-1);v = 0:(N-1);idx = find(u > M/2);u(idx) = u(idx) - M;idy = find(v > N/2);v(idy) = v(idy) - N; % MATLAB library function meshgrid(v, u) returns % 2D grid which contains the coordinates of vectors % v and u. Matrix V with each row is a copy of v % and matrix U with each column is a copy of u [V, U] = meshgrid(v, u); % Calculating Euclidean DistanceD = sqrt(U.^2 + V.^2); % determining the filtering maskH = 1./(1 + (D./D0).^(2*n)); % Convolution between the Fourier Transformed % image and the maskG = H.*FT_img; % Getting the resultant image by Inverse Fourier Transform % of the convoluted image using MATLAB library function % ifft2 (2D inverse fast fourier transform) output_image = real(ifft2(double(G))); % Displaying Input Image and Output Image subplot(2, 1, 1), imshow(input_image), subplot(2, 1, 2), imshow(output_image, [ ]);
Input Image –
Output:
Note: A Butterworth filter of order 1 has no ringing artifact. Generally ringing is imperceptible in filters of order 2. But it can become a significant factor in filters of a higher order. For a specific cut-off frequency, ringing increases with an increase in the filter order.
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Decision Tree
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
Reinforcement learning
Decision Tree Introduction with example
ML | Underfitting and Overfitting
KDD Process in Data Mining
Clustering in Machine Learning | [
{
"code": null,
"e": 24798,
"s": 24770,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 25073,
"s": 24798,
"text": "In the field of Image Processing, Butterworth Lowpass Filter (BLPF) is used for image smoothing in the frequency domain. It removes high-frequency noise from a digital image and preserves low-frequency components. The transfer function of BLPF of order is defined as-Where,"
},
{
"code": null,
"e": 25217,
"s": 25073,
"text": " is a positive constant. BLPF passes all the frequencies less than value without attenuation and cuts off all the frequencies greater than it."
},
{
"code": null,
"e": 25473,
"s": 25217,
"text": "This is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed as cutoff frequency. But instead of making a sharp cut-off (like, Ideal Lowpass Filter (ILPF)), it introduces a smooth transition from 1 to 0 to reduce ringing artifacts."
},
{
"code": null,
"e": 25566,
"s": 25473,
"text": " is the Euclidean Distance from any point (u, v) to the origin of the frequency plane, i.e, "
},
{
"code": null,
"e": 26003,
"s": 25566,
"text": "Approach:Step 1: Input – Read an imageStep 2: Saving the size of the input image in pixelsStep 3: Get the Fourier Transform of the input_imageStep 4: Assign the order and cut-off frequency Step 5: Designing filter: Butterworth Low Pass FilterStep 6: Convolution between the Fourier Transformed input image and the filtering maskStep 7: Take Inverse Fourier Transform of the convoluted imageStep 8: Display the resultant image as output"
},
{
"code": null,
"e": 26029,
"s": 26003,
"text": "Implementation in MATLAB:"
},
{
"code": "% MATLAB Code | Butterworth Low Pass Filter % Reading input image : input_imageinput_image = imread('[name of input image file].[file format]'); % Saving the size of the input_image in pixels-% M : no of rows (height of the image)% N : no of columns (width of the image)[M, N] = size(input_image); % Getting Fourier Transform of the input_image% using MATLAB library function fft2 (2D fast fourier transform)FT_img = fft2(double(input_image)); % Assign the order valuen = 2; % one can change this value accordingly % Assign Cut-off FrequencyD0 = 20; % one can change this value accordingly % Designing filteru = 0:(M-1);v = 0:(N-1);idx = find(u > M/2);u(idx) = u(idx) - M;idy = find(v > N/2);v(idy) = v(idy) - N; % MATLAB library function meshgrid(v, u) returns % 2D grid which contains the coordinates of vectors % v and u. Matrix V with each row is a copy of v % and matrix U with each column is a copy of u [V, U] = meshgrid(v, u); % Calculating Euclidean DistanceD = sqrt(U.^2 + V.^2); % determining the filtering maskH = 1./(1 + (D./D0).^(2*n)); % Convolution between the Fourier Transformed % image and the maskG = H.*FT_img; % Getting the resultant image by Inverse Fourier Transform % of the convoluted image using MATLAB library function % ifft2 (2D inverse fast fourier transform) output_image = real(ifft2(double(G))); % Displaying Input Image and Output Image subplot(2, 1, 1), imshow(input_image), subplot(2, 1, 2), imshow(output_image, [ ]);",
"e": 27507,
"s": 26029,
"text": null
},
{
"code": null,
"e": 27521,
"s": 27507,
"text": "Input Image –"
},
{
"code": null,
"e": 27529,
"s": 27521,
"text": "Output:"
},
{
"code": null,
"e": 27809,
"s": 27529,
"text": "Note: A Butterworth filter of order 1 has no ringing artifact. Generally ringing is imperceptible in filters of order 2. But it can become a significant factor in filters of a higher order. For a specific cut-off frequency, ringing increases with an increase in the filter order."
},
{
"code": null,
"e": 27826,
"s": 27809,
"text": "Image-Processing"
},
{
"code": null,
"e": 27833,
"s": 27826,
"text": "MATLAB"
},
{
"code": null,
"e": 27859,
"s": 27833,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27957,
"s": 27859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27966,
"s": 27957,
"text": "Comments"
},
{
"code": null,
"e": 27979,
"s": 27966,
"text": "Old Comments"
},
{
"code": null,
"e": 28002,
"s": 27979,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28016,
"s": 28002,
"text": "Decision Tree"
},
{
"code": null,
"e": 28060,
"s": 28016,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 28083,
"s": 28060,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 28121,
"s": 28083,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 28144,
"s": 28121,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 28184,
"s": 28144,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 28218,
"s": 28184,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 28245,
"s": 28218,
"text": "KDD Process in Data Mining"
}
]
|
What does the Double Star operator mean in Python? | For numeric data types double asterisk (**) is defined as exponentiation operator
>>> a=10; b=2
>>> a**b
100
>>> a=1.5; b=2.5
>>> a**b
2.7556759606310752
>>> a=3+2j
>>> b=3+5j
>>> a**b
(-0.7851059645317211+2.350232331971346j)
In a function definition, argument with double asterisks as prefix helps in sending multiple keyword arguments to it from calling environment
>>> def function(**arg):
for i in arg:
print (i,arg[i])
>>> function(a=1, b=2, c=3, d=4)
a 1
b 2
c 3
d 4 | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "For numeric data types double asterisk (**) is defined as exponentiation operator"
},
{
"code": null,
"e": 1288,
"s": 1144,
"text": ">>> a=10; b=2\n>>> a**b\n100\n>>> a=1.5; b=2.5\n>>> a**b\n2.7556759606310752\n>>> a=3+2j\n>>> b=3+5j\n>>> a**b\n(-0.7851059645317211+2.350232331971346j)"
},
{
"code": null,
"e": 1430,
"s": 1288,
"text": "In a function definition, argument with double asterisks as prefix helps in sending multiple keyword arguments to it from calling environment"
},
{
"code": null,
"e": 1546,
"s": 1430,
"text": ">>> def function(**arg):\n for i in arg:\n print (i,arg[i])\n\n>>> function(a=1, b=2, c=3, d=4)\na 1\nb 2\nc 3\nd 4"
}
]
|
How do I create an automatically updating GUI using Tkinter? | Using Tkinter, we can create GUI which can be configured for auto-updation. For
this purpose, we will create GUI-based clocks that will automatically get refreshed
when the time changes. We will display the clock along with the day and TimeZone.
First, we will import the tkinter library in the notebook, then we will create a function which creates instances of current time and day using the “strftime” function.
#Import the tkinter library
from tkinter import *
import time
#Create an instance of the canvas
win = Tk()
#Select the title of the window
win.title("tutorialspoint.com")
#Define the geometry of the window
win.geometry("600x400")
#Define the clock which
def clock():
hh= time.strftime("%I")
mm= time.strftime("%M")
ss= time.strftime("%S")
day=time.strftime("%A")
ap=time.strftime("%p")
time_zone= time.strftime("%Z")
my_lab.config(text= hh + ":" + mm +":" + ss)
my_lab.after(1000,clock)
my_lab1.config(text=time_zone+" "+ day)
#Update the Time
def updateTime():
my_lab.config(text= "New Text")
#Creating the label with text property of the clock
my_lab= Label(win,text= "",font=("sans-serif", 56), fg= "red")
my_lab.pack(pady=20)
my_lab1= Label(win, text= "", font=("Helvetica",20), fg= "blue")
my_lab1.pack(pady= 10)
#Calling the clock function
clock()
#Keep Running the window
win.mainloop()
Running the above code will create an automatically updated GUI Application in the window. | [
{
"code": null,
"e": 1308,
"s": 1062,
"text": "Using Tkinter, we can create GUI which can be configured for auto-updation. For\nthis purpose, we will create GUI-based clocks that will automatically get refreshed\nwhen the time changes. We will display the clock along with the day and TimeZone."
},
{
"code": null,
"e": 1477,
"s": 1308,
"text": "First, we will import the tkinter library in the notebook, then we will create a function which creates instances of current time and day using the “strftime” function."
},
{
"code": null,
"e": 2407,
"s": 1477,
"text": "#Import the tkinter library\nfrom tkinter import *\nimport time\n#Create an instance of the canvas\nwin = Tk()\n\n#Select the title of the window\nwin.title(\"tutorialspoint.com\")\n\n#Define the geometry of the window\nwin.geometry(\"600x400\")\n#Define the clock which\ndef clock():\n hh= time.strftime(\"%I\")\n mm= time.strftime(\"%M\")\n ss= time.strftime(\"%S\")\n day=time.strftime(\"%A\")\n ap=time.strftime(\"%p\")\n time_zone= time.strftime(\"%Z\")\n my_lab.config(text= hh + \":\" + mm +\":\" + ss)\n my_lab.after(1000,clock)\n\n my_lab1.config(text=time_zone+\" \"+ day)\n#Update the Time\ndef updateTime():\n my_lab.config(text= \"New Text\")\n\n#Creating the label with text property of the clock\nmy_lab= Label(win,text= \"\",font=(\"sans-serif\", 56), fg= \"red\")\nmy_lab.pack(pady=20)\nmy_lab1= Label(win, text= \"\", font=(\"Helvetica\",20), fg= \"blue\")\nmy_lab1.pack(pady= 10)\n\n#Calling the clock function\nclock()\n#Keep Running the window\n\nwin.mainloop()"
},
{
"code": null,
"e": 2498,
"s": 2407,
"text": "Running the above code will create an automatically updated GUI Application in the window."
}
]
|
Count ways to reach Nth Stairs by taking 1 and 2 steps with exactly one 3 step - GeeksforGeeks | 05 Jul, 2021
Given a number N which denotes the number of stairs, the task is to reach the Nth stair by taking 1, 2 steps any number of times and taking a step of 3 exactly once. Examples:
Input: N = 4 Output: 2 Explanation: Since a step of 3 has to be taken compulsorily and only once, There are only two possible ways: (1, 3) or (3, 1)Input: N = 5 Output: 5 Explanation: Since a step of 3 has to be taken compulsorily and only once, There are only 5 possible ways: (1, 1, 3), (1, 3, 1), (3, 1, 1), (2, 3), (3, 2)
Approach: This problem can be solved using Dynamic Programming. To Reach Nth stair the person should be on (N – 1)th, (N – 2)th or (N – 3)th. So, To reach Nth stair from the base Reach (N – 1)th stair which includes exact only one step of 3, Reach (N – 2)th step with the steps which includes exactly one step of 3 and Reach the (N – 3)th step without taking any step of 3. So, The Recurrence Relation for this problem will be –
includes_3[i] = includes_3[i-1] + includes_3[i-2] + not_includes[i-3]
whereas, the Recurrence relation when the 3 number of steps at a time is not allowed is
not_includes[i] = not_includes[i – 1] + not_includes[i – 2]
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ implementation to find the number// the number of ways to reach Nth stair// by taking 1, 2 step at a time and// 3 Steps at a time exactly once. #include <iostream>using namespace std; // Function to find the number// the number of ways to reach Nth stairint number_of_ways(int n){ // Array including number // of ways that includes 3 int includes_3[n + 1] = {}; // Array including number of // ways that doesn't includes 3 int not_includes_3[n + 1] = {}; // Initially to reach 3 stairs by // taking 3 steps can be // reached by 1 way includes_3[3] = 1; not_includes_3[1] = 1; not_includes_3[2] = 2; not_includes_3[3] = 3; // Loop to find the number // the number of ways to reach Nth stair for (int i = 4; i <= n; i++) { includes_3[i] = includes_3[i - 1] + includes_3[i - 2] + not_includes_3[i - 3]; not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]; } return includes_3[n];} // Driver Codeint main(){ int n = 7; cout << number_of_ways(n); return 0;}
// Java implementation to find the number// the number of ways to reach Nth stair// by taking 1, 2 step at a time and// 3 Steps at a time exactly once.class GFG{ // Function to find the number// the number of ways to reach Nth stairstatic int number_of_ways(int n){ // Array including number // of ways that includes 3 int []includes_3 = new int[n + 1]; // Array including number of // ways that doesn't includes 3 int []not_includes_3 = new int[n + 1]; // Initially to reach 3 stairs by // taking 3 steps can be // reached by 1 way includes_3[3] = 1; not_includes_3[1] = 1; not_includes_3[2] = 2; not_includes_3[3] = 3; // Loop to find the number // the number of ways to reach Nth stair for (int i = 4; i <= n; i++) { includes_3[i] = includes_3[i - 1] + includes_3[i - 2] + not_includes_3[i - 3]; not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]; } return includes_3[n];} // Driver Codepublic static void main(String[] args){ int n = 7; System.out.print(number_of_ways(n));}} // This code is contributed by Rajput-Ji
# Python3 implementation to find the number# the number of ways to reach Nth stair# by taking 1, 2 step at a time and# 3 Steps at a time exactly once. # Function to find the number# the number of ways to reach Nth stairdef number_of_ways(n): # Array including number # of ways that includes 3 includes_3 = [0]*(n + 1) # Array including number of # ways that doesn't includes 3 not_includes_3 = [0] * (n + 1) # Initially to reach 3 stairs by # taking 3 steps can be # reached by 1 way includes_3[3] = 1 not_includes_3[1] = 1 not_includes_3[2] = 2 not_includes_3[3] = 3 # Loop to find the number # the number of ways to reach Nth stair for i in range(4, n + 1): includes_3[i] = includes_3[i - 1] + \ includes_3[i - 2] + \ not_includes_3[i - 3] not_includes_3[i] = not_includes_3[i - 1] + \ not_includes_3[i - 2] return includes_3[n] # Driver Coden = 7 print(number_of_ways(n)) # This code is contributed by mohit kumar 29
// C# implementation to find the number// the number of ways to reach Nth stair// by taking 1, 2 step at a time and// 3 Steps at a time exactly once.using System; class GFG{ // Function to find the number// the number of ways to reach Nth stairstatic int number_of_ways(int n){ // Array including number // of ways that includes 3 int []includes_3 = new int[n + 1]; // Array including number of // ways that doesn't includes 3 int []not_includes_3 = new int[n + 1]; // Initially to reach 3 stairs by // taking 3 steps can be // reached by 1 way includes_3[3] = 1; not_includes_3[1] = 1; not_includes_3[2] = 2; not_includes_3[3] = 3; // Loop to find the number // the number of ways to reach Nth stair for (int i = 4; i <= n; i++) { includes_3[i] = includes_3[i - 1] + includes_3[i - 2] + not_includes_3[i - 3]; not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]; } return includes_3[n];} // Driver Codepublic static void Main(String[] args){ int n = 7; Console.Write(number_of_ways(n));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation to find the number// the number of ways to reach Nth stair// by taking 1, 2 step at a time and// 3 Steps at a time exactly once. // Function to find the number// the number of ways to reach Nth stairfunction number_of_ways(n){ // Array including number // of ways that includes 3 let includes_3 = new Uint8Array(n + 1); // Array including number of // ways that doesn't includes 3 let not_includes_3 = new Uint8Array(n + 1); // Initially to reach 3 stairs by // taking 3 steps can be // reached by 1 way includes_3[3] = 1; not_includes_3[1] = 1; not_includes_3[2] = 2; not_includes_3[3] = 3; // Loop to find the number // the number of ways to reach Nth stair for (let i = 4; i <= n; i++) { includes_3[i] = includes_3[i - 1] + includes_3[i - 2] + not_includes_3[i - 3]; not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]; } return includes_3[n];} // Driver Code let n = 7; document.write(number_of_ways(n)); // This code is contributed by Surbhi Tyagi. </script>
20
Similar Article: Count ways to reach Nth Stair using 1, 2 or 3 steps at a time
mohit kumar 29
Rajput-Ji
princiraj1992
nidhi_biet
surbhityagi15
simranarora5sos
gulshankumarar231
combionatrics
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count All Palindrome Sub-Strings in a String | Set 1
Optimal Substructure Property in Dynamic Programming | DP-2
Maximum sum such that no two elements are adjacent
Min Cost Path | DP-6
Optimal Binary Search Tree | DP-24
Maximum Subarray Sum using Divide and Conquer algorithm
3 Different ways to print Fibonacci series in Java
Greedy approach vs Dynamic programming
How to solve a Dynamic Programming Problem ?
Binomial Coefficient | DP-9 | [
{
"code": null,
"e": 24698,
"s": 24670,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 24876,
"s": 24698,
"text": "Given a number N which denotes the number of stairs, the task is to reach the Nth stair by taking 1, 2 steps any number of times and taking a step of 3 exactly once. Examples: "
},
{
"code": null,
"e": 25204,
"s": 24876,
"text": "Input: N = 4 Output: 2 Explanation: Since a step of 3 has to be taken compulsorily and only once, There are only two possible ways: (1, 3) or (3, 1)Input: N = 5 Output: 5 Explanation: Since a step of 3 has to be taken compulsorily and only once, There are only 5 possible ways: (1, 1, 3), (1, 3, 1), (3, 1, 1), (2, 3), (3, 2) "
},
{
"code": null,
"e": 25637,
"s": 25206,
"text": "Approach: This problem can be solved using Dynamic Programming. To Reach Nth stair the person should be on (N – 1)th, (N – 2)th or (N – 3)th. So, To reach Nth stair from the base Reach (N – 1)th stair which includes exact only one step of 3, Reach (N – 2)th step with the steps which includes exactly one step of 3 and Reach the (N – 3)th step without taking any step of 3. So, The Recurrence Relation for this problem will be – "
},
{
"code": null,
"e": 25709,
"s": 25637,
"text": "includes_3[i] = includes_3[i-1] + includes_3[i-2] + not_includes[i-3] "
},
{
"code": null,
"e": 25799,
"s": 25709,
"text": "whereas, the Recurrence relation when the 3 number of steps at a time is not allowed is "
},
{
"code": null,
"e": 25861,
"s": 25799,
"text": "not_includes[i] = not_includes[i – 1] + not_includes[i – 2] "
},
{
"code": null,
"e": 25913,
"s": 25861,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 25917,
"s": 25913,
"text": "C++"
},
{
"code": null,
"e": 25922,
"s": 25917,
"text": "Java"
},
{
"code": null,
"e": 25930,
"s": 25922,
"text": "Python3"
},
{
"code": null,
"e": 25933,
"s": 25930,
"text": "C#"
},
{
"code": null,
"e": 25944,
"s": 25933,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the number// the number of ways to reach Nth stair// by taking 1, 2 step at a time and// 3 Steps at a time exactly once. #include <iostream>using namespace std; // Function to find the number// the number of ways to reach Nth stairint number_of_ways(int n){ // Array including number // of ways that includes 3 int includes_3[n + 1] = {}; // Array including number of // ways that doesn't includes 3 int not_includes_3[n + 1] = {}; // Initially to reach 3 stairs by // taking 3 steps can be // reached by 1 way includes_3[3] = 1; not_includes_3[1] = 1; not_includes_3[2] = 2; not_includes_3[3] = 3; // Loop to find the number // the number of ways to reach Nth stair for (int i = 4; i <= n; i++) { includes_3[i] = includes_3[i - 1] + includes_3[i - 2] + not_includes_3[i - 3]; not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]; } return includes_3[n];} // Driver Codeint main(){ int n = 7; cout << number_of_ways(n); return 0;}",
"e": 27023,
"s": 25944,
"text": null
},
{
"code": "// Java implementation to find the number// the number of ways to reach Nth stair// by taking 1, 2 step at a time and// 3 Steps at a time exactly once.class GFG{ // Function to find the number// the number of ways to reach Nth stairstatic int number_of_ways(int n){ // Array including number // of ways that includes 3 int []includes_3 = new int[n + 1]; // Array including number of // ways that doesn't includes 3 int []not_includes_3 = new int[n + 1]; // Initially to reach 3 stairs by // taking 3 steps can be // reached by 1 way includes_3[3] = 1; not_includes_3[1] = 1; not_includes_3[2] = 2; not_includes_3[3] = 3; // Loop to find the number // the number of ways to reach Nth stair for (int i = 4; i <= n; i++) { includes_3[i] = includes_3[i - 1] + includes_3[i - 2] + not_includes_3[i - 3]; not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]; } return includes_3[n];} // Driver Codepublic static void main(String[] args){ int n = 7; System.out.print(number_of_ways(n));}} // This code is contributed by Rajput-Ji",
"e": 28181,
"s": 27023,
"text": null
},
{
"code": "# Python3 implementation to find the number# the number of ways to reach Nth stair# by taking 1, 2 step at a time and# 3 Steps at a time exactly once. # Function to find the number# the number of ways to reach Nth stairdef number_of_ways(n): # Array including number # of ways that includes 3 includes_3 = [0]*(n + 1) # Array including number of # ways that doesn't includes 3 not_includes_3 = [0] * (n + 1) # Initially to reach 3 stairs by # taking 3 steps can be # reached by 1 way includes_3[3] = 1 not_includes_3[1] = 1 not_includes_3[2] = 2 not_includes_3[3] = 3 # Loop to find the number # the number of ways to reach Nth stair for i in range(4, n + 1): includes_3[i] = includes_3[i - 1] + \\ includes_3[i - 2] + \\ not_includes_3[i - 3] not_includes_3[i] = not_includes_3[i - 1] + \\ not_includes_3[i - 2] return includes_3[n] # Driver Coden = 7 print(number_of_ways(n)) # This code is contributed by mohit kumar 29",
"e": 29247,
"s": 28181,
"text": null
},
{
"code": "// C# implementation to find the number// the number of ways to reach Nth stair// by taking 1, 2 step at a time and// 3 Steps at a time exactly once.using System; class GFG{ // Function to find the number// the number of ways to reach Nth stairstatic int number_of_ways(int n){ // Array including number // of ways that includes 3 int []includes_3 = new int[n + 1]; // Array including number of // ways that doesn't includes 3 int []not_includes_3 = new int[n + 1]; // Initially to reach 3 stairs by // taking 3 steps can be // reached by 1 way includes_3[3] = 1; not_includes_3[1] = 1; not_includes_3[2] = 2; not_includes_3[3] = 3; // Loop to find the number // the number of ways to reach Nth stair for (int i = 4; i <= n; i++) { includes_3[i] = includes_3[i - 1] + includes_3[i - 2] + not_includes_3[i - 3]; not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]; } return includes_3[n];} // Driver Codepublic static void Main(String[] args){ int n = 7; Console.Write(number_of_ways(n));}} // This code is contributed by PrinciRaj1992",
"e": 30415,
"s": 29247,
"text": null
},
{
"code": "<script> // JavaScript implementation to find the number// the number of ways to reach Nth stair// by taking 1, 2 step at a time and// 3 Steps at a time exactly once. // Function to find the number// the number of ways to reach Nth stairfunction number_of_ways(n){ // Array including number // of ways that includes 3 let includes_3 = new Uint8Array(n + 1); // Array including number of // ways that doesn't includes 3 let not_includes_3 = new Uint8Array(n + 1); // Initially to reach 3 stairs by // taking 3 steps can be // reached by 1 way includes_3[3] = 1; not_includes_3[1] = 1; not_includes_3[2] = 2; not_includes_3[3] = 3; // Loop to find the number // the number of ways to reach Nth stair for (let i = 4; i <= n; i++) { includes_3[i] = includes_3[i - 1] + includes_3[i - 2] + not_includes_3[i - 3]; not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]; } return includes_3[n];} // Driver Code let n = 7; document.write(number_of_ways(n)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 31535,
"s": 30415,
"text": null
},
{
"code": null,
"e": 31538,
"s": 31535,
"text": "20"
},
{
"code": null,
"e": 31620,
"s": 31540,
"text": "Similar Article: Count ways to reach Nth Stair using 1, 2 or 3 steps at a time "
},
{
"code": null,
"e": 31635,
"s": 31620,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31645,
"s": 31635,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31659,
"s": 31645,
"text": "princiraj1992"
},
{
"code": null,
"e": 31670,
"s": 31659,
"text": "nidhi_biet"
},
{
"code": null,
"e": 31684,
"s": 31670,
"text": "surbhityagi15"
},
{
"code": null,
"e": 31700,
"s": 31684,
"text": "simranarora5sos"
},
{
"code": null,
"e": 31718,
"s": 31700,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 31732,
"s": 31718,
"text": "combionatrics"
},
{
"code": null,
"e": 31752,
"s": 31732,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31772,
"s": 31752,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 31870,
"s": 31772,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31923,
"s": 31870,
"text": "Count All Palindrome Sub-Strings in a String | Set 1"
},
{
"code": null,
"e": 31983,
"s": 31923,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 32034,
"s": 31983,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 32055,
"s": 32034,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 32090,
"s": 32055,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 32146,
"s": 32090,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 32197,
"s": 32146,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 32236,
"s": 32197,
"text": "Greedy approach vs Dynamic programming"
},
{
"code": null,
"e": 32281,
"s": 32236,
"text": "How to solve a Dynamic Programming Problem ?"
}
]
|
Difference between UInt16, UInt32 and UInt64 in C# - GeeksforGeeks | 26 May, 2020
UInt16: This Struct is used to represents 16-bit unsigned integer. The UInt16 can store only positive value only which ranges from 0 to 65535.
Example :
C#
// C# program to show the // UInt16 structusing System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { //printing minimum & maximum values Console.WriteLine("Minimum value of UInt16: " + UInt16.MinValue); Console.WriteLine("Maximum value of UInt16: " + UInt16.MaxValue); Console.WriteLine(); // Int16 array UInt16[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt16 i in arr1) { Console.WriteLine(i); } }}
Output:
Minimum value of UInt16: 0
Maximum value of UInt16: 65535
13
0
1
3
7
UInt32: This Struct is used to represents 32-bit unsigned integer. The UInt32 can store only positive value only which ranges from 0 to 4294967295.
Example :
C#
// C# program to show the // UInt32 structusing System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine("Minimum value of UInt32: " + UInt32.MinValue); Console.WriteLine("Maximum value of UInt32: " + UInt32.MaxValue); Console.WriteLine(); // Int32 array UInt32[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt32 i in arr1) { Console.WriteLine(i); } }}
Output:
Minimum value of UInt32: 0
Maximum value of UInt32: 4294967295
13
0
1
3
7
UInt64: This Struct is used to represents 64-bit unsigned integer. The UInt64 can store only positive value only which ranges from 0 to 18,446,744,073,709,551,615.
Example :
C#
// C# program to show the // UInt64 structusing System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine("Minimum value of UInt64: " + UInt64.MinValue); Console.WriteLine("Maximum value of UInt64: " + UInt64.MaxValue); Console.WriteLine(); // Int64 array UInt64[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt64 i in arr1) { Console.WriteLine(i); } }}
Output:
Minimum value of UInt64: 0
Maximum value of UInt64: 18446744073709551615
13
0
1
3
7
Difference between UInt16, UInt32 and UInt64 in C#
Sr.No
UINT16
UINT32
UINT64
1.
2.
3.
4.
5.
6.
Syntax to declare the UInt16:
UInt16 variable_name;
Syntax to declare the UInt32:
UInt32 variable_name;
Syntax to declare the UInt64:
UInt64 variable_name;
CSharp-UInt16-Struct
CSharp-UInt32-Struct
CSharp-UInt64-Struct
C#
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Introduction to .NET Framework
C# | Constructors
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between Black Box Testing vs White Box Testing | [
{
"code": null,
"e": 24564,
"s": 24536,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 24707,
"s": 24564,
"text": "UInt16: This Struct is used to represents 16-bit unsigned integer. The UInt16 can store only positive value only which ranges from 0 to 65535."
},
{
"code": null,
"e": 24717,
"s": 24707,
"text": "Example :"
},
{
"code": null,
"e": 24720,
"s": 24717,
"text": "C#"
},
{
"code": "// C# program to show the // UInt16 structusing System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { //printing minimum & maximum values Console.WriteLine(\"Minimum value of UInt16: \" + UInt16.MinValue); Console.WriteLine(\"Maximum value of UInt16: \" + UInt16.MaxValue); Console.WriteLine(); // Int16 array UInt16[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt16 i in arr1) { Console.WriteLine(i); } }}",
"e": 25321,
"s": 24720,
"text": null
},
{
"code": null,
"e": 25329,
"s": 25321,
"text": "Output:"
},
{
"code": null,
"e": 25400,
"s": 25329,
"text": "Minimum value of UInt16: 0\nMaximum value of UInt16: 65535\n\n13\n0\n1\n3\n7\n"
},
{
"code": null,
"e": 25548,
"s": 25400,
"text": "UInt32: This Struct is used to represents 32-bit unsigned integer. The UInt32 can store only positive value only which ranges from 0 to 4294967295."
},
{
"code": null,
"e": 25558,
"s": 25548,
"text": "Example :"
},
{
"code": null,
"e": 25561,
"s": 25558,
"text": "C#"
},
{
"code": "// C# program to show the // UInt32 structusing System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine(\"Minimum value of UInt32: \" + UInt32.MinValue); Console.WriteLine(\"Maximum value of UInt32: \" + UInt32.MaxValue); Console.WriteLine(); // Int32 array UInt32[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt32 i in arr1) { Console.WriteLine(i); } }}",
"e": 26163,
"s": 25561,
"text": null
},
{
"code": null,
"e": 26171,
"s": 26163,
"text": "Output:"
},
{
"code": null,
"e": 26247,
"s": 26171,
"text": "Minimum value of UInt32: 0\nMaximum value of UInt32: 4294967295\n\n13\n0\n1\n3\n7\n"
},
{
"code": null,
"e": 26411,
"s": 26247,
"text": "UInt64: This Struct is used to represents 64-bit unsigned integer. The UInt64 can store only positive value only which ranges from 0 to 18,446,744,073,709,551,615."
},
{
"code": null,
"e": 26421,
"s": 26411,
"text": "Example :"
},
{
"code": null,
"e": 26424,
"s": 26421,
"text": "C#"
},
{
"code": "// C# program to show the // UInt64 structusing System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine(\"Minimum value of UInt64: \" + UInt64.MinValue); Console.WriteLine(\"Maximum value of UInt64: \" + UInt64.MaxValue); Console.WriteLine(); // Int64 array UInt64[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt64 i in arr1) { Console.WriteLine(i); } }}",
"e": 27026,
"s": 26424,
"text": null
},
{
"code": null,
"e": 27034,
"s": 27026,
"text": "Output:"
},
{
"code": null,
"e": 27120,
"s": 27034,
"text": "Minimum value of UInt64: 0\nMaximum value of UInt64: 18446744073709551615\n\n13\n0\n1\n3\n7\n"
},
{
"code": null,
"e": 27171,
"s": 27120,
"text": "Difference between UInt16, UInt32 and UInt64 in C#"
},
{
"code": null,
"e": 27177,
"s": 27171,
"text": "Sr.No"
},
{
"code": null,
"e": 27184,
"s": 27177,
"text": "UINT16"
},
{
"code": null,
"e": 27191,
"s": 27184,
"text": "UINT32"
},
{
"code": null,
"e": 27198,
"s": 27191,
"text": "UINT64"
},
{
"code": null,
"e": 27201,
"s": 27198,
"text": "1."
},
{
"code": null,
"e": 27204,
"s": 27201,
"text": "2."
},
{
"code": null,
"e": 27207,
"s": 27204,
"text": "3."
},
{
"code": null,
"e": 27210,
"s": 27207,
"text": "4."
},
{
"code": null,
"e": 27213,
"s": 27210,
"text": "5."
},
{
"code": null,
"e": 27217,
"s": 27213,
"text": " 6."
},
{
"code": null,
"e": 27248,
"s": 27217,
"text": " Syntax to declare the UInt16:"
},
{
"code": null,
"e": 27271,
"s": 27248,
"text": "UInt16 variable_name;\n"
},
{
"code": null,
"e": 27302,
"s": 27271,
"text": " Syntax to declare the UInt32:"
},
{
"code": null,
"e": 27325,
"s": 27302,
"text": "UInt32 variable_name;\n"
},
{
"code": null,
"e": 27356,
"s": 27325,
"text": " Syntax to declare the UInt64:"
},
{
"code": null,
"e": 27379,
"s": 27356,
"text": "UInt64 variable_name;\n"
},
{
"code": null,
"e": 27400,
"s": 27379,
"text": "CSharp-UInt16-Struct"
},
{
"code": null,
"e": 27421,
"s": 27400,
"text": "CSharp-UInt32-Struct"
},
{
"code": null,
"e": 27442,
"s": 27421,
"text": "CSharp-UInt64-Struct"
},
{
"code": null,
"e": 27445,
"s": 27442,
"text": "C#"
},
{
"code": null,
"e": 27464,
"s": 27445,
"text": "Difference Between"
},
{
"code": null,
"e": 27562,
"s": 27464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27571,
"s": 27562,
"text": "Comments"
},
{
"code": null,
"e": 27584,
"s": 27571,
"text": "Old Comments"
},
{
"code": null,
"e": 27612,
"s": 27584,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27635,
"s": 27612,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27657,
"s": 27635,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27688,
"s": 27657,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27706,
"s": 27688,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27737,
"s": 27706,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 27777,
"s": 27737,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 27809,
"s": 27777,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27870,
"s": 27809,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
How can I delete an element in Selenium using Python? | We can delete an element in Selenium webdriver using Python with the help of JavaScript Executor. Selenium is not capable of modifying the structure of DOM directly.
It has the feature of injecting JavaScript into the webpage and changing the DOM with the help execute_script method. The JavaScript command to be used is passed as a parameter to this method.
JavaScript command to delete an element is −
var l = document.getElementsByClassName("tp-logo")[0];
l.parentNode.removeChild(l);
The above script is to be passed as a parameter to the execute_script method.
Let us try to remove the highlighted logo from the below page −
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#implicit wait
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#delete element with JavaScript Executor
driver.execute_script("""
var l = document.getElementsByClassName("tp-logo")[0];
l.parentNode.removeChild(l);
""") | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "We can delete an element in Selenium webdriver using Python with the help of JavaScript Executor. Selenium is not capable of modifying the structure of DOM directly."
},
{
"code": null,
"e": 1421,
"s": 1228,
"text": "It has the feature of injecting JavaScript into the webpage and changing the DOM with the help execute_script method. The JavaScript command to be used is passed as a parameter to this method."
},
{
"code": null,
"e": 1466,
"s": 1421,
"text": "JavaScript command to delete an element is −"
},
{
"code": null,
"e": 1550,
"s": 1466,
"text": "var l = document.getElementsByClassName(\"tp-logo\")[0];\nl.parentNode.removeChild(l);"
},
{
"code": null,
"e": 1628,
"s": 1550,
"text": "The above script is to be passed as a parameter to the execute_script method."
},
{
"code": null,
"e": 1692,
"s": 1628,
"text": "Let us try to remove the highlighted logo from the below page −"
},
{
"code": null,
"e": 2145,
"s": 1692,
"text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n#implicit wait\ndriver.implicitly_wait(0.5)\n#maximize browser\ndriver.maximize_window()\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#delete element with JavaScript Executor\ndriver.execute_script(\"\"\"\n var l = document.getElementsByClassName(\"tp-logo\")[0];\n l.parentNode.removeChild(l);\n\"\"\")"
}
]
|
Node.js Child Process - GeeksforGeeks | 10 Jul, 2020
Node.js is a web development framework that offers a variety of modules to work with. Usually, Node.js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system.
The following are the four different ways to create a child process in Node.js:
spawn() method
fork() method
exec() method
execFile() method
Above mentioned ways are explained below:
spawn() method: This method spawns a new process using the given command and the command line arguments in args. The ChildProcess instance implements EventEmitterAPI which enables us to register handlers for events on child object directly. Some events that can be registered for handling with the ChildProcess are exit, disconnect, error, close and message.Syntax:
child_process.spawn(command[, args][, options])
Parameters:
command: Accepts a string which is the command to run.
args: List of string arguments. Default value is an empty array.
options:shell: Accepts a boolean value. If true, runs command inside of a shell. Different shell can be specified as a string. Default value is false which implies no shell. By default, spawn() does not create a shell to execute the command hence it is important to pass it as option while invoking the child process.Additional options such as cwd, env, argv0, stdio etc can be used as per requirement.
shell: Accepts a boolean value. If true, runs command inside of a shell. Different shell can be specified as a string. Default value is false which implies no shell. By default, spawn() does not create a shell to execute the command hence it is important to pass it as option while invoking the child process.
Additional options such as cwd, env, argv0, stdio etc can be used as per requirement.
Return Value: Returns a ChildProcess object.
Example:
const { spawn } = require('child_process');const child = spawn('dir', ['D:\Test'], {shell: true});child.stdout.on('data', (data) => { console.log(`stdout: ${data}`);}); child.stderr.on('data', (data) => { console.error(`stderr: ${data}`);}); child.on('close', (code) => { console.log(`child process exited with code ${code}`);});
Output:
fork() method: The child_process.fork() is a special case of child_process.spawn() where the parent and the child process can communicate with each other via send(). The fork() allows separation of computation-intensive tasks from the main event loop. Child processes are independent of the parent except the IPC communication channel established between them. Each process has its own memory, therefore invoking a large number of child processes can affect the performance of the application. The shell option is not supported by child_process.fork().
Syntax:
child_process.fork(modulePath[, args][, options])
Parameters:
modulePath: Accepts a string that specifies the module to run in the child.
args: List of string arguments.
options: cwd, detached, env, execPath, execArgv are some of the available options for this method.
Return Value: Returns a ChildProcess instance.
Example: Filename: fork.js
// Write Javascript code herevar cp = require('child_process'); var child = cp.fork(__dirname + '/sub.js'); child.on('message', function(m) { console.log('Parent process received:', m);}); child.send({ hello: 'from parent process' }); child.on('close', (code) => { console.log(`child process exited with code ${code}`);});
Filename: sub.js
process.on('message', function(m) { console.log('Child process received:', m);}); process.send({ hello: 'from child process' });
Output:
exec() method: This method creates a shell first and then executes the command.
Syntax:
child_process.exec(command[, options][, callback])
Parameters:
command: Accepts a string that specifies the command to run with space-separated arguments.
options: Some of the options available are cwd, env, encoding, shell, timeout etc
callback: The callback function is called when process terminates. The arguments to this function are error, stdout and stderr respectively.
Return Value: Returns an instance of ChildProcess.
Example:
const { exec } = require('child_process'); // Counts the number of directory in // current working directoryexec('dir | find /c /v ""', (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); return; } console.log(`stdout: No. of directories = ${stdout}`); if (stderr!= "") console.error(`stderr: ${stderr}`);});
Output:
execFile() method: The child_process.execFile() function is does not spawn a shell by default. It is slightly more efficient than child_process.exec() as the specified executable file is spawned directly as a new process.
Syntax:
child_process.execFile(file[, args][, options][, callback])
Parameters:
file: Accepts a string that specifies the name or path of the file to run.
args: List of string arguments.
options: Some of the options available are cwd, env, encoding, shell, timeout etc
callback: The callback function is called when process terminates. The arguments to this function are error, stdout and stderr respectively.
Return Value: Returns an instance of ChildProcess.
Example:
const { execFile } = require('child_process'); // Executes the exec.js fileconst child = execFile('node', ['exec.js'], (error, stdout, stderr) => { if (error) { throw error; } console.log(stdout);});
Output:
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Express.js express.Router() Function
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
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?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24832,
"s": 24804,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 25207,
"s": 24832,
"text": "Node.js is a web development framework that offers a variety of modules to work with. Usually, Node.js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system."
},
{
"code": null,
"e": 25287,
"s": 25207,
"text": "The following are the four different ways to create a child process in Node.js:"
},
{
"code": null,
"e": 25302,
"s": 25287,
"text": "spawn() method"
},
{
"code": null,
"e": 25316,
"s": 25302,
"text": "fork() method"
},
{
"code": null,
"e": 25330,
"s": 25316,
"text": "exec() method"
},
{
"code": null,
"e": 25348,
"s": 25330,
"text": "execFile() method"
},
{
"code": null,
"e": 25390,
"s": 25348,
"text": "Above mentioned ways are explained below:"
},
{
"code": null,
"e": 25756,
"s": 25390,
"text": "spawn() method: This method spawns a new process using the given command and the command line arguments in args. The ChildProcess instance implements EventEmitterAPI which enables us to register handlers for events on child object directly. Some events that can be registered for handling with the ChildProcess are exit, disconnect, error, close and message.Syntax:"
},
{
"code": null,
"e": 25804,
"s": 25756,
"text": "child_process.spawn(command[, args][, options])"
},
{
"code": null,
"e": 25816,
"s": 25804,
"text": "Parameters:"
},
{
"code": null,
"e": 25871,
"s": 25816,
"text": "command: Accepts a string which is the command to run."
},
{
"code": null,
"e": 25936,
"s": 25871,
"text": "args: List of string arguments. Default value is an empty array."
},
{
"code": null,
"e": 26339,
"s": 25936,
"text": "options:shell: Accepts a boolean value. If true, runs command inside of a shell. Different shell can be specified as a string. Default value is false which implies no shell. By default, spawn() does not create a shell to execute the command hence it is important to pass it as option while invoking the child process.Additional options such as cwd, env, argv0, stdio etc can be used as per requirement."
},
{
"code": null,
"e": 26649,
"s": 26339,
"text": "shell: Accepts a boolean value. If true, runs command inside of a shell. Different shell can be specified as a string. Default value is false which implies no shell. By default, spawn() does not create a shell to execute the command hence it is important to pass it as option while invoking the child process."
},
{
"code": null,
"e": 26735,
"s": 26649,
"text": "Additional options such as cwd, env, argv0, stdio etc can be used as per requirement."
},
{
"code": null,
"e": 26780,
"s": 26735,
"text": "Return Value: Returns a ChildProcess object."
},
{
"code": null,
"e": 26789,
"s": 26780,
"text": "Example:"
},
{
"code": "const { spawn } = require('child_process');const child = spawn('dir', ['D:\\Test'], {shell: true});child.stdout.on('data', (data) => { console.log(`stdout: ${data}`);}); child.stderr.on('data', (data) => { console.error(`stderr: ${data}`);}); child.on('close', (code) => { console.log(`child process exited with code ${code}`);});",
"e": 27124,
"s": 26789,
"text": null
},
{
"code": null,
"e": 27132,
"s": 27124,
"text": "Output:"
},
{
"code": null,
"e": 27685,
"s": 27132,
"text": "fork() method: The child_process.fork() is a special case of child_process.spawn() where the parent and the child process can communicate with each other via send(). The fork() allows separation of computation-intensive tasks from the main event loop. Child processes are independent of the parent except the IPC communication channel established between them. Each process has its own memory, therefore invoking a large number of child processes can affect the performance of the application. The shell option is not supported by child_process.fork()."
},
{
"code": null,
"e": 27693,
"s": 27685,
"text": "Syntax:"
},
{
"code": null,
"e": 27743,
"s": 27693,
"text": "child_process.fork(modulePath[, args][, options])"
},
{
"code": null,
"e": 27755,
"s": 27743,
"text": "Parameters:"
},
{
"code": null,
"e": 27831,
"s": 27755,
"text": "modulePath: Accepts a string that specifies the module to run in the child."
},
{
"code": null,
"e": 27863,
"s": 27831,
"text": "args: List of string arguments."
},
{
"code": null,
"e": 27962,
"s": 27863,
"text": "options: cwd, detached, env, execPath, execArgv are some of the available options for this method."
},
{
"code": null,
"e": 28009,
"s": 27962,
"text": "Return Value: Returns a ChildProcess instance."
},
{
"code": null,
"e": 28036,
"s": 28009,
"text": "Example: Filename: fork.js"
},
{
"code": "// Write Javascript code herevar cp = require('child_process'); var child = cp.fork(__dirname + '/sub.js'); child.on('message', function(m) { console.log('Parent process received:', m);}); child.send({ hello: 'from parent process' }); child.on('close', (code) => { console.log(`child process exited with code ${code}`);});",
"e": 28365,
"s": 28036,
"text": null
},
{
"code": null,
"e": 28382,
"s": 28365,
"text": "Filename: sub.js"
},
{
"code": "process.on('message', function(m) { console.log('Child process received:', m);}); process.send({ hello: 'from child process' });",
"e": 28513,
"s": 28382,
"text": null
},
{
"code": null,
"e": 28521,
"s": 28513,
"text": "Output:"
},
{
"code": null,
"e": 28601,
"s": 28521,
"text": "exec() method: This method creates a shell first and then executes the command."
},
{
"code": null,
"e": 28609,
"s": 28601,
"text": "Syntax:"
},
{
"code": null,
"e": 28660,
"s": 28609,
"text": "child_process.exec(command[, options][, callback])"
},
{
"code": null,
"e": 28672,
"s": 28660,
"text": "Parameters:"
},
{
"code": null,
"e": 28764,
"s": 28672,
"text": "command: Accepts a string that specifies the command to run with space-separated arguments."
},
{
"code": null,
"e": 28846,
"s": 28764,
"text": "options: Some of the options available are cwd, env, encoding, shell, timeout etc"
},
{
"code": null,
"e": 28987,
"s": 28846,
"text": "callback: The callback function is called when process terminates. The arguments to this function are error, stdout and stderr respectively."
},
{
"code": null,
"e": 29038,
"s": 28987,
"text": "Return Value: Returns an instance of ChildProcess."
},
{
"code": null,
"e": 29047,
"s": 29038,
"text": "Example:"
},
{
"code": "const { exec } = require('child_process'); // Counts the number of directory in // current working directoryexec('dir | find /c /v \"\"', (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); return; } console.log(`stdout: No. of directories = ${stdout}`); if (stderr!= \"\") console.error(`stderr: ${stderr}`);});",
"e": 29397,
"s": 29047,
"text": null
},
{
"code": null,
"e": 29405,
"s": 29397,
"text": "Output:"
},
{
"code": null,
"e": 29627,
"s": 29405,
"text": "execFile() method: The child_process.execFile() function is does not spawn a shell by default. It is slightly more efficient than child_process.exec() as the specified executable file is spawned directly as a new process."
},
{
"code": null,
"e": 29635,
"s": 29627,
"text": "Syntax:"
},
{
"code": null,
"e": 29695,
"s": 29635,
"text": "child_process.execFile(file[, args][, options][, callback])"
},
{
"code": null,
"e": 29707,
"s": 29695,
"text": "Parameters:"
},
{
"code": null,
"e": 29782,
"s": 29707,
"text": "file: Accepts a string that specifies the name or path of the file to run."
},
{
"code": null,
"e": 29814,
"s": 29782,
"text": "args: List of string arguments."
},
{
"code": null,
"e": 29896,
"s": 29814,
"text": "options: Some of the options available are cwd, env, encoding, shell, timeout etc"
},
{
"code": null,
"e": 30037,
"s": 29896,
"text": "callback: The callback function is called when process terminates. The arguments to this function are error, stdout and stderr respectively."
},
{
"code": null,
"e": 30088,
"s": 30037,
"text": "Return Value: Returns an instance of ChildProcess."
},
{
"code": null,
"e": 30097,
"s": 30088,
"text": "Example:"
},
{
"code": "const { execFile } = require('child_process'); // Executes the exec.js fileconst child = execFile('node', ['exec.js'], (error, stdout, stderr) => { if (error) { throw error; } console.log(stdout);});",
"e": 30312,
"s": 30097,
"text": null
},
{
"code": null,
"e": 30320,
"s": 30312,
"text": "Output:"
},
{
"code": null,
"e": 30335,
"s": 30320,
"text": "Node.js-Basics"
},
{
"code": null,
"e": 30342,
"s": 30335,
"text": "Picked"
},
{
"code": null,
"e": 30350,
"s": 30342,
"text": "Node.js"
},
{
"code": null,
"e": 30367,
"s": 30350,
"text": "Web Technologies"
},
{
"code": null,
"e": 30465,
"s": 30367,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30474,
"s": 30465,
"text": "Comments"
},
{
"code": null,
"e": 30487,
"s": 30474,
"text": "Old Comments"
},
{
"code": null,
"e": 30516,
"s": 30487,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 30546,
"s": 30516,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 30603,
"s": 30546,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 30640,
"s": 30603,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 30694,
"s": 30640,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 30736,
"s": 30694,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30798,
"s": 30736,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30841,
"s": 30798,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30891,
"s": 30841,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
C++ Program to Implement Priority Queue | The queue which is implemented as FIFO where insertions are done at one end (rear) and deletions are done from another end (front). The first element that entered is deleted first.
Queue operations are
EnQueue (int data): Insertion at rear end
EnQueue (int data): Insertion at rear end
int DeQueue(): Deletion from front end
int DeQueue(): Deletion from front end
But a priority queue doesn’t follow First-In-First-Out, but rather than each element has a priority based on the basis of urgency.
Items with the same priority are processed on First-In-First-Out service basis.
An item with higher priority is processed before other items with lower priority.
Begin
class Priority_Queue has following functions:
function insert() to insert items at priority queue with their priorities:
1) If queue is empty insert data from the left end of the queue.
2) If queue is having some nodes then insert the new node at the end of those nodes having priority
same with the new node and also before all the nodes having priority lesser than the
current priority of the new node.
function del() to delete items from queue.
If queue is completely empty, print underflow otherwise delete the front element and update front.
End
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
struct n // node declaration {
int p;
int info;
struct n *l;
};
class Priority_Queue {
private:
//Declare a front pointer f and initialize it to NULL.
n *f;
public:
Priority_Queue() //constructor {
f = NULL;
}
void insert(int i, int p) {
n *t, *q;
t = new n;
t->info = i;
t->p = p;
if (f == NULL || p < f->p) {
t->l= f;
f = t;
} else {
q = f;
while (q->l != NULL && q->l->p <= p)
q = q->l;
t->l = q->l;
q->l = t;
}
}
void del() {
n *t;
if(f == NULL) //if queue is null
cout<<"Queue Underflow\n";
else {
t = f;
cout<<"Deleted item is: "<<t->info<<endl;
f = f->l;
free(t);
}
}
void show() //print queue {
n *ptr;
ptr = f;
if (f == NULL)
cout<<"Queue is empty\n";
else {
cout<<"Queue is :\n";
cout<<"Priority Item\n";
while(ptr != NULL) {
cout<<ptr->p<<" "<<ptr->info<<endl;
ptr = ptr->l;
}
}
}
};
int main() {
int c, i, p;
Priority_Queue pq;
Do//perform switch opeartion {
cout<<"1.Insert\n";
cout<<"2.Delete\n";
cout<<"3.Display\n";
cout<<"4.Exit\n";
cout<<"Enter your choice : ";
cin>>c;
switch(c) {
case 1:
cout<<"Input the item value to be added in the queue : ";
cin>>i;
cout<<"Enter its priority : ";
cin>>p;
pq.insert(i, p);
break;
case 2:
pq.del();
break;
case 3:
pq.show();
break;
case 4:
break;
default:
cout<<"Wrong choice\n";
}
}
while(c != 4);
return 0;
}
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 1
Input the item value to be added in the queue : 7
Enter its priority : 2
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 1
Input the item value to be added in the queue : 6
Enter its priority : 1
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 1
Input the item value to be added in the queue : 3
Enter its priority : 3
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 1
Input the item value to be added in the queue : 4
Enter its priority : 3
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 3
Queue is :
Priority Item
1 6
2 7
3 3
3 4
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice : 4 | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "The queue which is implemented as FIFO where insertions are done at one end (rear) and deletions are done from another end (front). The first element that entered is deleted first."
},
{
"code": null,
"e": 1264,
"s": 1243,
"text": "Queue operations are"
},
{
"code": null,
"e": 1306,
"s": 1264,
"text": "EnQueue (int data): Insertion at rear end"
},
{
"code": null,
"e": 1348,
"s": 1306,
"text": "EnQueue (int data): Insertion at rear end"
},
{
"code": null,
"e": 1387,
"s": 1348,
"text": "int DeQueue(): Deletion from front end"
},
{
"code": null,
"e": 1426,
"s": 1387,
"text": "int DeQueue(): Deletion from front end"
},
{
"code": null,
"e": 1557,
"s": 1426,
"text": "But a priority queue doesn’t follow First-In-First-Out, but rather than each element has a priority based on the basis of urgency."
},
{
"code": null,
"e": 1637,
"s": 1557,
"text": "Items with the same priority are processed on First-In-First-Out service basis."
},
{
"code": null,
"e": 1719,
"s": 1637,
"text": "An item with higher priority is processed before other items with lower priority."
},
{
"code": null,
"e": 2321,
"s": 1719,
"text": "Begin\n class Priority_Queue has following functions:\n function insert() to insert items at priority queue with their priorities:\n 1) If queue is empty insert data from the left end of the queue.\n 2) If queue is having some nodes then insert the new node at the end of those nodes having priority\n same with the new node and also before all the nodes having priority lesser than the\n current priority of the new node.\n function del() to delete items from queue.\n If queue is completely empty, print underflow otherwise delete the front element and update front.\nEnd"
},
{
"code": null,
"e": 4408,
"s": 2321,
"text": "#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\nusing namespace std;\nstruct n // node declaration {\n int p;\n int info;\n struct n *l;\n};\nclass Priority_Queue {\n private:\n //Declare a front pointer f and initialize it to NULL.\n n *f;\n public:\n Priority_Queue() //constructor {\n f = NULL;\n }\n void insert(int i, int p) {\n n *t, *q;\n t = new n;\n t->info = i;\n t->p = p;\n if (f == NULL || p < f->p) {\n t->l= f;\n f = t;\n } else {\n q = f;\n while (q->l != NULL && q->l->p <= p)\n q = q->l;\n t->l = q->l;\n q->l = t;\n }\n }\n void del() {\n n *t;\n if(f == NULL) //if queue is null\n cout<<\"Queue Underflow\\n\";\n else {\n t = f;\n cout<<\"Deleted item is: \"<<t->info<<endl;\n f = f->l;\n free(t);\n }\n }\n void show() //print queue {\n n *ptr;\n ptr = f;\n if (f == NULL)\n cout<<\"Queue is empty\\n\";\n else {\n cout<<\"Queue is :\\n\";\n cout<<\"Priority Item\\n\";\n while(ptr != NULL) {\n cout<<ptr->p<<\" \"<<ptr->info<<endl;\n ptr = ptr->l;\n }\n }\n }\n};\nint main() {\n int c, i, p;\n Priority_Queue pq;\n Do//perform switch opeartion {\n cout<<\"1.Insert\\n\";\n cout<<\"2.Delete\\n\";\n cout<<\"3.Display\\n\";\n cout<<\"4.Exit\\n\";\n cout<<\"Enter your choice : \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Input the item value to be added in the queue : \";\n cin>>i;\n cout<<\"Enter its priority : \";\n cin>>p;\n pq.insert(i, p);\n break;\n case 2:\n pq.del();\n break;\n case 3:\n pq.show();\n break;\n case 4:\n break;\n default:\n cout<<\"Wrong choice\\n\";\n }\n }\n while(c != 4);\n return 0;\n}"
},
{
"code": null,
"e": 5083,
"s": 4408,
"text": "1.Insert\n2.Delete\n3.Display\n4.Exit\nEnter your choice : 1\nInput the item value to be added in the queue : 7\nEnter its priority : 2\n1.Insert\n2.Delete\n3.Display\n4.Exit\nEnter your choice : 1\nInput the item value to be added in the queue : 6\nEnter its priority : 1\n1.Insert\n2.Delete\n3.Display\n4.Exit\nEnter your choice : 1\nInput the item value to be added in the queue : 3\nEnter its priority : 3\n1.Insert\n2.Delete\n3.Display\n4.Exit\nEnter your choice : 1\nInput the item value to be added in the queue : 4\nEnter its priority : 3\n1.Insert\n2.Delete\n3.Display\n4.Exit\nEnter your choice : 3\nQueue is :\nPriority Item\n1 6\n2 7\n3 3\n3 4\n1.Insert\n2.Delete\n3.Display\n4.Exit\nEnter your choice : 4"
}
]
|
How to use Alert Component in ReactJS? - GeeksforGeeks | 05 Mar, 2021
Alerts are urgent interruptions, requiring acknowledgment, that inform the user about a situation. Material UI for React has this component available for us, and it is very easy to integrate. We can use Alert Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
npm install @material-ui/lab
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import MuiAlert from "@material-ui/lab/Alert"; function Alert(props) { return <MuiAlert elevation={6} variant="filled" {...props} />;} export default function App() { return ( <div> <h4>How to use Alert Component in ReactJS?</h4> <Alert severity="success">Sample Success Message</Alert> <Alert severity="error">Sample Error Message</Alert> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/dialogs/#alerts
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
ReactJS useNavigate() Hook
React-Router Hooks
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 25111,
"s": 24851,
"text": "Alerts are urgent interruptions, requiring acknowledgment, that inform the user about a situation. Material UI for React has this component available for us, and it is very easy to integrate. We can use Alert Component in ReactJS using the following approach."
},
{
"code": null,
"e": 25161,
"s": 25111,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 25225,
"s": 25161,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 25257,
"s": 25225,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 25357,
"s": 25257,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 25371,
"s": 25357,
"text": "cd foldername"
},
{
"code": null,
"e": 25480,
"s": 25371,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command."
},
{
"code": null,
"e": 25539,
"s": 25480,
"text": "npm install @material-ui/core\nnpm install @material-ui/lab"
},
{
"code": null,
"e": 25591,
"s": 25539,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 25609,
"s": 25591,
"text": "Project Structure"
},
{
"code": null,
"e": 25739,
"s": 25609,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 25746,
"s": 25739,
"text": "App.js"
},
{
"code": "import React from \"react\";import MuiAlert from \"@material-ui/lab/Alert\"; function Alert(props) { return <MuiAlert elevation={6} variant=\"filled\" {...props} />;} export default function App() { return ( <div> <h4>How to use Alert Component in ReactJS?</h4> <Alert severity=\"success\">Sample Success Message</Alert> <Alert severity=\"error\">Sample Error Message</Alert> </div> );}",
"e": 26168,
"s": 25746,
"text": null
},
{
"code": null,
"e": 26281,
"s": 26168,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 26291,
"s": 26281,
"text": "npm start"
},
{
"code": null,
"e": 26390,
"s": 26291,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 26452,
"s": 26390,
"text": "Reference: https://material-ui.com/components/dialogs/#alerts"
},
{
"code": null,
"e": 26464,
"s": 26452,
"text": "Material-UI"
},
{
"code": null,
"e": 26480,
"s": 26464,
"text": "React-Questions"
},
{
"code": null,
"e": 26488,
"s": 26480,
"text": "ReactJS"
},
{
"code": null,
"e": 26505,
"s": 26488,
"text": "Web Technologies"
},
{
"code": null,
"e": 26603,
"s": 26505,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26645,
"s": 26603,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 26680,
"s": 26645,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 26738,
"s": 26680,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 26765,
"s": 26738,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 26784,
"s": 26765,
"text": "React-Router Hooks"
},
{
"code": null,
"e": 26826,
"s": 26784,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26859,
"s": 26826,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26921,
"s": 26859,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26971,
"s": 26921,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
How to check Azure VM Power state using PowerShell? | To check if the VMs are running, deallocated, or stopped using PowerShell, we need to use the - Status parameter.
If you write only the Get-AzVM command to get the VM details, it won’t show up the Azure VM power status default.
To check the Azure VM Power Status,
Get-AzVM -status
The above command will show the Power State for all VMs for that particular subscription. For different subscriptions, you need to change the subscription and run this command.
To get the VM Power State for the specific ResourceGroup, use the ResourceGroup name parameter.
For example,
Get-AzVM -ResourceGroupName TestVMRG -Status
The above command will retrieve all VM Power states from the resource group TestVMRG.
For the specific VM Power state, you need to provide a particular VM name, as shown below.
Get-AzVM -VMName Win2k16vm1 -Status | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "To check if the VMs are running, deallocated, or stopped using PowerShell, we need to use the - Status parameter."
},
{
"code": null,
"e": 1290,
"s": 1176,
"text": "If you write only the Get-AzVM command to get the VM details, it won’t show up the Azure VM power status default."
},
{
"code": null,
"e": 1326,
"s": 1290,
"text": "To check the Azure VM Power Status,"
},
{
"code": null,
"e": 1343,
"s": 1326,
"text": "Get-AzVM -status"
},
{
"code": null,
"e": 1522,
"s": 1345,
"text": "The above command will show the Power State for all VMs for that particular subscription. For different subscriptions, you need to change the subscription and run this command."
},
{
"code": null,
"e": 1618,
"s": 1522,
"text": "To get the VM Power State for the specific ResourceGroup, use the ResourceGroup name parameter."
},
{
"code": null,
"e": 1631,
"s": 1618,
"text": "For example,"
},
{
"code": null,
"e": 1676,
"s": 1631,
"text": "Get-AzVM -ResourceGroupName TestVMRG -Status"
},
{
"code": null,
"e": 1762,
"s": 1676,
"text": "The above command will retrieve all VM Power states from the resource group TestVMRG."
},
{
"code": null,
"e": 1853,
"s": 1762,
"text": "For the specific VM Power state, you need to provide a particular VM name, as shown below."
},
{
"code": null,
"e": 1889,
"s": 1853,
"text": "Get-AzVM -VMName Win2k16vm1 -Status"
}
]
|
Gerrit - Push Your Change Set to Gerrit | You can submit the patches for review by using the git-review command. The change set can be pushed to Gerrit, by running the git review -R command as shown in the following screenshot.
The -R option informs git-review not to complete rebase before submitting git changes to Gerrit.
You can submit the code to other branch rather than the master, using the following command.
git review name_of_branch
It is also possible to submit the code to a different remote, using the following command.
git review -r name_of_remote
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2424,
"s": 2238,
"text": "You can submit the patches for review by using the git-review command. The change set can be pushed to Gerrit, by running the git review -R command as shown in the following screenshot."
},
{
"code": null,
"e": 2521,
"s": 2424,
"text": "The -R option informs git-review not to complete rebase before submitting git changes to Gerrit."
},
{
"code": null,
"e": 2614,
"s": 2521,
"text": "You can submit the code to other branch rather than the master, using the following command."
},
{
"code": null,
"e": 2641,
"s": 2614,
"text": "git review name_of_branch\n"
},
{
"code": null,
"e": 2732,
"s": 2641,
"text": "It is also possible to submit the code to a different remote, using the following command."
},
{
"code": null,
"e": 2762,
"s": 2732,
"text": "git review -r name_of_remote\n"
},
{
"code": null,
"e": 2769,
"s": 2762,
"text": " Print"
},
{
"code": null,
"e": 2780,
"s": 2769,
"text": " Add Notes"
}
]
|
Load a Large spaCy model on AWS Lambda | by Hironsan | Towards Data Science | spaCy is a useful tool that allows us to perform many natural language processing tasks. When integrating spaCy into an existing application, it is convenient to provide it as an API using AWS Lambda and API Gateway. However, due to Lambda’s limitations, it is hard to deploy large models.
In this article, I will show you how to deploy spaCy using the recently released feature to mount Elastic File System (EFS) on AWS Lambda. By using this feature, we can store a large size model to EFS and load it from Lambda functions. Specifically, it is possible to load data larger than the space available in Lambda’s/tmp (512MB).
The overall architecture is as follows. Lambda loads the spaCy package on Lambda Layers. EFS stores the spaCy models. Lambda then loads the models from EFS. For redundancy, four subnets are placed on two different availability zones.
Requirements:
Docker
AWS CLI
First of all, we must configure VPC that can reach the EFS mount targets. Here, we create a VPC, an internet gateway, two NAT gateway, and four subnets(two public, two private).
In the VPC console, I select Create VPC and set a Name tag and IPv4 CIDR block as follows:
In the next step, I create an internet gateway to connect the Internet from the VPC with the following settings. After that, I attach it to the created VPC.
In the next step, I create four subnets(public-spacy-1, public-spacy-2, private-spacy-1, private-spacy-2) with the following settings. Notice that public-spacy-1 and private-spacy-1 have the same availability zone.
Then, I create two NAT gateways and attach it to public subnets to access the Internet from a lambda function in the private subnet. I gave NAT gateways names: NAT spaCy 1 and NAT spaCy 2.
Finally, I create route tables. For public subnets, I add a destination 0.0.0.0/0 and a target Internet Gateway to access the Internet. For private subnets, I add a destination 0.0.0.0/0 and a target NAT spaCy 1 for private-spacy-1 and NAT spaCy 2 for private-spacy-2.
In the EFS console, I select Create file system and make sure that the default VPC and its subnets are selected. For all subnets, I use a security group that allows network access to other resources in the VPC. For simplicity, I set up a security group that allows all traffic.
In the next step, I give the file system a Name tag and select the Next Step.
Then, I select Add access point. I use 1001 for the User ID, Group ID, Owner User ID and Owner Group ID and 750 for the permissions. Also, I limit access to the /models path.
EFS creation is complete. Let’s go to the next step.
In the next step, we publish spaCy as Lambda Layers. We must do the following things:
Install spaCy
Compress it as a Zip file
Publish the file to Lambda Layer
For simplicity, I prepared the following shell script:
You have only to execute it like sh publish_spacy_as_lambda_layer.sh.
Next, we create a Lambda function. In the Lambda console, create a function and select Python 3.7 as the runtime. For permissions, select a role that is attached policiesAWSLambdaVPCAccessExecutionRole and AmazonElasticFileSystemClientReadWriteAccess.
After creating a function, we set up the VPC configuration. Here, we need to specify the same security group and VPC we specified for the EFS mount points and select the private subnets.
Then, we select the Add file system. We select the ESF and access point that has been created before. Here, we set /mnt/models as the local mount point. This is the path where the access point is mounted and corresponds to the /models directory in the EFS.
In the layer section, we select Add a layer to add spaCy.
In the function editor, copy and paste the following code.
Finally, we should increase the memory allocation and timeout values. If the memory allocation is not large enough, the following error will occur.
{ "errorType": "Runtime.ExitError", "errorMessage": "RequestId: Error: Runtime exited with error: signal: killed"}
As a test, when I test with the data {"text": "He works at Google."}, the following response will be returned.
[ { "text": "Google", "label": "ORG", "start": 12, "end": 18 }]
New — A Shared File System for Your Lambda Functions
AWS Lambda limits
Natural Language Processing in Cloud
Creating a Serverless NLP API using Spacy and AWS Lambda | [
{
"code": null,
"e": 461,
"s": 171,
"text": "spaCy is a useful tool that allows us to perform many natural language processing tasks. When integrating spaCy into an existing application, it is convenient to provide it as an API using AWS Lambda and API Gateway. However, due to Lambda’s limitations, it is hard to deploy large models."
},
{
"code": null,
"e": 796,
"s": 461,
"text": "In this article, I will show you how to deploy spaCy using the recently released feature to mount Elastic File System (EFS) on AWS Lambda. By using this feature, we can store a large size model to EFS and load it from Lambda functions. Specifically, it is possible to load data larger than the space available in Lambda’s/tmp (512MB)."
},
{
"code": null,
"e": 1030,
"s": 796,
"text": "The overall architecture is as follows. Lambda loads the spaCy package on Lambda Layers. EFS stores the spaCy models. Lambda then loads the models from EFS. For redundancy, four subnets are placed on two different availability zones."
},
{
"code": null,
"e": 1044,
"s": 1030,
"text": "Requirements:"
},
{
"code": null,
"e": 1051,
"s": 1044,
"text": "Docker"
},
{
"code": null,
"e": 1059,
"s": 1051,
"text": "AWS CLI"
},
{
"code": null,
"e": 1237,
"s": 1059,
"text": "First of all, we must configure VPC that can reach the EFS mount targets. Here, we create a VPC, an internet gateway, two NAT gateway, and four subnets(two public, two private)."
},
{
"code": null,
"e": 1328,
"s": 1237,
"text": "In the VPC console, I select Create VPC and set a Name tag and IPv4 CIDR block as follows:"
},
{
"code": null,
"e": 1485,
"s": 1328,
"text": "In the next step, I create an internet gateway to connect the Internet from the VPC with the following settings. After that, I attach it to the created VPC."
},
{
"code": null,
"e": 1700,
"s": 1485,
"text": "In the next step, I create four subnets(public-spacy-1, public-spacy-2, private-spacy-1, private-spacy-2) with the following settings. Notice that public-spacy-1 and private-spacy-1 have the same availability zone."
},
{
"code": null,
"e": 1889,
"s": 1700,
"text": "Then, I create two NAT gateways and attach it to public subnets to access the Internet from a lambda function in the private subnet. I gave NAT gateways names: NAT spaCy 1 and NAT spaCy 2."
},
{
"code": null,
"e": 2158,
"s": 1889,
"text": "Finally, I create route tables. For public subnets, I add a destination 0.0.0.0/0 and a target Internet Gateway to access the Internet. For private subnets, I add a destination 0.0.0.0/0 and a target NAT spaCy 1 for private-spacy-1 and NAT spaCy 2 for private-spacy-2."
},
{
"code": null,
"e": 2436,
"s": 2158,
"text": "In the EFS console, I select Create file system and make sure that the default VPC and its subnets are selected. For all subnets, I use a security group that allows network access to other resources in the VPC. For simplicity, I set up a security group that allows all traffic."
},
{
"code": null,
"e": 2514,
"s": 2436,
"text": "In the next step, I give the file system a Name tag and select the Next Step."
},
{
"code": null,
"e": 2689,
"s": 2514,
"text": "Then, I select Add access point. I use 1001 for the User ID, Group ID, Owner User ID and Owner Group ID and 750 for the permissions. Also, I limit access to the /models path."
},
{
"code": null,
"e": 2742,
"s": 2689,
"text": "EFS creation is complete. Let’s go to the next step."
},
{
"code": null,
"e": 2828,
"s": 2742,
"text": "In the next step, we publish spaCy as Lambda Layers. We must do the following things:"
},
{
"code": null,
"e": 2842,
"s": 2828,
"text": "Install spaCy"
},
{
"code": null,
"e": 2868,
"s": 2842,
"text": "Compress it as a Zip file"
},
{
"code": null,
"e": 2901,
"s": 2868,
"text": "Publish the file to Lambda Layer"
},
{
"code": null,
"e": 2956,
"s": 2901,
"text": "For simplicity, I prepared the following shell script:"
},
{
"code": null,
"e": 3026,
"s": 2956,
"text": "You have only to execute it like sh publish_spacy_as_lambda_layer.sh."
},
{
"code": null,
"e": 3278,
"s": 3026,
"text": "Next, we create a Lambda function. In the Lambda console, create a function and select Python 3.7 as the runtime. For permissions, select a role that is attached policiesAWSLambdaVPCAccessExecutionRole and AmazonElasticFileSystemClientReadWriteAccess."
},
{
"code": null,
"e": 3465,
"s": 3278,
"text": "After creating a function, we set up the VPC configuration. Here, we need to specify the same security group and VPC we specified for the EFS mount points and select the private subnets."
},
{
"code": null,
"e": 3722,
"s": 3465,
"text": "Then, we select the Add file system. We select the ESF and access point that has been created before. Here, we set /mnt/models as the local mount point. This is the path where the access point is mounted and corresponds to the /models directory in the EFS."
},
{
"code": null,
"e": 3780,
"s": 3722,
"text": "In the layer section, we select Add a layer to add spaCy."
},
{
"code": null,
"e": 3839,
"s": 3780,
"text": "In the function editor, copy and paste the following code."
},
{
"code": null,
"e": 3987,
"s": 3839,
"text": "Finally, we should increase the memory allocation and timeout values. If the memory allocation is not large enough, the following error will occur."
},
{
"code": null,
"e": 4104,
"s": 3987,
"text": "{ \"errorType\": \"Runtime.ExitError\", \"errorMessage\": \"RequestId: Error: Runtime exited with error: signal: killed\"}"
},
{
"code": null,
"e": 4215,
"s": 4104,
"text": "As a test, when I test with the data {\"text\": \"He works at Google.\"}, the following response will be returned."
},
{
"code": null,
"e": 4293,
"s": 4215,
"text": "[ { \"text\": \"Google\", \"label\": \"ORG\", \"start\": 12, \"end\": 18 }]"
},
{
"code": null,
"e": 4346,
"s": 4293,
"text": "New — A Shared File System for Your Lambda Functions"
},
{
"code": null,
"e": 4364,
"s": 4346,
"text": "AWS Lambda limits"
},
{
"code": null,
"e": 4401,
"s": 4364,
"text": "Natural Language Processing in Cloud"
}
]
|
Tryit Editor v3.7 | HTML Computer Code
Tryit: HTML code element | [
{
"code": null,
"e": 29,
"s": 10,
"text": "HTML Computer Code"
}
]
|
Dart Programming - Map Property isEmpty | Returns true if the Map is empty.
Map.isEmpty
void main() {
var details = {'Usrname':'tom','Password':'pass@123'};
print(details.isEmpty);
var hosts = {};
print(hosts.isEmpty);
}
It will produce the following output −
false
true
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2559,
"s": 2525,
"text": "Returns true if the Map is empty."
},
{
"code": null,
"e": 2573,
"s": 2559,
"text": "Map.isEmpty \n"
},
{
"code": null,
"e": 2723,
"s": 2573,
"text": "void main() { \n var details = {'Usrname':'tom','Password':'pass@123'}; \n print(details.isEmpty); \n var hosts = {}; \n print(hosts.isEmpty); \n}"
},
{
"code": null,
"e": 2762,
"s": 2723,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 2775,
"s": 2762,
"text": "false \ntrue\n"
},
{
"code": null,
"e": 2810,
"s": 2775,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2830,
"s": 2810,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 2863,
"s": 2830,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2883,
"s": 2863,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 2916,
"s": 2883,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2933,
"s": 2916,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 2968,
"s": 2933,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 2985,
"s": 2968,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3020,
"s": 2985,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3040,
"s": 3020,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3073,
"s": 3040,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3093,
"s": 3073,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3100,
"s": 3093,
"text": " Print"
},
{
"code": null,
"e": 3111,
"s": 3100,
"text": " Add Notes"
}
]
|
Pretty displaying tricks for columnar data in Python | by Aadarsh Vadakattu | Towards Data Science | For everyone who has extensively wrangled data using lists, Pandas, or NumPy before, you might have had experienced issues with printing the data in the right way. Especially if there are a lot of columns, displaying the data becomes a hassle. This article shows you how you can print large columnar data in python in a readable way.
To explain clearly, I am using the NYC Property sales data, which has a total of 21 columns.
This is what happens if you have a Pandas DataFrame with many columns and try to print it out with a regular print statement:
import pandas as pdnycdata=pd.read_csv('nyc-rolling-sales.csv',index_col=0)print(nycdata.head())
This happens as Pandas will detect the number of columns it can fit in the space of your terminal window, which would not display exactly what we need. Most data is omitted from printing to save terminal space on your screen.
To solve this, here are some ways to go.
You can increase the max number of columns Pandas lets you display, by adding this line to your code:
pd.options.display.max_columns = None
This removes the max column limit for displaying on the screen. Here is how it looks when printed (printing the first 11 columns only for now..)
But hey, that is not totally what we needed. The data is split into multiple lines, with headers divided by backward slashes. This is readable and can be useful, but is still not perfect.
To get over this, simply use this line with your code and you can get all the data in a single line fashion:
pd.options.display.width=None
And this is how it looks like now (printed only 7 columns):
Beware — most code editors don’t display big chunks of columnar data in a good way. Your output will be cluttered in a totally unreadable way, and you need to maximize your output window to have a good look at all of the data. PyCharm does a very good job in this case — it shows you a horizontal scrollbar where you can scroll through the data you have printed. This would not be the case with a standard Terminal or editors like VSCode.
If you are using Terminal or VSCode, maximize the window and reduce the font size so that you can fit in the most columns in the limited space and have a pretty look at your data.
This is how the complete data is displayed in Terminal output (VSCode prints it in the same way):
And this is how PyCharm displays the same data:
If you are using PyCharm and would like to display the data similar to the above, or if you think maximizing and reducing font size would be acceptable — here is a better way to display your data.
You can use a library called “tabulate” to easily display data in columns. It is as easy as wrapping a simple function to the print function used on the DataFrame.
from tabulate import tabulate...print(tabulate(df,headers='firstrow'))
and this is how tabulate displays your data:
To get rid of extra lines of code at the print statement, a simple lambda function can be written in this way:
from tabulate import tabulatepdtabulate=lambda df:tabulate(df,headers='keys')...print(pdtabulate(df))
What is more amazing, is you can select the format of printing from a variety of formats. All you need to do is add the ‘tablefmt’ argument to the tabulate function and assign it with a print format of your choice. My favorite of all is ‘psql’, which uses PostgreSQL’s formatting for displaying tabular data.
from tabulate import tabulatepdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='psql')...print(pdtabulate(df))
And this is how it looks like:
If you have a necessity of converting the data into HTML tables, tabulate easily does that for you.
from tabulate import tabulatepdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='html')...print(pdtabulate(df))
Tabulate works very well even for large lists and huge NumPy arrays.
from tabulate import tabulatepdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='psql')#Creating a list using garbage valueslist = [['a', 'b', 'c','d'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]print(pdtabulate(list))
And this is how it looks:
Here is a sample NumPy array visualized using tabulate:
For more information about this amazing library and more to know more about different print formats, visit this page.
Though these tricks would be very helpful, the following trick shows our data in the best way possible.
Forget about PyCharm, Terminal and tabulate — use Jupyter notebooks instead to display your data.
Jupyter notebooks display your data similar to the first case out of the box— they omit a few columns in their display.
To get around that, use the same line used in the print example to display all columns of your data:
pd.options.display.max_columns = None
And Jupyter shows a perfectly formatted HTML table for you:
If you are comfortable frequently using Jupyter notebooks, simply setting max columns to None will display all of your data at once. But if you are a person who likes to write code in editors and not move to Jupyter notebooks to understand data, using the tabulate library is the best way to go. | [
{
"code": null,
"e": 506,
"s": 172,
"text": "For everyone who has extensively wrangled data using lists, Pandas, or NumPy before, you might have had experienced issues with printing the data in the right way. Especially if there are a lot of columns, displaying the data becomes a hassle. This article shows you how you can print large columnar data in python in a readable way."
},
{
"code": null,
"e": 599,
"s": 506,
"text": "To explain clearly, I am using the NYC Property sales data, which has a total of 21 columns."
},
{
"code": null,
"e": 725,
"s": 599,
"text": "This is what happens if you have a Pandas DataFrame with many columns and try to print it out with a regular print statement:"
},
{
"code": null,
"e": 822,
"s": 725,
"text": "import pandas as pdnycdata=pd.read_csv('nyc-rolling-sales.csv',index_col=0)print(nycdata.head())"
},
{
"code": null,
"e": 1048,
"s": 822,
"text": "This happens as Pandas will detect the number of columns it can fit in the space of your terminal window, which would not display exactly what we need. Most data is omitted from printing to save terminal space on your screen."
},
{
"code": null,
"e": 1089,
"s": 1048,
"text": "To solve this, here are some ways to go."
},
{
"code": null,
"e": 1191,
"s": 1089,
"text": "You can increase the max number of columns Pandas lets you display, by adding this line to your code:"
},
{
"code": null,
"e": 1229,
"s": 1191,
"text": "pd.options.display.max_columns = None"
},
{
"code": null,
"e": 1374,
"s": 1229,
"text": "This removes the max column limit for displaying on the screen. Here is how it looks when printed (printing the first 11 columns only for now..)"
},
{
"code": null,
"e": 1562,
"s": 1374,
"text": "But hey, that is not totally what we needed. The data is split into multiple lines, with headers divided by backward slashes. This is readable and can be useful, but is still not perfect."
},
{
"code": null,
"e": 1671,
"s": 1562,
"text": "To get over this, simply use this line with your code and you can get all the data in a single line fashion:"
},
{
"code": null,
"e": 1701,
"s": 1671,
"text": "pd.options.display.width=None"
},
{
"code": null,
"e": 1761,
"s": 1701,
"text": "And this is how it looks like now (printed only 7 columns):"
},
{
"code": null,
"e": 2200,
"s": 1761,
"text": "Beware — most code editors don’t display big chunks of columnar data in a good way. Your output will be cluttered in a totally unreadable way, and you need to maximize your output window to have a good look at all of the data. PyCharm does a very good job in this case — it shows you a horizontal scrollbar where you can scroll through the data you have printed. This would not be the case with a standard Terminal or editors like VSCode."
},
{
"code": null,
"e": 2380,
"s": 2200,
"text": "If you are using Terminal or VSCode, maximize the window and reduce the font size so that you can fit in the most columns in the limited space and have a pretty look at your data."
},
{
"code": null,
"e": 2478,
"s": 2380,
"text": "This is how the complete data is displayed in Terminal output (VSCode prints it in the same way):"
},
{
"code": null,
"e": 2526,
"s": 2478,
"text": "And this is how PyCharm displays the same data:"
},
{
"code": null,
"e": 2723,
"s": 2526,
"text": "If you are using PyCharm and would like to display the data similar to the above, or if you think maximizing and reducing font size would be acceptable — here is a better way to display your data."
},
{
"code": null,
"e": 2887,
"s": 2723,
"text": "You can use a library called “tabulate” to easily display data in columns. It is as easy as wrapping a simple function to the print function used on the DataFrame."
},
{
"code": null,
"e": 2958,
"s": 2887,
"text": "from tabulate import tabulate...print(tabulate(df,headers='firstrow'))"
},
{
"code": null,
"e": 3003,
"s": 2958,
"text": "and this is how tabulate displays your data:"
},
{
"code": null,
"e": 3114,
"s": 3003,
"text": "To get rid of extra lines of code at the print statement, a simple lambda function can be written in this way:"
},
{
"code": null,
"e": 3216,
"s": 3114,
"text": "from tabulate import tabulatepdtabulate=lambda df:tabulate(df,headers='keys')...print(pdtabulate(df))"
},
{
"code": null,
"e": 3525,
"s": 3216,
"text": "What is more amazing, is you can select the format of printing from a variety of formats. All you need to do is add the ‘tablefmt’ argument to the tabulate function and assign it with a print format of your choice. My favorite of all is ‘psql’, which uses PostgreSQL’s formatting for displaying tabular data."
},
{
"code": null,
"e": 3643,
"s": 3525,
"text": "from tabulate import tabulatepdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='psql')...print(pdtabulate(df))"
},
{
"code": null,
"e": 3674,
"s": 3643,
"text": "And this is how it looks like:"
},
{
"code": null,
"e": 3774,
"s": 3674,
"text": "If you have a necessity of converting the data into HTML tables, tabulate easily does that for you."
},
{
"code": null,
"e": 3892,
"s": 3774,
"text": "from tabulate import tabulatepdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='html')...print(pdtabulate(df))"
},
{
"code": null,
"e": 3961,
"s": 3892,
"text": "Tabulate works very well even for large lists and huge NumPy arrays."
},
{
"code": null,
"e": 4351,
"s": 3961,
"text": "from tabulate import tabulatepdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='psql')#Creating a list using garbage valueslist = [['a', 'b', 'c','d'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]print(pdtabulate(list))"
},
{
"code": null,
"e": 4377,
"s": 4351,
"text": "And this is how it looks:"
},
{
"code": null,
"e": 4433,
"s": 4377,
"text": "Here is a sample NumPy array visualized using tabulate:"
},
{
"code": null,
"e": 4551,
"s": 4433,
"text": "For more information about this amazing library and more to know more about different print formats, visit this page."
},
{
"code": null,
"e": 4655,
"s": 4551,
"text": "Though these tricks would be very helpful, the following trick shows our data in the best way possible."
},
{
"code": null,
"e": 4753,
"s": 4655,
"text": "Forget about PyCharm, Terminal and tabulate — use Jupyter notebooks instead to display your data."
},
{
"code": null,
"e": 4873,
"s": 4753,
"text": "Jupyter notebooks display your data similar to the first case out of the box— they omit a few columns in their display."
},
{
"code": null,
"e": 4974,
"s": 4873,
"text": "To get around that, use the same line used in the print example to display all columns of your data:"
},
{
"code": null,
"e": 5012,
"s": 4974,
"text": "pd.options.display.max_columns = None"
},
{
"code": null,
"e": 5072,
"s": 5012,
"text": "And Jupyter shows a perfectly formatted HTML table for you:"
}
]
|
How can I display an image inside SVG circle in HTML5? | To display an image inside SVG circle, use the <circle> element and set the clipping path. The <clipPath> element is used to define a clipping path. Image in SVG is set using the <image> element.
You can try to run the following code to learn how to display an image inside SVG circle in HTML5
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML5 SVG Image</title>
<head>
<body>
<svg width="500" height="350">
<defs>
<clipPath id="myCircle">
<circle cx="250" cy="145" r="125" fill="#FFFFFF" />
</clipPath>
</defs>
<image width="500" height="350" xlink:href="https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg" clip-path="url(#myCircle)" />
</svg>
</body>
</html> | [
{
"code": null,
"e": 1258,
"s": 1062,
"text": "To display an image inside SVG circle, use the <circle> element and set the clipping path. The <clipPath> element is used to define a clipping path. Image in SVG is set using the <image> element."
},
{
"code": null,
"e": 1356,
"s": 1258,
"text": "You can try to run the following code to learn how to display an image inside SVG circle in HTML5"
},
{
"code": null,
"e": 1366,
"s": 1356,
"text": "Live Demo"
},
{
"code": null,
"e": 1846,
"s": 1366,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML5 SVG Image</title>\n <head>\n <body>\n <svg width=\"500\" height=\"350\">\n <defs>\n <clipPath id=\"myCircle\">\n <circle cx=\"250\" cy=\"145\" r=\"125\" fill=\"#FFFFFF\" />\n </clipPath>\n </defs>\n <image width=\"500\" height=\"350\" xlink:href=\"https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg\" clip-path=\"url(#myCircle)\" />\n </svg>\n </body>\n</html>"
}
]
|
Find X and Y in Linear Equation | Practice | GeeksforGeeks | Given A, B and N. Find x and y that satisfies equation Ax + By = N. If there's no solution print -1 in place of both x and y.
Note: There are Multiple solutions possible. Find the solution where x is minimum. x and y should both be non-negative.
Example 1:
Input:
A = 2, B = 3, N = 7
Output:
2 1
Explanation:
2*2 + 3*1 = 7.
Example 2:
Input:
A = 4, B = 2, N = 7
Output:
-1 -1
Explanation:
There's no solution for x and y the equation.
Your Task:
You don't need to read input or print anything. Your task is to complete the function findXandY() which takes 3 Integers A,B and N as input and returns a list of 2 integers with the first integer x and the second being y.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= A,B <= 105
0 <= N <= 105
No Comments to load
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 485,
"s": 238,
"text": "Given A, B and N. Find x and y that satisfies equation Ax + By = N. If there's no solution print -1 in place of both x and y. \nNote: There are Multiple solutions possible. Find the solution where x is minimum. x and y should both be non-negative."
},
{
"code": null,
"e": 498,
"s": 487,
"text": "Example 1:"
},
{
"code": null,
"e": 565,
"s": 498,
"text": "Input:\nA = 2, B = 3, N = 7\nOutput:\n2 1\nExplanation:\n2*2 + 3*1 = 7."
},
{
"code": null,
"e": 576,
"s": 565,
"text": "Example 2:"
},
{
"code": null,
"e": 676,
"s": 576,
"text": "Input:\nA = 4, B = 2, N = 7\nOutput:\n-1 -1\nExplanation:\nThere's no solution for x and y the equation."
},
{
"code": null,
"e": 911,
"s": 678,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function findXandY() which takes 3 Integers A,B and N as input and returns a list of 2 integers with the first integer x and the second being y."
},
{
"code": null,
"e": 975,
"s": 913,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1020,
"s": 977,
"text": "Constraints:\n1 <= A,B <= 105\n0 <= N <= 105"
},
{
"code": null,
"e": 1040,
"s": 1020,
"text": "No Comments to load"
},
{
"code": null,
"e": 1186,
"s": 1040,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 1222,
"s": 1186,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 1232,
"s": 1222,
"text": "\nProblem\n"
},
{
"code": null,
"e": 1242,
"s": 1232,
"text": "\nContest\n"
},
{
"code": null,
"e": 1305,
"s": 1242,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 1453,
"s": 1305,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 1661,
"s": 1453,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 1767,
"s": 1661,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
How to Insert an Image in HTML Page? | Images can be easily inserted at any section in an HTML page. To insert image in an HTML page, use the <img> tags. It is an empty tag, containing only attributes since the closing tag is not required.
Just keep in mind that you should use the <img> tag inside <body>...</body> tag. The src attribute is used to add the image source i.e. URL of the image. The alt attribute is for adding alternate text, width for adding width, and height for adding the height of the image.
You can try the following code to insert an image in an HTML page −
<!DOCTYPE html>
<html>
<head>
<title>HTML img Tag</title>
</head>
<body>
<img src="https://www.tutorialspoint.com/html/images/test.png" alt="Simply Easy Learning" width="200" height="80">
</body>
</html> | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "Images can be easily inserted at any section in an HTML page. To insert image in an HTML page, use the <img> tags. It is an empty tag, containing only attributes since the closing tag is not required."
},
{
"code": null,
"e": 1536,
"s": 1263,
"text": "Just keep in mind that you should use the <img> tag inside <body>...</body> tag. The src attribute is used to add the image source i.e. URL of the image. The alt attribute is for adding alternate text, width for adding width, and height for adding the height of the image."
},
{
"code": null,
"e": 1604,
"s": 1536,
"text": "You can try the following code to insert an image in an HTML page −"
},
{
"code": null,
"e": 1833,
"s": 1604,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML img Tag</title>\n </head>\n\n <body>\n <img src=\"https://www.tutorialspoint.com/html/images/test.png\" alt=\"Simply Easy Learning\" width=\"200\" height=\"80\">\n </body>\n</html>"
}
]
|
C++ break statement | The break statement has the following two usages in C++ −
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
The syntax of a break statement in C++ is −
break;
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15) {
// terminate the loop
break;
}
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2376,
"s": 2318,
"text": "The break statement has the following two usages in C++ −"
},
{
"code": null,
"e": 2536,
"s": 2376,
"text": "When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2696,
"s": 2536,
"text": "When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2786,
"s": 2696,
"text": "It can be used to terminate a case in the switch statement (covered in the next chapter)."
},
{
"code": null,
"e": 2876,
"s": 2786,
"text": "It can be used to terminate a case in the switch statement (covered in the next chapter)."
},
{
"code": null,
"e": 3069,
"s": 2876,
"text": "If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block."
},
{
"code": null,
"e": 3113,
"s": 3069,
"text": "The syntax of a break statement in C++ is −"
},
{
"code": null,
"e": 3121,
"s": 3113,
"text": "break;\n"
},
{
"code": null,
"e": 3434,
"s": 3121,
"text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // Local variable declaration:\n int a = 10;\n\n // do loop execution\n do {\n cout << \"value of a: \" << a << endl;\n a = a + 1;\n if( a > 15) {\n // terminate the loop\n break;\n }\n } while( a < 20 );\n \n return 0;\n}"
},
{
"code": null,
"e": 3515,
"s": 3434,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3606,
"s": 3515,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\n"
},
{
"code": null,
"e": 3643,
"s": 3606,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 3662,
"s": 3643,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3694,
"s": 3662,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 3717,
"s": 3694,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 3753,
"s": 3717,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3770,
"s": 3753,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3805,
"s": 3770,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3822,
"s": 3805,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3857,
"s": 3822,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3874,
"s": 3857,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3909,
"s": 3874,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3926,
"s": 3909,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3933,
"s": 3926,
"text": " Print"
},
{
"code": null,
"e": 3944,
"s": 3933,
"text": " Add Notes"
}
]
|
Find four elements that sum to a given value | Set 1 (n^3 solution) - GeeksforGeeks | 24 Mar, 2021
Given an array of integers, find all combination of four elements in the array whose sum is equal to a given value X. For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23, then your function should print “3 5 7 8” (3 + 5 + 7 + 8 = 23).
A Naive Solution is to generate all possible quadruples and compare the sum of every quadruple with X. The following code implements this simple method using four nested loops
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for naive solution to// print all combination of 4 elements// in A[] with sum equal to X#include <bits/stdc++.h>using namespace std; /* A naive solution to print all combinationof 4 elements in A[]with sum equal to X */void findFourElements(int A[], int n, int X){ // Fix the first element and find other threefor (int i = 0; i < n - 3; i++){ // Fix the second element and find other two for (int j = i + 1; j < n - 2; j++) { // Fix the third element and find the fourth for (int k = j + 1; k < n - 1; k++) { // find the fourth for (int l = k + 1; l < n; l++) if (A[i] + A[j] + A[k] + A[l] == X) cout << A[i] <<", " << A[j] << ", " << A[k] << ", " << A[l]; } }}} // Driver Codeint main(){ int A[] = {10, 20, 30, 40, 1, 2}; int n = sizeof(A) / sizeof(A[0]); int X = 91; findFourElements (A, n, X); return 0;} // This code is contributed// by Akanksha Rai
#include <stdio.h> /* A naive solution to print all combination of 4 elements in A[] with sum equal to X */void findFourElements(int A[], int n, int X){ // Fix the first element and find other three for (int i = 0; i < n-3; i++) { // Fix the second element and find other two for (int j = i+1; j < n-2; j++) { // Fix the third element and find the fourth for (int k = j+1; k < n-1; k++) { // find the fourth for (int l = k+1; l < n; l++) if (A[i] + A[j] + A[k] + A[l] == X) printf("%d, %d, %d, %d", A[i], A[j], A[k], A[l]); } } }} // Driver program to test above functionint main(){ int A[] = {10, 20, 30, 40, 1, 2}; int n = sizeof(A) / sizeof(A[0]); int X = 91; findFourElements (A, n, X); return 0;}
class FindFourElements{ /* A naive solution to print all combination of 4 elements in A[] with sum equal to X */ void findFourElements(int A[], int n, int X) { // Fix the first element and find other three for (int i = 0; i < n - 3; i++) { // Fix the second element and find other two for (int j = i + 1; j < n - 2; j++) { // Fix the third element and find the fourth for (int k = j + 1; k < n - 1; k++) { // find the fourth for (int l = k + 1; l < n; l++) { if (A[i] + A[j] + A[k] + A[l] == X) System.out.print(A[i]+" "+A[j]+" "+A[k] +" "+A[l]); } } } } } // Driver program to test above functions public static void main(String[] args) { FindFourElements findfour = new FindFourElements(); int A[] = {10, 20, 30, 40, 1, 2}; int n = A.length; int X = 91; findfour.findFourElements(A, n, X); }}
# A naive solution to print all combination# of 4 elements in A[] with sum equal to Xdef findFourElements(A, n, X): # Fix the first element and find # other three for i in range(0,n-3): # Fix the second element and # find other two for j in range(i+1,n-2): # Fix the third element # and find the fourth for k in range(j+1,n-1): # find the fourth for l in range(k+1,n): if A[i] + A[j] + A[k] + A[l] == X: print ("%d, %d, %d, %d" %( A[i], A[j], A[k], A[l])) # Driver program to test above functionA = [10, 2, 3, 4, 5, 9, 7, 8]n = len(A)X = 23findFourElements (A, n, X) # This code is contributed by shreyanshi_arun
// C# program for naive solution to// print all combination of 4 elements// in A[] with sum equal to Xusing System; class FindFourElements{ void findFourElements(int []A, int n, int X) { // Fix the first element and find other three for (int i = 0; i < n - 3; i++) { // Fix the second element and find other two for (int j = i + 1; j < n - 2; j++) { // Fix the third element and find the fourth for (int k = j + 1; k < n - 1; k++) { // find the fourth for (int l = k + 1; l < n; l++) { if (A[i] + A[j] + A[k] + A[l] == X) Console.Write(A[i] + " " + A[j] + " " + A[k] + " " + A[l]); } } } } } // Driver program to test above functions public static void Main() { FindFourElements findfour = new FindFourElements(); int []A = {10, 20, 30, 40, 1, 2}; int n = A.Length; int X = 91; findfour.findFourElements(A, n, X); }} // This code is contributed by nitin mittal
<?php/* A naive solution to print all combinationof 4 elements in A[] with sum equal to X */ function findFourElements($A, $n, $X){ // Fix the first element and find other // three for ($i = 0; $i < $n-3; $i++) { // Fix the second element and find // other two for ($j = $i+1; $j < $n-2; $j++) { // Fix the third element and // find the fourth for ($k = $j+1; $k < $n-1; $k++) { // find the fourth for ($l = $k+1; $l < $n; $l++) if ($A[$i] + $A[$j] + $A[$k] + $A[$l] == $X) echo $A[$i], ", " , $A[$j], ", ", $A[$k], ", ", $A[$l]; } } }} // Driver program to test above function $A = array (10, 20, 30, 40, 1, 2); $n = sizeof($A) ; $X = 91; findFourElements ($A, $n, $X); // This code is contributed by m_kit?>
<script> // Javascript program for the above approach /* A naive solution to print all combinationof 4 elements in A[]with sum equal to X */function findFourElements(A, n, X){ // Fix the first element and find other threefor (let i = 0; i < n - 3; i++){ // Fix the second element and find other two for (let j = i + 1; j < n - 2; j++) { // Fix the third element and find the fourth for (let k = j + 1; k < n - 1; k++) { // find the fourth for (let l = k + 1; l < n; l++) if (A[i] + A[j] + A[k] + A[l] == X) document.write(A[i]+", "+A[j]+", "+A[k] +", "+A[l]); } }}} // Driver Code let A = [10, 20, 30, 40, 1, 2]; let n = A.length; let X = 91; findFourElements (A, n, X); </script>
Output:
20, 30, 40, 1
Time Complexity: O(n^4)The time complexity can be improved to O(n^3) with the use of sorting as a preprocessing step, and then using method 1 of this post to reduce a loop.Following are the detailed steps. 1) Sort the input array. 2) Fix the first element as A[i] where i is from 0 to n–3. After fixing the first element of quadruple, fix the second element as A[j] where j varies from i+1 to n-2. Find remaining two elements in O(n) time, using the method 1 of this post Following is the implementation of O(n^3) solution.
C++
C
Java
Python 3
C#
PHP
Javascript
// C++ program for to print all combination// of 4 elements in A[] with sum equal to X#include<bits/stdc++.h>using namespace std; /* Following function is neededfor library function qsort(). */int compare (const void *a, const void * b){ return ( *(int *)a - *(int *)b );} /* A sorting based solution to printall combination of 4 elements in A[]with sum equal to X */void find4Numbers(int A[], int n, int X){ int l, r; // Sort the array in increasing // order, using library function // for quick sort qsort (A, n, sizeof(A[0]), compare); /* Now fix the first 2 elements one by one and find the other two elements */ for (int i = 0; i < n - 3; i++) { for (int j = i+1; j < n - 2; j++) { // Initialize two variables as // indexes of the first and last // elements in the remaining elements l = j + 1; r = n-1; // To find the remaining two // elements, move the index // variables (l & r) toward each other. while (l < r) { if( A[i] + A[j] + A[l] + A[r] == X) { cout << A[i]<<", " << A[j] << ", " << A[l] << ", " << A[r]; l++; r--; } else if (A[i] + A[j] + A[l] + A[r] < X) l++; else // A[i] + A[j] + A[l] + A[r] > X r--; } // end of while } // end of inner for loop } // end of outer for loop} /* Driver code */int main(){ int A[] = {1, 4, 45, 6, 10, 12}; int X = 21; int n = sizeof(A) / sizeof(A[0]); find4Numbers(A, n, X); return 0;} // This code is contributed by rathbhupendra
# include <stdio.h># include <stdlib.h> /* Following function is needed for library function qsort(). Refer http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){ return ( *(int *)a - *(int *)b ); } /* A sorting based solution to print all combination of 4 elements in A[] with sum equal to X */void find4Numbers(int A[], int n, int X){ int l, r; // Sort the array in increasing order, using library // function for quick sort qsort (A, n, sizeof(A[0]), compare); /* Now fix the first 2 elements one by one and find the other two elements */ for (int i = 0; i < n - 3; i++) { for (int j = i+1; j < n - 2; j++) { // Initialize two variables as indexes of the first and last // elements in the remaining elements l = j + 1; r = n-1; // To find the remaining two elements, move the index // variables (l & r) toward each other. while (l < r) { if( A[i] + A[j] + A[l] + A[r] == X) { printf("%d, %d, %d, %d", A[i], A[j], A[l], A[r]); l++; r--; } else if (A[i] + A[j] + A[l] + A[r] < X) l++; else // A[i] + A[j] + A[l] + A[r] > X r--; } // end of while } // end of inner for loop } // end of outer for loop} /* Driver program to test above function */int main(){ int A[] = {1, 4, 45, 6, 10, 12}; int X = 21; int n = sizeof(A)/sizeof(A[0]); find4Numbers(A, n, X); return 0;}
import java.util.Arrays; class FindFourElements{ /* A sorting based solution to print all combination of 4 elements in A[] with sum equal to X */ void find4Numbers(int A[], int n, int X) { int l, r; // Sort the array in increasing order, using library // function for quick sort Arrays.sort(A); /* Now fix the first 2 elements one by one and find the other two elements */ for (int i = 0; i < n - 3; i++) { for (int j = i + 1; j < n - 2; j++) { // Initialize two variables as indexes of the first and last // elements in the remaining elements l = j + 1; r = n - 1; // To find the remaining two elements, move the index // variables (l & r) toward each other. while (l < r) { if (A[i] + A[j] + A[l] + A[r] == X) { System.out.println(A[i]+" "+A[j]+" "+A[l]+" "+A[r]); l++; r--; } else if (A[i] + A[j] + A[l] + A[r] < X) l++; else // A[i] + A[j] + A[l] + A[r] > X r--; } // end of while } // end of inner for loop } // end of outer for loop } // Driver program to test above functions public static void main(String[] args) { FindFourElements findfour = new FindFourElements(); int A[] = {1, 4, 45, 6, 10, 12}; int n = A.length; int X = 21; findfour.find4Numbers(A, n, X); }} // This code has been contributed by Mayank Jaiswal
# A sorting based solution to print all combination# of 4 elements in A[] with sum equal to Xdef find4Numbers(A, n, X): # Sort the array in increasing order, # using library function for quick sort A.sort() # Now fix the first 2 elements one by # one and find the other two elements for i in range(n - 3): for j in range(i + 1, n - 2): # Initialize two variables as indexes # of the first and last elements in # the remaining elements l = j + 1 r = n - 1 # To find the remaining two elements, # move the index variables (l & r) # toward each other. while (l < r): if(A[i] + A[j] + A[l] + A[r] == X): print(A[i], ",", A[j], ",", A[l], ",", A[r]) l += 1 r -= 1 elif (A[i] + A[j] + A[l] + A[r] < X): l += 1 else: # A[i] + A[j] + A[l] + A[r] > X r -= 1 # Driver Codeif __name__ == "__main__": A = [1, 4, 45, 6, 10, 12] X = 21 n = len(A) find4Numbers(A, n, X) # This code is contributed by ita_c
// C# program for to print all combination// of 4 elements in A[] with sum equal to Xusing System; class FindFourElements{ // A sorting based solution to print all // combination of 4 elements in A[] with // sum equal to X void find4Numbers(int []A, int n, int X) { int l, r; // Sort the array in increasing order, // using library function for quick sort Array.Sort(A); /* Now fix the first 2 elements one by one and find the other two elements */ for (int i = 0; i < n - 3; i++) { for (int j = i + 1; j < n - 2; j++) { // Initialize two variables as indexes of // the first and last elements in the // remaining elements l = j + 1; r = n - 1; // To find the remaining two elements, move the // index variables (l & r) toward each other. while (l < r) { if (A[i] + A[j] + A[l] + A[r] == X) { Console.Write(A[i] + " " + A[j] + " " + A[l] + " " + A[r]); l++; r--; } else if (A[i] + A[j] + A[l] + A[r] < X) l++; else // A[i] + A[j] + A[l] + A[r] > X r--; } // end of while } // end of inner for loop } // end of outer for loop } // Driver program to test above functions public static void Main() { FindFourElements findfour = new FindFourElements(); int []A = {1, 4, 45, 6, 10, 12}; int n = A.Length; int X = 21; findfour.find4Numbers(A, n, X); }} // This code has been contributed by nitin mittal
<?php// PHP program for to print all// combination of 4 elements in// A[] with sum equal to X // A sorting based solution to// print all combination of 4// elements in A[] with sum// equal to Xfunction find4Numbers($A, $n, $X){ $l; $r; // Sort the array in increasing // order, using library function // for quick sort sort($A); // Now fix the first 2 elements // one by one and find the other // two elements for ($i = 0; $i < $n - 3; $i++) { for ($j = $i + 1; $j < $n - 2; $j++) { // Initialize two variables // as indexes of the first // and last elements in the // remaining elements $l = $j + 1; $r = $n - 1; // To find the remaining two // elements, move the index // variables (l & r) towards // each other. while ($l < $r) { if ($A[$i] + $A[$j] + $A[$l] + $A[$r] == $X) { echo $A[$i] , " " , $A[$j] , " " , $A[$l] , " " , $A[$r]; $l++; $r--; } else if ($A[$i] + $A[$j] + $A[$l] + $A[$r] < $X) $l++; // A[i] + A[j] + A[l] + A[r] > X else $r--; } } }} // Driver Code$A = array(1, 4, 45, 6, 10, 12);$n = count($A);$X = 21;find4Numbers($A, $n, $X); // This code is contributed// by nitin mittal?>
<script> /* A sorting based solution to print all combination of 4 elements in A[] with sum equal to X */ function find4Numbers(A,n,X) { let l, r; // Sort the array in increasing order, using library // function for quick sort A.sort(function(a, b){return a - b}); /* Now fix the first 2 elements one by one and find the other two elements */ for (let i = 0; i < n - 3; i++) { for (let j = i + 1; j < n - 2; j++) { // Initialize two variables as indexes of the first and last // elements in the remaining elements l = j + 1; r = n - 1; // To find the remaining two elements, move the index // variables (l & r) toward each other. while (l < r) { if (A[i] + A[j] + A[l] + A[r] == X) { document.write(A[i]+" "+A[j]+" "+A[l]+" "+A[r]+"<br>"); l++; r--; } else if ((A[i] + A[j] + A[l] + A[r]) < X) { l++; } else // A[i] + A[j] + A[l] + A[r] > X { r--; } } // end of while } // end of inner for loop }// end of outer for loop } // Driver program to test above functions let A= [1, 4, 45, 6, 10, 12]; let n = A.length; let X = 21; find4Numbers(A, n, X) // This code is contributed by rag2127 </script>
Output :
1, 4, 6, 10
Time Complexity : O(n^3)
YouTubeGeeksforGeeks501K subscribersFind four elements that sum to a given value | Set 1 (n^3 solution) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0fo7goi2GEg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This problem can also be solved in O(n^2Logn) complexity. Please refer below post for detailsFind four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.
nitin mittal
jit_t
vt_m
ukasp
Akanksha_Rai
rathbhupendra
shubham_singh
souravghosh0416
rag2127
Amazon
OYO Rooms
two-pointer-algorithm
Arrays
Searching
Amazon
OYO Rooms
two-pointer-algorithm
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1 | [
{
"code": null,
"e": 25158,
"s": 25130,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 25414,
"s": 25158,
"text": "Given an array of integers, find all combination of four elements in the array whose sum is equal to a given value X. For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23, then your function should print “3 5 7 8” (3 + 5 + 7 + 8 = 23). "
},
{
"code": null,
"e": 25592,
"s": 25414,
"text": "A Naive Solution is to generate all possible quadruples and compare the sum of every quadruple with X. The following code implements this simple method using four nested loops "
},
{
"code": null,
"e": 25596,
"s": 25592,
"text": "C++"
},
{
"code": null,
"e": 25598,
"s": 25596,
"text": "C"
},
{
"code": null,
"e": 25603,
"s": 25598,
"text": "Java"
},
{
"code": null,
"e": 25611,
"s": 25603,
"text": "Python3"
},
{
"code": null,
"e": 25614,
"s": 25611,
"text": "C#"
},
{
"code": null,
"e": 25618,
"s": 25614,
"text": "PHP"
},
{
"code": null,
"e": 25629,
"s": 25618,
"text": "Javascript"
},
{
"code": "// C++ program for naive solution to// print all combination of 4 elements// in A[] with sum equal to X#include <bits/stdc++.h>using namespace std; /* A naive solution to print all combinationof 4 elements in A[]with sum equal to X */void findFourElements(int A[], int n, int X){ // Fix the first element and find other threefor (int i = 0; i < n - 3; i++){ // Fix the second element and find other two for (int j = i + 1; j < n - 2; j++) { // Fix the third element and find the fourth for (int k = j + 1; k < n - 1; k++) { // find the fourth for (int l = k + 1; l < n; l++) if (A[i] + A[j] + A[k] + A[l] == X) cout << A[i] <<\", \" << A[j] << \", \" << A[k] << \", \" << A[l]; } }}} // Driver Codeint main(){ int A[] = {10, 20, 30, 40, 1, 2}; int n = sizeof(A) / sizeof(A[0]); int X = 91; findFourElements (A, n, X); return 0;} // This code is contributed// by Akanksha Rai",
"e": 26634,
"s": 25629,
"text": null
},
{
"code": "#include <stdio.h> /* A naive solution to print all combination of 4 elements in A[] with sum equal to X */void findFourElements(int A[], int n, int X){ // Fix the first element and find other three for (int i = 0; i < n-3; i++) { // Fix the second element and find other two for (int j = i+1; j < n-2; j++) { // Fix the third element and find the fourth for (int k = j+1; k < n-1; k++) { // find the fourth for (int l = k+1; l < n; l++) if (A[i] + A[j] + A[k] + A[l] == X) printf(\"%d, %d, %d, %d\", A[i], A[j], A[k], A[l]); } } }} // Driver program to test above functionint main(){ int A[] = {10, 20, 30, 40, 1, 2}; int n = sizeof(A) / sizeof(A[0]); int X = 91; findFourElements (A, n, X); return 0;}",
"e": 27425,
"s": 26634,
"text": null
},
{
"code": "class FindFourElements{ /* A naive solution to print all combination of 4 elements in A[] with sum equal to X */ void findFourElements(int A[], int n, int X) { // Fix the first element and find other three for (int i = 0; i < n - 3; i++) { // Fix the second element and find other two for (int j = i + 1; j < n - 2; j++) { // Fix the third element and find the fourth for (int k = j + 1; k < n - 1; k++) { // find the fourth for (int l = k + 1; l < n; l++) { if (A[i] + A[j] + A[k] + A[l] == X) System.out.print(A[i]+\" \"+A[j]+\" \"+A[k] +\" \"+A[l]); } } } } } // Driver program to test above functions public static void main(String[] args) { FindFourElements findfour = new FindFourElements(); int A[] = {10, 20, 30, 40, 1, 2}; int n = A.length; int X = 91; findfour.findFourElements(A, n, X); }}",
"e": 28609,
"s": 27425,
"text": null
},
{
"code": "# A naive solution to print all combination# of 4 elements in A[] with sum equal to Xdef findFourElements(A, n, X): # Fix the first element and find # other three for i in range(0,n-3): # Fix the second element and # find other two for j in range(i+1,n-2): # Fix the third element # and find the fourth for k in range(j+1,n-1): # find the fourth for l in range(k+1,n): if A[i] + A[j] + A[k] + A[l] == X: print (\"%d, %d, %d, %d\" %( A[i], A[j], A[k], A[l])) # Driver program to test above functionA = [10, 2, 3, 4, 5, 9, 7, 8]n = len(A)X = 23findFourElements (A, n, X) # This code is contributed by shreyanshi_arun",
"e": 29445,
"s": 28609,
"text": null
},
{
"code": "// C# program for naive solution to// print all combination of 4 elements// in A[] with sum equal to Xusing System; class FindFourElements{ void findFourElements(int []A, int n, int X) { // Fix the first element and find other three for (int i = 0; i < n - 3; i++) { // Fix the second element and find other two for (int j = i + 1; j < n - 2; j++) { // Fix the third element and find the fourth for (int k = j + 1; k < n - 1; k++) { // find the fourth for (int l = k + 1; l < n; l++) { if (A[i] + A[j] + A[k] + A[l] == X) Console.Write(A[i] + \" \" + A[j] + \" \" + A[k] + \" \" + A[l]); } } } } } // Driver program to test above functions public static void Main() { FindFourElements findfour = new FindFourElements(); int []A = {10, 20, 30, 40, 1, 2}; int n = A.Length; int X = 91; findfour.findFourElements(A, n, X); }} // This code is contributed by nitin mittal",
"e": 30648,
"s": 29445,
"text": null
},
{
"code": "<?php/* A naive solution to print all combinationof 4 elements in A[] with sum equal to X */ function findFourElements($A, $n, $X){ // Fix the first element and find other // three for ($i = 0; $i < $n-3; $i++) { // Fix the second element and find // other two for ($j = $i+1; $j < $n-2; $j++) { // Fix the third element and // find the fourth for ($k = $j+1; $k < $n-1; $k++) { // find the fourth for ($l = $k+1; $l < $n; $l++) if ($A[$i] + $A[$j] + $A[$k] + $A[$l] == $X) echo $A[$i], \", \" , $A[$j], \", \", $A[$k], \", \", $A[$l]; } } }} // Driver program to test above function $A = array (10, 20, 30, 40, 1, 2); $n = sizeof($A) ; $X = 91; findFourElements ($A, $n, $X); // This code is contributed by m_kit?>",
"e": 31622,
"s": 30648,
"text": null
},
{
"code": "<script> // Javascript program for the above approach /* A naive solution to print all combinationof 4 elements in A[]with sum equal to X */function findFourElements(A, n, X){ // Fix the first element and find other threefor (let i = 0; i < n - 3; i++){ // Fix the second element and find other two for (let j = i + 1; j < n - 2; j++) { // Fix the third element and find the fourth for (let k = j + 1; k < n - 1; k++) { // find the fourth for (let l = k + 1; l < n; l++) if (A[i] + A[j] + A[k] + A[l] == X) document.write(A[i]+\", \"+A[j]+\", \"+A[k] +\", \"+A[l]); } }}} // Driver Code let A = [10, 20, 30, 40, 1, 2]; let n = A.length; let X = 91; findFourElements (A, n, X); </script>",
"e": 32417,
"s": 31622,
"text": null
},
{
"code": null,
"e": 32425,
"s": 32417,
"text": "Output:"
},
{
"code": null,
"e": 32439,
"s": 32425,
"text": "20, 30, 40, 1"
},
{
"code": null,
"e": 32965,
"s": 32439,
"text": "Time Complexity: O(n^4)The time complexity can be improved to O(n^3) with the use of sorting as a preprocessing step, and then using method 1 of this post to reduce a loop.Following are the detailed steps. 1) Sort the input array. 2) Fix the first element as A[i] where i is from 0 to n–3. After fixing the first element of quadruple, fix the second element as A[j] where j varies from i+1 to n-2. Find remaining two elements in O(n) time, using the method 1 of this post Following is the implementation of O(n^3) solution. "
},
{
"code": null,
"e": 32969,
"s": 32965,
"text": "C++"
},
{
"code": null,
"e": 32971,
"s": 32969,
"text": "C"
},
{
"code": null,
"e": 32976,
"s": 32971,
"text": "Java"
},
{
"code": null,
"e": 32985,
"s": 32976,
"text": "Python 3"
},
{
"code": null,
"e": 32988,
"s": 32985,
"text": "C#"
},
{
"code": null,
"e": 32992,
"s": 32988,
"text": "PHP"
},
{
"code": null,
"e": 33003,
"s": 32992,
"text": "Javascript"
},
{
"code": "// C++ program for to print all combination// of 4 elements in A[] with sum equal to X#include<bits/stdc++.h>using namespace std; /* Following function is neededfor library function qsort(). */int compare (const void *a, const void * b){ return ( *(int *)a - *(int *)b );} /* A sorting based solution to printall combination of 4 elements in A[]with sum equal to X */void find4Numbers(int A[], int n, int X){ int l, r; // Sort the array in increasing // order, using library function // for quick sort qsort (A, n, sizeof(A[0]), compare); /* Now fix the first 2 elements one by one and find the other two elements */ for (int i = 0; i < n - 3; i++) { for (int j = i+1; j < n - 2; j++) { // Initialize two variables as // indexes of the first and last // elements in the remaining elements l = j + 1; r = n-1; // To find the remaining two // elements, move the index // variables (l & r) toward each other. while (l < r) { if( A[i] + A[j] + A[l] + A[r] == X) { cout << A[i]<<\", \" << A[j] << \", \" << A[l] << \", \" << A[r]; l++; r--; } else if (A[i] + A[j] + A[l] + A[r] < X) l++; else // A[i] + A[j] + A[l] + A[r] > X r--; } // end of while } // end of inner for loop } // end of outer for loop} /* Driver code */int main(){ int A[] = {1, 4, 45, 6, 10, 12}; int X = 21; int n = sizeof(A) / sizeof(A[0]); find4Numbers(A, n, X); return 0;} // This code is contributed by rathbhupendra",
"e": 34754,
"s": 33003,
"text": null
},
{
"code": "# include <stdio.h># include <stdlib.h> /* Following function is needed for library function qsort(). Refer http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){ return ( *(int *)a - *(int *)b ); } /* A sorting based solution to print all combination of 4 elements in A[] with sum equal to X */void find4Numbers(int A[], int n, int X){ int l, r; // Sort the array in increasing order, using library // function for quick sort qsort (A, n, sizeof(A[0]), compare); /* Now fix the first 2 elements one by one and find the other two elements */ for (int i = 0; i < n - 3; i++) { for (int j = i+1; j < n - 2; j++) { // Initialize two variables as indexes of the first and last // elements in the remaining elements l = j + 1; r = n-1; // To find the remaining two elements, move the index // variables (l & r) toward each other. while (l < r) { if( A[i] + A[j] + A[l] + A[r] == X) { printf(\"%d, %d, %d, %d\", A[i], A[j], A[l], A[r]); l++; r--; } else if (A[i] + A[j] + A[l] + A[r] < X) l++; else // A[i] + A[j] + A[l] + A[r] > X r--; } // end of while } // end of inner for loop } // end of outer for loop} /* Driver program to test above function */int main(){ int A[] = {1, 4, 45, 6, 10, 12}; int X = 21; int n = sizeof(A)/sizeof(A[0]); find4Numbers(A, n, X); return 0;}",
"e": 36437,
"s": 34754,
"text": null
},
{
"code": "import java.util.Arrays; class FindFourElements{ /* A sorting based solution to print all combination of 4 elements in A[] with sum equal to X */ void find4Numbers(int A[], int n, int X) { int l, r; // Sort the array in increasing order, using library // function for quick sort Arrays.sort(A); /* Now fix the first 2 elements one by one and find the other two elements */ for (int i = 0; i < n - 3; i++) { for (int j = i + 1; j < n - 2; j++) { // Initialize two variables as indexes of the first and last // elements in the remaining elements l = j + 1; r = n - 1; // To find the remaining two elements, move the index // variables (l & r) toward each other. while (l < r) { if (A[i] + A[j] + A[l] + A[r] == X) { System.out.println(A[i]+\" \"+A[j]+\" \"+A[l]+\" \"+A[r]); l++; r--; } else if (A[i] + A[j] + A[l] + A[r] < X) l++; else // A[i] + A[j] + A[l] + A[r] > X r--; } // end of while } // end of inner for loop } // end of outer for loop } // Driver program to test above functions public static void main(String[] args) { FindFourElements findfour = new FindFourElements(); int A[] = {1, 4, 45, 6, 10, 12}; int n = A.length; int X = 21; findfour.find4Numbers(A, n, X); }} // This code has been contributed by Mayank Jaiswal",
"e": 38177,
"s": 36437,
"text": null
},
{
"code": "# A sorting based solution to print all combination# of 4 elements in A[] with sum equal to Xdef find4Numbers(A, n, X): # Sort the array in increasing order, # using library function for quick sort A.sort() # Now fix the first 2 elements one by # one and find the other two elements for i in range(n - 3): for j in range(i + 1, n - 2): # Initialize two variables as indexes # of the first and last elements in # the remaining elements l = j + 1 r = n - 1 # To find the remaining two elements, # move the index variables (l & r) # toward each other. while (l < r): if(A[i] + A[j] + A[l] + A[r] == X): print(A[i], \",\", A[j], \",\", A[l], \",\", A[r]) l += 1 r -= 1 elif (A[i] + A[j] + A[l] + A[r] < X): l += 1 else: # A[i] + A[j] + A[l] + A[r] > X r -= 1 # Driver Codeif __name__ == \"__main__\": A = [1, 4, 45, 6, 10, 12] X = 21 n = len(A) find4Numbers(A, n, X) # This code is contributed by ita_c",
"e": 39407,
"s": 38177,
"text": null
},
{
"code": "// C# program for to print all combination// of 4 elements in A[] with sum equal to Xusing System; class FindFourElements{ // A sorting based solution to print all // combination of 4 elements in A[] with // sum equal to X void find4Numbers(int []A, int n, int X) { int l, r; // Sort the array in increasing order, // using library function for quick sort Array.Sort(A); /* Now fix the first 2 elements one by one and find the other two elements */ for (int i = 0; i < n - 3; i++) { for (int j = i + 1; j < n - 2; j++) { // Initialize two variables as indexes of // the first and last elements in the // remaining elements l = j + 1; r = n - 1; // To find the remaining two elements, move the // index variables (l & r) toward each other. while (l < r) { if (A[i] + A[j] + A[l] + A[r] == X) { Console.Write(A[i] + \" \" + A[j] + \" \" + A[l] + \" \" + A[r]); l++; r--; } else if (A[i] + A[j] + A[l] + A[r] < X) l++; else // A[i] + A[j] + A[l] + A[r] > X r--; } // end of while } // end of inner for loop } // end of outer for loop } // Driver program to test above functions public static void Main() { FindFourElements findfour = new FindFourElements(); int []A = {1, 4, 45, 6, 10, 12}; int n = A.Length; int X = 21; findfour.find4Numbers(A, n, X); }} // This code has been contributed by nitin mittal",
"e": 41344,
"s": 39407,
"text": null
},
{
"code": "<?php// PHP program for to print all// combination of 4 elements in// A[] with sum equal to X // A sorting based solution to// print all combination of 4// elements in A[] with sum// equal to Xfunction find4Numbers($A, $n, $X){ $l; $r; // Sort the array in increasing // order, using library function // for quick sort sort($A); // Now fix the first 2 elements // one by one and find the other // two elements for ($i = 0; $i < $n - 3; $i++) { for ($j = $i + 1; $j < $n - 2; $j++) { // Initialize two variables // as indexes of the first // and last elements in the // remaining elements $l = $j + 1; $r = $n - 1; // To find the remaining two // elements, move the index // variables (l & r) towards // each other. while ($l < $r) { if ($A[$i] + $A[$j] + $A[$l] + $A[$r] == $X) { echo $A[$i] , \" \" , $A[$j] , \" \" , $A[$l] , \" \" , $A[$r]; $l++; $r--; } else if ($A[$i] + $A[$j] + $A[$l] + $A[$r] < $X) $l++; // A[i] + A[j] + A[l] + A[r] > X else $r--; } } }} // Driver Code$A = array(1, 4, 45, 6, 10, 12);$n = count($A);$X = 21;find4Numbers($A, $n, $X); // This code is contributed// by nitin mittal?>",
"e": 42981,
"s": 41344,
"text": null
},
{
"code": "<script> /* A sorting based solution to print all combination of 4 elements in A[] with sum equal to X */ function find4Numbers(A,n,X) { let l, r; // Sort the array in increasing order, using library // function for quick sort A.sort(function(a, b){return a - b}); /* Now fix the first 2 elements one by one and find the other two elements */ for (let i = 0; i < n - 3; i++) { for (let j = i + 1; j < n - 2; j++) { // Initialize two variables as indexes of the first and last // elements in the remaining elements l = j + 1; r = n - 1; // To find the remaining two elements, move the index // variables (l & r) toward each other. while (l < r) { if (A[i] + A[j] + A[l] + A[r] == X) { document.write(A[i]+\" \"+A[j]+\" \"+A[l]+\" \"+A[r]+\"<br>\"); l++; r--; } else if ((A[i] + A[j] + A[l] + A[r]) < X) { l++; } else // A[i] + A[j] + A[l] + A[r] > X { r--; } } // end of while } // end of inner for loop }// end of outer for loop } // Driver program to test above functions let A= [1, 4, 45, 6, 10, 12]; let n = A.length; let X = 21; find4Numbers(A, n, X) // This code is contributed by rag2127 </script>",
"e": 44683,
"s": 42981,
"text": null
},
{
"code": null,
"e": 44693,
"s": 44683,
"text": "Output : "
},
{
"code": null,
"e": 44705,
"s": 44693,
"text": "1, 4, 6, 10"
},
{
"code": null,
"e": 44731,
"s": 44705,
"text": "Time Complexity : O(n^3) "
},
{
"code": null,
"e": 45597,
"s": 44731,
"text": "YouTubeGeeksforGeeks501K subscribersFind four elements that sum to a given value | Set 1 (n^3 solution) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:28•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0fo7goi2GEg\" 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": 45891,
"s": 45597,
"text": "This problem can also be solved in O(n^2Logn) complexity. Please refer below post for detailsFind four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 45904,
"s": 45891,
"text": "nitin mittal"
},
{
"code": null,
"e": 45910,
"s": 45904,
"text": "jit_t"
},
{
"code": null,
"e": 45915,
"s": 45910,
"text": "vt_m"
},
{
"code": null,
"e": 45921,
"s": 45915,
"text": "ukasp"
},
{
"code": null,
"e": 45934,
"s": 45921,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 45948,
"s": 45934,
"text": "rathbhupendra"
},
{
"code": null,
"e": 45962,
"s": 45948,
"text": "shubham_singh"
},
{
"code": null,
"e": 45978,
"s": 45962,
"text": "souravghosh0416"
},
{
"code": null,
"e": 45986,
"s": 45978,
"text": "rag2127"
},
{
"code": null,
"e": 45993,
"s": 45986,
"text": "Amazon"
},
{
"code": null,
"e": 46003,
"s": 45993,
"text": "OYO Rooms"
},
{
"code": null,
"e": 46025,
"s": 46003,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 46032,
"s": 46025,
"text": "Arrays"
},
{
"code": null,
"e": 46042,
"s": 46032,
"text": "Searching"
},
{
"code": null,
"e": 46049,
"s": 46042,
"text": "Amazon"
},
{
"code": null,
"e": 46059,
"s": 46049,
"text": "OYO Rooms"
},
{
"code": null,
"e": 46081,
"s": 46059,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 46088,
"s": 46081,
"text": "Arrays"
},
{
"code": null,
"e": 46098,
"s": 46088,
"text": "Searching"
},
{
"code": null,
"e": 46196,
"s": 46098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46205,
"s": 46196,
"text": "Comments"
},
{
"code": null,
"e": 46218,
"s": 46205,
"text": "Old Comments"
},
{
"code": null,
"e": 46266,
"s": 46218,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 46310,
"s": 46266,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 46342,
"s": 46310,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 46365,
"s": 46342,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 46379,
"s": 46365,
"text": "Linear Search"
},
{
"code": null,
"e": 46393,
"s": 46379,
"text": "Binary Search"
},
{
"code": null,
"e": 46407,
"s": 46393,
"text": "Linear Search"
},
{
"code": null,
"e": 46475,
"s": 46407,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 46499,
"s": 46475,
"text": "Find the Missing Number"
}
]
|
How to load and modify matrices and vectors in Octave? - GeeksforGeeks | 01 Aug, 2020
In this article, we will see how to load and play with the data inside matrices and vectors in Octave. Here are some basic commands and function to regarding with matrices and vector in Octave :
1. The dimensions of the matrix : We can find the dimensions of a matrix or vector using the size() function.
% declaring the matrix M = [1 2 3; 4 5 6; 7 8 9]; % dimensions of the matrixsize(M) % number of rowsrows = size(M, 1) % number of columnscols = size(M, 2)
Output :
ans =
3 3
rows = 3
cols = 3
2. Accessing the elements of the matrix : The elements of a matrix can be accessed by passing the location of the element in parentheses. In Octave, the indexing starts from 1.
% declaring the matrix M = [1 2 3; 4 5 6; 7 8 9]; % accessing the element at index (2, 3) % i.e. 2nd row and 3rd columnM(2, 3) % print the 3rd rowM(3, : ) % print the 1st columnM(:, 1) % print every thing from 1st and 3rd rowM([1, 3], : )
Output :
ans = 6
ans =
7 8 9
ans =
1
4
7
ans =
1 2 3
7 8 9
3. Longest Dimension : length() function returns the size of the longest dimension of the matrix/vector.
% declaring the row vectorM1 = [1 2 3 4 5 6 7 8 9 10];len_M1 = length(M1) % declaring the matrixM2 = [1 2 3; 4 5 6];len_M2 = length(M2)
Output :
len_M1 = 10
len_M2 = 3
4. Loading Data : First of all let us see how to identify the directories in Octave :
% see the present working directorypwd % see the directory's of the folder in which you arels
Output :
ans = /home/dikshant
derby.log Desktop Documents Downloads Music Pictures Public ${system:java.io.tmpdir} Templates Videos
Now before loading the data, we need to change our present working directory to the location where our data is stored. We can do this with the cd command and then load it as follows :
% changing the directorycd /home/dikshant/Documents/Octave-Project % list the data present in this directoryls
Output :
Feature.dat target.dat
Here we have taken the data of the scores of a student as Feature and their marks as target variable.This is the Feature.dat file which consists of 25 records of student’s study hours.
This is the target.dat file which consists of 25 records of student’s marks.
We can load the file with the load command in Octave, there are actually 2 ways to load the data either simply with load command or using the name of the file as a string in load(). We can use the name of the file like Feature or target to print its data.
% loading Feature.datload Feature.dat % or load('Feature.dat') % loading target.datload target.dat % or load('target.dat') % print Feature dataFeature % print target datatarget % displaying the size of Feature file i.e. the number of data records and columnFeature_size = size(Feature) % displaying the size of target file i.e. the number of data records and columntarget_size = size(target)
Output :
Feature =
2.5000
5.1000
3.2000
8.5000
3.5000
1.5000
9.2000
5.5000
8.3000
2.7000
7.7000
5.9000
4.5000
3.3000
1.1000
8.9000
2.5000
1.9000
6.1000
7.4000
2.7000
4.8000
3.8000
6.9000
7.8000
target =
21
47
27
75
30
20
88
60
81
25
85
62
41
42
17
95
30
24
67
69
30
54
35
76
86
Feature_size =
25 1
target_size =
25 1
We can use who command for knowing the variables in our current Octave scope or whos for more a detailed description.
% using the who commandwho % using the whos commandwhos
Output:
Variables in the current scope:
Feature M M1 M2 ans target
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
Feature 25x1 200 double
M 3x3 72 double
M1 1x10 80 double
M2 2x3 48 double
ans 1x2 16 double
target 25x1 200 double
Total is 77 elements using 616 bytes
We can also select some of the rows from a loaded file, for example in our case 25 records data is present in Feature and target, we can create some other variable to store the trimmed data rows as shown below :
% storing initial 5 records of Feature in varvar = Feature(1:5) % storing initial 5 records of target in var1var1 = target(1:5) % saving the data of var in a file named modified_Feature.mat in binary formatmodified_Feature.mat in binary format % saving the data of var1 in a file named modified_target.mat in binary formatmodified_target.mat in binary format % saves the data in a readable formatsave Feature_data.txt var -ASCII
Output:
var =
2.5000
5.1000
3.2000
8.5000
3.5000
var1 =
21
47
27
75
30
5. Modifying Data :Let us now see how to modify the data of matrices and vectors.
% declaring the matrixM = [1 2 3; 4 5 6; 7 8 9]; % modifying the data of 2nd column for each entryM(:, 2) = [54; 56; 98] % declaring the matrixm = [0 0 0; 0 0 0; 0 0 0]; % modifying the data of 3nd row for each entrym(3, = [100; 568; 987]
Output :
M =
1 54 3
4 56 6
7 98 9
m =
0 0 0
0 0 0
100 568 987
We can also append the new columns and rows in an existing matrix :
% declaring the matrixM = [1 2 3; 4 5 6; 7 8 9]; % appending the new column vector to your matrixM = [M, [20;30;40]]; % putting all values of matrix M in a single column vectorM(:)
Output :
ans =
1
4
7
2
5
8
3
6
9
20
30
40
We can also concatenate 2 different matrices :
% declaring the matricesa = [10 20; 30 40; 50 60];b = [11 22; 33 44; 55 66]; % concatenate matrix as "a" on the left and "b" on the rightc = [a b] % concatenate matrix as "a" on the top and "b" on the bottomc = [a ; b]
Output :
c =
10 20 11 22
30 40 33 44
50 60 55 66
c =
10 20
30 40
50 60
11 22
33 44
55 66
Octave-GNU
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Programming Languages to Learn in 2022
Difference between Shallow and Deep copy of a class
Advantages and Disadvantages of OOP
Java Swing | JComboBox with examples
Prolog | An Introduction
Program to calculate Electricity Bill
Top 10 Fastest Programming Languages
return 0 vs return 1 in C++
JLabel | Java Swing
10 Best IDEs for C or C++ Developers in 2021 | [
{
"code": null,
"e": 24532,
"s": 24504,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24727,
"s": 24532,
"text": "In this article, we will see how to load and play with the data inside matrices and vectors in Octave. Here are some basic commands and function to regarding with matrices and vector in Octave :"
},
{
"code": null,
"e": 24837,
"s": 24727,
"text": "1. The dimensions of the matrix : We can find the dimensions of a matrix or vector using the size() function."
},
{
"code": " % declaring the matrix M = [1 2 3; 4 5 6; 7 8 9]; % dimensions of the matrixsize(M) % number of rowsrows = size(M, 1) % number of columnscols = size(M, 2)",
"e": 25000,
"s": 24837,
"text": null
},
{
"code": null,
"e": 25009,
"s": 25000,
"text": "Output :"
},
{
"code": null,
"e": 25051,
"s": 25009,
"text": " \nans =\n\n 3 3\n\nrows = 3\ncols = 3\n"
},
{
"code": null,
"e": 25228,
"s": 25051,
"text": "2. Accessing the elements of the matrix : The elements of a matrix can be accessed by passing the location of the element in parentheses. In Octave, the indexing starts from 1."
},
{
"code": " % declaring the matrix M = [1 2 3; 4 5 6; 7 8 9]; % accessing the element at index (2, 3) % i.e. 2nd row and 3rd columnM(2, 3) % print the 3rd rowM(3, : ) % print the 1st columnM(:, 1) % print every thing from 1st and 3rd rowM([1, 3], : )",
"e": 25478,
"s": 25228,
"text": null
},
{
"code": null,
"e": 25487,
"s": 25478,
"text": "Output :"
},
{
"code": null,
"e": 25581,
"s": 25487,
"text": " \nans = 6 \n\nans =\n\n 7 8 9\n\nans =\n\n 1\n 4\n 7\n\nans =\n\n 1 2 3\n 7 8 9 \n"
},
{
"code": null,
"e": 25686,
"s": 25581,
"text": "3. Longest Dimension : length() function returns the size of the longest dimension of the matrix/vector."
},
{
"code": " % declaring the row vectorM1 = [1 2 3 4 5 6 7 8 9 10];len_M1 = length(M1) % declaring the matrixM2 = [1 2 3; 4 5 6];len_M2 = length(M2)",
"e": 25827,
"s": 25686,
"text": null
},
{
"code": null,
"e": 25836,
"s": 25827,
"text": "Output :"
},
{
"code": null,
"e": 25862,
"s": 25836,
"text": "len_M1 = 10\nlen_M2 = 3\n"
},
{
"code": null,
"e": 25948,
"s": 25862,
"text": "4. Loading Data : First of all let us see how to identify the directories in Octave :"
},
{
"code": " % see the present working directorypwd % see the directory's of the folder in which you arels",
"e": 26049,
"s": 25948,
"text": null
},
{
"code": null,
"e": 26058,
"s": 26049,
"text": "Output :"
},
{
"code": null,
"e": 26191,
"s": 26058,
"text": "ans = /home/dikshant\nderby.log Desktop Documents Downloads Music Pictures Public ${system:java.io.tmpdir} Templates Videos\n"
},
{
"code": null,
"e": 26375,
"s": 26191,
"text": "Now before loading the data, we need to change our present working directory to the location where our data is stored. We can do this with the cd command and then load it as follows :"
},
{
"code": " % changing the directorycd /home/dikshant/Documents/Octave-Project % list the data present in this directoryls",
"e": 26490,
"s": 26375,
"text": null
},
{
"code": null,
"e": 26499,
"s": 26490,
"text": "Output :"
},
{
"code": null,
"e": 26524,
"s": 26499,
"text": "Feature.dat target.dat\n"
},
{
"code": null,
"e": 26709,
"s": 26524,
"text": "Here we have taken the data of the scores of a student as Feature and their marks as target variable.This is the Feature.dat file which consists of 25 records of student’s study hours."
},
{
"code": null,
"e": 26786,
"s": 26709,
"text": "This is the target.dat file which consists of 25 records of student’s marks."
},
{
"code": null,
"e": 27042,
"s": 26786,
"text": "We can load the file with the load command in Octave, there are actually 2 ways to load the data either simply with load command or using the name of the file as a string in load(). We can use the name of the file like Feature or target to print its data."
},
{
"code": " % loading Feature.datload Feature.dat % or load('Feature.dat') % loading target.datload target.dat % or load('target.dat') % print Feature dataFeature % print target datatarget % displaying the size of Feature file i.e. the number of data records and columnFeature_size = size(Feature) % displaying the size of target file i.e. the number of data records and columntarget_size = size(target)",
"e": 27445,
"s": 27042,
"text": null
},
{
"code": null,
"e": 27454,
"s": 27445,
"text": "Output :"
},
{
"code": null,
"e": 27932,
"s": 27454,
"text": "Feature =\n\n 2.5000\n 5.1000\n 3.2000\n 8.5000\n 3.5000\n 1.5000\n 9.2000\n 5.5000\n 8.3000\n 2.7000\n 7.7000\n 5.9000\n 4.5000\n 3.3000\n 1.1000\n 8.9000\n 2.5000\n 1.9000\n 6.1000\n 7.4000\n 2.7000\n 4.8000\n 3.8000\n 6.9000\n 7.8000\n\ntarget =\n\n 21\n 47\n 27\n 75\n 30\n 20\n 88\n 60\n 81\n 25\n 85\n 62\n 41\n 42\n 17\n 95\n 30\n 24\n 67\n 69\n 30\n 54\n 35\n 76\n 86\n\nFeature_size =\n\n 25 1\n\ntarget_size =\n\n 25 1\n"
},
{
"code": null,
"e": 28050,
"s": 27932,
"text": "We can use who command for knowing the variables in our current Octave scope or whos for more a detailed description."
},
{
"code": " % using the who commandwho % using the whos commandwhos",
"e": 28110,
"s": 28050,
"text": null
},
{
"code": null,
"e": 28118,
"s": 28110,
"text": "Output:"
},
{
"code": null,
"e": 28754,
"s": 28118,
"text": "Variables in the current scope:\n\nFeature M M1 M2 ans target\n\nVariables in the current scope:\n\n Attr Name Size Bytes Class\n ==== ==== ==== ===== =====\n Feature 25x1 200 double\n M 3x3 72 double\n M1 1x10 80 double\n M2 2x3 48 double\n ans 1x2 16 double\n target 25x1 200 double\n\nTotal is 77 elements using 616 bytes\n"
},
{
"code": null,
"e": 28966,
"s": 28754,
"text": "We can also select some of the rows from a loaded file, for example in our case 25 records data is present in Feature and target, we can create some other variable to store the trimmed data rows as shown below :"
},
{
"code": " % storing initial 5 records of Feature in varvar = Feature(1:5) % storing initial 5 records of target in var1var1 = target(1:5) % saving the data of var in a file named modified_Feature.mat in binary formatmodified_Feature.mat in binary format % saving the data of var1 in a file named modified_target.mat in binary formatmodified_target.mat in binary format % saves the data in a readable formatsave Feature_data.txt var -ASCII",
"e": 29402,
"s": 28966,
"text": null
},
{
"code": null,
"e": 29410,
"s": 29402,
"text": "Output:"
},
{
"code": null,
"e": 29507,
"s": 29410,
"text": "var =\n\n 2.5000\n 5.1000\n 3.2000\n 8.5000\n 3.5000\n\nvar1 =\n\n 21\n 47\n 27\n 75\n 30\n"
},
{
"code": null,
"e": 29589,
"s": 29507,
"text": "5. Modifying Data :Let us now see how to modify the data of matrices and vectors."
},
{
"code": " % declaring the matrixM = [1 2 3; 4 5 6; 7 8 9]; % modifying the data of 2nd column for each entryM(:, 2) = [54; 56; 98] % declaring the matrixm = [0 0 0; 0 0 0; 0 0 0]; % modifying the data of 3nd row for each entrym(3, = [100; 568; 987]",
"e": 29835,
"s": 29589,
"text": null
},
{
"code": null,
"e": 29844,
"s": 29835,
"text": "Output :"
},
{
"code": null,
"e": 29961,
"s": 29844,
"text": "M =\n\n 1 54 3\n 4 56 6\n 7 98 9\n\nm =\n\n 0 0 0\n 0 0 0\n 100 568 987\n"
},
{
"code": null,
"e": 30029,
"s": 29961,
"text": "We can also append the new columns and rows in an existing matrix :"
},
{
"code": " % declaring the matrixM = [1 2 3; 4 5 6; 7 8 9]; % appending the new column vector to your matrixM = [M, [20;30;40]]; % putting all values of matrix M in a single column vectorM(:)",
"e": 30215,
"s": 30029,
"text": null
},
{
"code": null,
"e": 30224,
"s": 30215,
"text": "Output :"
},
{
"code": null,
"e": 30304,
"s": 30224,
"text": "ans =\n\n 1\n 4\n 7\n 2\n 5\n 8\n 3\n 6\n 9\n 20\n 30\n 40\n"
},
{
"code": null,
"e": 30351,
"s": 30304,
"text": "We can also concatenate 2 different matrices :"
},
{
"code": " % declaring the matricesa = [10 20; 30 40; 50 60];b = [11 22; 33 44; 55 66]; % concatenate matrix as \"a\" on the left and \"b\" on the rightc = [a b] % concatenate matrix as \"a\" on the top and \"b\" on the bottomc = [a ; b]",
"e": 30575,
"s": 30351,
"text": null
},
{
"code": null,
"e": 30584,
"s": 30575,
"text": "Output :"
},
{
"code": null,
"e": 30725,
"s": 30584,
"text": "c =\n\n 10 20 11 22\n 30 40 33 44\n 50 60 55 66\n\nc =\n\n 10 20\n 30 40\n 50 60\n 11 22\n 33 44\n 55 66\n"
},
{
"code": null,
"e": 30736,
"s": 30725,
"text": "Octave-GNU"
},
{
"code": null,
"e": 30757,
"s": 30736,
"text": "Programming Language"
},
{
"code": null,
"e": 30855,
"s": 30757,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30864,
"s": 30855,
"text": "Comments"
},
{
"code": null,
"e": 30877,
"s": 30864,
"text": "Old Comments"
},
{
"code": null,
"e": 30923,
"s": 30877,
"text": "Top 10 Programming Languages to Learn in 2022"
},
{
"code": null,
"e": 30975,
"s": 30923,
"text": "Difference between Shallow and Deep copy of a class"
},
{
"code": null,
"e": 31011,
"s": 30975,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 31048,
"s": 31011,
"text": "Java Swing | JComboBox with examples"
},
{
"code": null,
"e": 31073,
"s": 31048,
"text": "Prolog | An Introduction"
},
{
"code": null,
"e": 31111,
"s": 31073,
"text": "Program to calculate Electricity Bill"
},
{
"code": null,
"e": 31148,
"s": 31111,
"text": "Top 10 Fastest Programming Languages"
},
{
"code": null,
"e": 31176,
"s": 31148,
"text": "return 0 vs return 1 in C++"
},
{
"code": null,
"e": 31196,
"s": 31176,
"text": "JLabel | Java Swing"
}
]
|
Spread operator for arrays in JavaScript | The spread (...) syntax allow us to expand an iterable like array in places where 0+ arguments are expected. It allows us to pass a number of parameters as an array to a
function.
Following is the code to implement spread operator for arrays in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,
.sample {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
.sample {
color: red;
}
</style>
</head>
<body>
<h1>Spread operator for arrays JavaScript</h1>
<div class="sample">[22,55,11,19,55]</div>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call the add function and pass the above
array as parameter</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
function add(num1, num2, num3, num4, num5) {
return num1 + num2 + num3 + num4 + num5;
}
let arr = [22, 55, 11, 19, 55];
BtnEle.addEventListener("click", (event) => {
resEle.innerHTML = "The sum of the above array = " + add(...arr);
});
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button − | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "The spread (...) syntax allow us to expand an iterable like array in places where 0+ arguments are expected. It allows us to pass a number of parameters as an array to a\nfunction."
},
{
"code": null,
"e": 1320,
"s": 1242,
"text": "Following is the code to implement spread operator for arrays in JavaScript −"
},
{
"code": null,
"e": 1331,
"s": 1320,
"text": " Live Demo"
},
{
"code": null,
"e": 2402,
"s": 1331,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result,\n .sample {\n font-size: 20px;\n font-weight: 500;\n color: blueviolet;\n }\n .sample {\n color: red;\n}\n</style>\n</head>\n<body>\n<h1>Spread operator for arrays JavaScript</h1>\n<div class=\"sample\">[22,55,11,19,55]</div>\n<div class=\"result\"></div>\n<br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to call the add function and pass the above\narray as parameter</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n function add(num1, num2, num3, num4, num5) {\n return num1 + num2 + num3 + num4 + num5;\n }\n let arr = [22, 55, 11, 19, 55];\n BtnEle.addEventListener(\"click\", (event) => {\n resEle.innerHTML = \"The sum of the above array = \" + add(...arr);\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2440,
"s": 2402,
"text": "On clicking the ‘CLICK HERE’ button −"
}
]
|
Command Line arguments in Lua | Handling command line arguments in Lua is one of the key features of any programming language. In Lua, the command line arguments are stored in a table named args and we can use the indices to extract any particular command line argument we require.
lua [options] [script [args]]
The options are −
-e stat− executes string stat;
-l mod− "requires" mod;
-i− enters interactive mode after running script;
-v− prints version information;
--− stops handling options;
-− executes stdin as a file and stops handling
options.
Let’s consider an example where we will open a Lua shell in interactive mode and we will pass the script as dev/null and then we will pass our arguments.
lua -i -- /dev/null one two three
It should be noted that the above command will work only if Lua is installed on your local machine.
The above command opens the terminal in an interactive mode.
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio
Now we can access the arguments that we passed, as we know they are stored in a table named args.
Consider the example shown below −
lua -i -- /dev/null one two three
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio
>print(arg[1]) one
>print(arg[2]) two
>print(arg[3]0
stdin:1: ')' expected near '0'
>print(arg[3]) three
>print(arg[0])
/dev/null
one
two
three
/dev/null | [
{
"code": null,
"e": 1312,
"s": 1062,
"text": "Handling command line arguments in Lua is one of the key features of any programming language. In Lua, the command line arguments are stored in a table named args and we can use the indices to extract any particular command line argument we require."
},
{
"code": null,
"e": 1342,
"s": 1312,
"text": "lua [options] [script [args]]"
},
{
"code": null,
"e": 1360,
"s": 1342,
"text": "The options are −"
},
{
"code": null,
"e": 1391,
"s": 1360,
"text": "-e stat− executes string stat;"
},
{
"code": null,
"e": 1415,
"s": 1391,
"text": "-l mod− \"requires\" mod;"
},
{
"code": null,
"e": 1465,
"s": 1415,
"text": "-i− enters interactive mode after running script;"
},
{
"code": null,
"e": 1497,
"s": 1465,
"text": "-v− prints version information;"
},
{
"code": null,
"e": 1525,
"s": 1497,
"text": "--− stops handling options;"
},
{
"code": null,
"e": 1572,
"s": 1525,
"text": "-− executes stdin as a file and stops handling"
},
{
"code": null,
"e": 1581,
"s": 1572,
"text": "options."
},
{
"code": null,
"e": 1735,
"s": 1581,
"text": "Let’s consider an example where we will open a Lua shell in interactive mode and we will pass the script as dev/null and then we will pass our arguments."
},
{
"code": null,
"e": 1769,
"s": 1735,
"text": "lua -i -- /dev/null one two three"
},
{
"code": null,
"e": 1869,
"s": 1769,
"text": "It should be noted that the above command will work only if Lua is installed on your local machine."
},
{
"code": null,
"e": 1930,
"s": 1869,
"text": "The above command opens the terminal in an interactive mode."
},
{
"code": null,
"e": 1981,
"s": 1930,
"text": "Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio"
},
{
"code": null,
"e": 2079,
"s": 1981,
"text": "Now we can access the arguments that we passed, as we know they are stored in a table named args."
},
{
"code": null,
"e": 2114,
"s": 2079,
"text": "Consider the example shown below −"
},
{
"code": null,
"e": 2329,
"s": 2114,
"text": "lua -i -- /dev/null one two three\nLua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio\n>print(arg[1]) one\n>print(arg[2]) two\n>print(arg[3]0\nstdin:1: ')' expected near '0'\n>print(arg[3]) three\n>print(arg[0])\n/dev/null"
},
{
"code": null,
"e": 2353,
"s": 2329,
"text": "one\ntwo\nthree\n/dev/null"
}
]
|
Print "Even" or "Odd" without using conditional statement - GeeksforGeeks | 17 Aug, 2021
Write a program that accepts a number from the user and prints “Even” if the entered number is even and prints “Odd” if the number is odd. You are not allowed to use any comparison (==, <,>,...etc) or conditional statements (if, else, switch, ternary operator,. Etc).
Method 1 Below is a tricky code can be used to print “Even” or “Odd” accordingly.
C++
Java
Python3
C#
PHP
Javascript
#include <iostream> using namespace std; int main(){ char arr[2][5] = { "Even", "Odd" }; int no; cout << "Enter a number: "; cin >> no; cout << arr[no % 2]; getchar(); return 0;}
import java.util.Scanner;class GFG{ public static void main(String[] args) { String[] arr = {"Even", "Odd"}; Scanner s = new Scanner(System.in); System.out.print("Enter the number: "); int no = s.nextInt(); System.out.println(arr[no%2]); }} // This code is contributed by divyeshrabadiya07.
arr = ["Even", "Odd"]print ("Enter the number")no = int(input())print (arr[no % 2])
using System;class GFG { static void Main() { string[] arr = {"Even", "Odd"}; Console.Write("Enter the number: "); string val; val = Console.ReadLine(); int no = Convert.ToInt32(val); Console.WriteLine(arr[no%2]); }} // This code is contributed by divyesh072019.
<?php$arr = ["Even", "Odd"];$input = 5;echo ($arr[$input % 2]); // This code is contributed// by Aman ojha?>
<script> let arr = ["Even", "Odd"]; let no = prompt("Enter a number: "); document.write(arr[no % 2]); // This code is contributed by suresh07 </script>
Method 2 Below is another tricky code can be used to print “Even” or “Odd” accordingly. Thanks to student for suggesting this method.
C++
#include<stdio.h>int main(){ int no; printf("Enter a no: "); scanf("%d", &no); (no & 1 && printf("odd"))|| printf("even"); return 0;}
Enter a no: even
Please write comments if you find the above code incorrect, or find better ways to solve the same problem
Method 3This can also be done using a concept known as Branchless Programming. Essentially, make use of the fact that a true statement in Python (other some other languages) evaluates to 1 and a false statements evaluates to false.
Python3
# coden = int(input("Enter a number: "))print("Even" * (n % 2 == 0), "Odd" * (n % 2 != 0))
Enter a number: Even
Prateek Bajaj
Aman ojha
divyeshrabadiya07
divyesh072019
kumarv456
suresh07
mv72d9gyw3u06zvq4i4elurjcmu1d239e0cn047m
sarcasm1o1
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 25196,
"s": 25168,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 25464,
"s": 25196,
"text": "Write a program that accepts a number from the user and prints “Even” if the entered number is even and prints “Odd” if the number is odd. You are not allowed to use any comparison (==, <,>,...etc) or conditional statements (if, else, switch, ternary operator,. Etc)."
},
{
"code": null,
"e": 25547,
"s": 25464,
"text": "Method 1 Below is a tricky code can be used to print “Even” or “Odd” accordingly. "
},
{
"code": null,
"e": 25551,
"s": 25547,
"text": "C++"
},
{
"code": null,
"e": 25556,
"s": 25551,
"text": "Java"
},
{
"code": null,
"e": 25564,
"s": 25556,
"text": "Python3"
},
{
"code": null,
"e": 25567,
"s": 25564,
"text": "C#"
},
{
"code": null,
"e": 25571,
"s": 25567,
"text": "PHP"
},
{
"code": null,
"e": 25582,
"s": 25571,
"text": "Javascript"
},
{
"code": "#include <iostream> using namespace std; int main(){ char arr[2][5] = { \"Even\", \"Odd\" }; int no; cout << \"Enter a number: \"; cin >> no; cout << arr[no % 2]; getchar(); return 0;}",
"e": 25782,
"s": 25582,
"text": null
},
{
"code": "import java.util.Scanner;class GFG{ public static void main(String[] args) { String[] arr = {\"Even\", \"Odd\"}; Scanner s = new Scanner(System.in); System.out.print(\"Enter the number: \"); int no = s.nextInt(); System.out.println(arr[no%2]); }} // This code is contributed by divyeshrabadiya07.",
"e": 26145,
"s": 25782,
"text": null
},
{
"code": "arr = [\"Even\", \"Odd\"]print (\"Enter the number\")no = int(input())print (arr[no % 2])",
"e": 26229,
"s": 26145,
"text": null
},
{
"code": "using System;class GFG { static void Main() { string[] arr = {\"Even\", \"Odd\"}; Console.Write(\"Enter the number: \"); string val; val = Console.ReadLine(); int no = Convert.ToInt32(val); Console.WriteLine(arr[no%2]); }} // This code is contributed by divyesh072019.",
"e": 26524,
"s": 26229,
"text": null
},
{
"code": "<?php$arr = [\"Even\", \"Odd\"];$input = 5;echo ($arr[$input % 2]); // This code is contributed// by Aman ojha?>",
"e": 26633,
"s": 26524,
"text": null
},
{
"code": "<script> let arr = [\"Even\", \"Odd\"]; let no = prompt(\"Enter a number: \"); document.write(arr[no % 2]); // This code is contributed by suresh07 </script>",
"e": 26810,
"s": 26633,
"text": null
},
{
"code": null,
"e": 26944,
"s": 26810,
"text": "Method 2 Below is another tricky code can be used to print “Even” or “Odd” accordingly. Thanks to student for suggesting this method."
},
{
"code": null,
"e": 26948,
"s": 26944,
"text": "C++"
},
{
"code": "#include<stdio.h>int main(){ int no; printf(\"Enter a no: \"); scanf(\"%d\", &no); (no & 1 && printf(\"odd\"))|| printf(\"even\"); return 0;}",
"e": 27097,
"s": 26948,
"text": null
},
{
"code": null,
"e": 27114,
"s": 27097,
"text": "Enter a no: even"
},
{
"code": null,
"e": 27220,
"s": 27114,
"text": "Please write comments if you find the above code incorrect, or find better ways to solve the same problem"
},
{
"code": null,
"e": 27453,
"s": 27220,
"text": "Method 3This can also be done using a concept known as Branchless Programming. Essentially, make use of the fact that a true statement in Python (other some other languages) evaluates to 1 and a false statements evaluates to false. "
},
{
"code": null,
"e": 27461,
"s": 27453,
"text": "Python3"
},
{
"code": "# coden = int(input(\"Enter a number: \"))print(\"Even\" * (n % 2 == 0), \"Odd\" * (n % 2 != 0))",
"e": 27552,
"s": 27461,
"text": null
},
{
"code": null,
"e": 27574,
"s": 27552,
"text": "Enter a number: Even "
},
{
"code": null,
"e": 27588,
"s": 27574,
"text": "Prateek Bajaj"
},
{
"code": null,
"e": 27598,
"s": 27588,
"text": "Aman ojha"
},
{
"code": null,
"e": 27616,
"s": 27598,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 27630,
"s": 27616,
"text": "divyesh072019"
},
{
"code": null,
"e": 27640,
"s": 27630,
"text": "kumarv456"
},
{
"code": null,
"e": 27649,
"s": 27640,
"text": "suresh07"
},
{
"code": null,
"e": 27690,
"s": 27649,
"text": "mv72d9gyw3u06zvq4i4elurjcmu1d239e0cn047m"
},
{
"code": null,
"e": 27701,
"s": 27690,
"text": "sarcasm1o1"
},
{
"code": null,
"e": 27712,
"s": 27701,
"text": "C Language"
},
{
"code": null,
"e": 27716,
"s": 27712,
"text": "C++"
},
{
"code": null,
"e": 27720,
"s": 27716,
"text": "CPP"
},
{
"code": null,
"e": 27818,
"s": 27720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27853,
"s": 27818,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27881,
"s": 27853,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27893,
"s": 27881,
"text": "fork() in C"
},
{
"code": null,
"e": 27933,
"s": 27893,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 27979,
"s": 27933,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27997,
"s": 27979,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28043,
"s": 27997,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28062,
"s": 28043,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28105,
"s": 28062,
"text": "Map in C++ Standard Template Library (STL)"
}
]
|
Mining Twitter Data. Inside Social Media | by Paul Charles Owe | Towards Data Science | Twitter is a microblogging and social networking service where users post content and interact with posts known as “tweets”. Today, Twitter has popularized the use of hashtags as a way to group conversations and allow users to follow conversations on particular topics.
With over 500 million tweets per day, you can imagine how rich with information this platform is. The objective of this project is to gather and analyze twitter data in order to discover interesting information and hidden patterns.
This post serves as a “technical reflection” of my experience completing this task. I will be showing and briefly explaining relevant code snippets as well as results of my analysis. Here’s an overview of key steps I think are worth talking about.
AuthenticationData CollectionData Cleaning and PreprocessingModelling and AnalysisConclusion
Authentication
Data Collection
Data Cleaning and Preprocessing
Modelling and Analysis
Conclusion
In this application the authentication step was performed using the industry standard OAuth process which involves the user, consumer (the app) and the resource provider (Twitter). The key takeaway from this is that the exchange of credentials like username and password only happens between the user and the resource provider. All other exchanges are driven by tokens.
Creating a Twitter Developer Account. You need a developer account to have access to the twitter API. Once you create an application you may generate the Consumer Key, Consumer Secret, Access token and Access secret
I chose tweepy as my Twitter API client and I chose to create environment variables for my tokens as it promotes security and is language agnostic. Here is how I setup my twitter client.
import osimport sysfrom tweepy import APIfrom tweepy import OAuthHandlerdef get_twitter_auth(): #set up twitter authentication# Return: tweepy.OAuthHandler objecttry: consumer_key = os.environ['TWITTER_CONSUMER_KEY'] consumer_secret = os.environ['TWITTER_CONSUMER_SECRET'] access_token = os.environ['TWITTER_ACCESS_TOKEN'] access_secret= os.environ['TWITTER_ACCESS_SECRET'] except KeyError: sys.stderr.write("TWITTER_* environment variables not set\n") sys.exit(1) auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) return authdef get_twitter_client(): #Setup twitter API client.# Return tweepy.API objectauth = get_twitter_auth() client = API(auth) return client
After the preliminary set ups. I could immediately start gathering data and interacting with the API.
Interacting with twitter’s REST API
All REST endpoints allow you to “go back in time”, meaning we are able to search for already published tweets.
Interacting with twitter’s Streaming API
The Streaming API looks into the future. Once you open a connection, you may leave it open and go forward in time. By keeping the HTTP connection open, we can retrieve all the tweets that match our filter criteria as they are published.
This is generally the preferred way of downloading a huge number of tweets.
In my case, I wanted to investigate realtime conversations among users during the US-Iran tension in December 2019 so I decided to stream all tweets with trending hashtags such as #USIran #USvsIran #Iranattacks
Here is how I implemented a custom stream listener.
class CustomListener(StreamListener): """ Custom StreamListener for streaming twitter data."""def __init__(self, fname): safe_fname = format_filename(fname) self.outfile = "stream_%s.jsonl" % safe_fnamedef on_data(self, data): #called when data is coming through. This method simply stores data as it is received in a .jsonl file. Each line in this file will contain a single tweet in json format try: with open(self.outfile, 'a') as f: f.write(data) return True except BaseException as e: sys.stderr.write("Error on_data: {}\n".format(e)) time.sleep(5) return True ...if __name__ == '__main__': query = sys.argv[1:] # list of CLI argumentsquery_fname query_fname = ' '.join(query) # string auth = get_twitter_auth() twitter_stream = Stream(auth, CustomListener(query_fname)) twitter_stream.filter(track=query, is_async=True)
So, after streaming for about an hour, I managed to gather 13, 908 tweets from users who were talking about the US-Iran tension. I stored these tweets in a .jsonl file and it was time to pre-process the text. Here are some preprocessing tasks I performed:
Tokenization using nltk library
Tokenization refers to breaking down a stream of texts into tokens such as words, phrases, symbols. The content of a tweet includes emojis, user mentions, hasthags, urls etc. For this reason, when using the nltk library, I will showcase the use of the TweetTokenizer class as a tool to appropriately tokenize twitter content.
Stop word removal
Stop words are not content bearing and so we need to remove them. This category of words include articles, adverbs, symbols, punctuation, etc. Frequency analysis shows that these strings are the most frequently occurring in a document.
Normalization
Normalization is used to aggregate different terms in the same unit. Performing case normalization will help in automatically matching these strings with originally different casing so that they can be aggregated under the same term.
import sysimport stringimport jsonfrom collections import Counterfrom nltk.tokenize import TweetTokenizerfrom nltk.corpus import stopwordsimport matplotlib.pyplot as pltdef process(text, tokenizer=TweetTokenizer(), stopwords=[]): """ Process tweet text: - Lowercase - tokenize - stopword removal - digits removal Return: list of strings """text = text.lower() tokens = tokenizer.tokenize(text) return [tok for tok in tokens if tok not in stopwords and not tok.isdigit()]if __name__ == '__main__': fname = sys.argv[1] tweet_tokenizer = TweetTokenizer() punct = list(string.punctuation) stopword_list = stopwords.words('english') + punct + ['rt', 'via', '...']tf = Counter() with open(fname, 'r') as f: for line in f: tweet = json.loads(line) tokens = process(text=tweet['text'], tokenizer=tweet_tokenizer, stopwords=stopword_list) tf.update(tokens) for tag, count in tf.most_common(20):print("{}: {}".format(tag, count))#plot resultsy = [count for tag, count in tf.most_common(20)] x = range(1, len(y)+1)plt.bar(x, y) plt.title("Term frequencies used in US-Iran Stream Data") plt.ylabel("Frequency") plt.savefig('us-iran-term-distn.png')
In the above snippet, I began the analysis by creating a visual representation of the term distribution of the 20 most common terms used in the tweets I collected.
Continuing the analysis, I searched the dataset for the key people everybody was talking about by finding their mention frequency.
With this information, I knew exactly which profiles I could start investigating to receive a more related feed. It was shocking, however, to discover that realdonaldtrump ranked 8th in popular user mentions related to this issue.
Time Series Analysis
A time series is a sequence of data points that consists of successive observation over a given time interval
It can be used to reorder tweets and track how users react to realtime events (such as — Sports, political elections, news)
In this application, I performed a time series analysis to monitor how users were tweeting as more news about this topic was being released. It seems to me as though within the hour I was streaming, users were actively tweeting about the topic throughout, with a peak of 200 tweets collected around 10:45AM
Users, Followers and Friends
I decided to explore some of the top users’ profiles, list of followers and “following” (or friends) for further analysis. Here is how I pulled this information from twitter.
#get followers for a given userfname = "Twitter_Profiles/{}/followers.jsonl".format(screen_name) with open(fname, 'w') as f: for followers in Cursor(client.followers_ids, screen_name=screen_name).pages(max_pages): for chunk in paginate(followers, 100): users = client.lookup_users(user_ids=chunk) for user in users: f.write(json.dumps(user._json)+"\n") if len(followers) == 5000: print("More results available. Sleeping for 60 seconds to avoid rate limit") time.sleep(60)#get friends for a given userfname = "Twitter_Profiles/{}/friends.jsonl".format(screen_name) with open(fname, 'w') as f: for friends in Cursor(client.friends_ids, screen_name=screen_name).pages(max_pages): for chunk in paginate(friends, 100): users = client.lookup_users(user_ids=chunk) for user in users: f.write(json.dumps(user._json)+"\n") if len(friends) == 5000: print("More results available. Sleeping for 60 seconds to avoid rate limit") time.sleep(60)# get user's profile fname = "Twitter_Profiles/{}/user_profile.json".format(screen_name) with open(fname, 'w') as f: profile = client.get_user(screen_name=screen_name) f.write(json.dumps(profile._json, indent=4))
Measuring Influence and Engagement
A metric of engagement provides an assessment of users’ responses to tweets and other content, often created with the purpose to drive traffic. On twitter, users engage by means of liking or retweeting — which provides more visibility to the tweets
Understanding the influence of a user involves analyzing the user’s reach in combination with their tweet engagement statistics.
#Build up a list of followers followers_file1 = 'Twitter_Profiles/{}/followers.jsonl'.format(screen_name1) followers_file2 = 'Twitter_Profiles/{}/followers.jsonl'.format(screen_name2)with open(followers_file1) as f1, open(followers_file2) as f2: reach1 = [] reach2 = [] for line in f1: profile = json.loads(line) reach1.append((profile['screen_name'], profile['followers_count'])) for line in f2: profile = json.loads(line) reach2.append((profile['screen_name'], profile['followers_count']))#Load basic statistics profile_file1 = 'Twitter_Profiles/{}/user_profile.json'.format(screen_name1) profile_file2 = 'Twitter_Profiles/{}/user_profile.json'.format(screen_name2) with open(profile_file1) as f1, open(profile_file2) as f2: profile1 = json.load(f1) profile2 = json.load(f2)followers1 = profile1['followers_count'] followers2 = profile2['followers_count']tweets1 = profile['statuses_count'] tweets2 = profile['statuses_count']sum_reach1 = sum([x[1] for x in reach1]) #sum up all of a user's followers, followers sum_reach2 = sum([x[1] for x in reach2]) avg_followers1 = round(sum_reach1/ followers1, 2) avg_followers2 = round(sum_reach2/ followers2, 2)#Load the timelines for two users to observe the number of times their tweets have been favorited timeline_file1 = 'user_timeline_{}.jsonl'.format(screen_name1) timeline_file2 = 'user_timeline_{}.jsonl'.format(screen_name2) with open(timeline_file1) as f1, open(timeline_file2) as f2: favorited_count1, retweet_count1 = [], [] favorited_count2, retweet_count2 = [], [] for line in f1: tweet = json.loads(line) favorited_count1.append(tweet['favorite_count']) retweet_count1.append(tweet['retweet_count'])for line in f2: tweet = json.loads(line) favorited_count2.append(tweet['favorite_count']) retweet_count2.append(tweet['retweet_count'])
Complete scripts for doing this can be found on my GitHub
Mining Social Communities
A social community is a group of people who share some common conditions e.g geographical area, same religious beliefs, or people who share same interests.
Explicit community — people with common interests and explicitly know exactly whether they belong to a community or not and typically understand who other members in the said community are.
Implicit communities — come into existence when members share common interests without having clear and strong connections between each other
In the next section, I will demonstrate how I analyzed user data in order to segment a bunch of user profiles into groups with the purpose of uncovering a user’s Implicit Communities.
Cluster analysis
Cluster Analysis is a machine learning technique used to group items in such a way that objects in the same cluster are similar to each other and dissimilar to objects in other clusters. Here are some of the key takeaways from the script.
I used the K-means algorithm to achieve this purpose.
Each user profile is represented as a vector. Based on user description, I used the TF-IDF approach to measure the weight/ importance of a word in a given context
We can limit the number of features being extracted by the TfidfVectorizer (by explicitly specifying max_features or specifying range of min_df and max_df). The idea of excluding features based on document frequency is to avoid features that are not representative. Limiting them can also be used to speed up the computation.
An ngram is a contiguous sequence of n items and in this context, it refers to text which is tokenized into a sequence of words. The benefit of using ngrams is its ability of capturing phrases.
Heres how I performed the cluster analysis based on user bios.
from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.cluster import KMeansdef get_parser(): parser = ArgumentParser("Clustering for followers") parser.add_argument('--filename') parser.add_argument('--k', type=int) parser.add_argument('--min-df', type=int, default=2) parser.add_argument('--max-df', type=float, default=0.8) parser.add_argument('--max-features', type=int, default=None) parser.add_argument('--no-idf', dest='user_idf', default=True, action='store_false') parser.add_argument('--min-ngram', type=int, default=1) parser.add_argument('--max-ngram', type=int, default=1) return parserif __name__ == '__main__': parser = get_parser() args = parser.parse_args() if args.min_ngram > args.max_ngram: print("Error: incorrect value for --min--ngram ({}): it cant be higher than \ --max--value ({})".format(args.min_ngram, args.max_ngram)) sys.exit(1) with open(args.filename) as f: #load datausers = [] for line in f: profile = json.loads(line) users.append(profile['description']) #create vectorizer vectorizer = TfidfVectorizer(max_df=args.max_df, min_df=args.min_df, max_features=args.max_features, stop_words='english', ngram_range=(args.min_ngram, args.max_ngram), use_idf=args.user_idf)#fit data X = vectorizer.fit_transform(users) print("Data dimensions: {}".format(X.shape))#perform clustering km = KMeans(n_clusters=args.k) km.fit(X) clusters = defaultdict(list) for i, label in enumerate(km.labels_): clusters[label].append(users[i])#print 10 user description of this clusterfor label, description in clusters.items(): print("--------- Cluster {}".format(label+i)) for desc in description[:10]: print(desc)
So you can tell that the script performed fairly well in segmenting users based on the bio they have on their profiles. I used my twitter profile for this example and you can tell that I have a couple of investors, tech enthusiasts, entrepreneurs and religious people in my community. This reminds me of a popular saying — “Show me your friends and I will tell you who you are”. The script could as well be used to delve deeper into other users’ profiles in order to uncover implicit communities they belong to.
Graph Mining and Analyzing Conversations
When many users are engaging in conversation, a “reply to” network emerges. The image below represents a conversation model on twitter with tweets as nodes, and edges as “reply to” relationship.
Naturally, this kind of structure can easily be mapped onto a Graph data structure. Some key takeaways from this model:
One-to-Many cardinality
No cycles
For these reasons I modelled a Directed Acyclic Graph and used properties of this graph and algorithms from graph theory to mine conversations. Here is the code snippet of the graph mining technique I used.
import sysimport jsonfrom operator import itemgetterimport networkx as nxdef usage(): print("Usage") print("python {} <filename>".format(sys.argv[0]))if __name__ == "__main__": if len(sys.argv) != 2: usage() sys.exit(1)fname = sys.argv[1] with open(fname) as f: #takes in a jsonl file of tweets as input graph = nx.DiGraph() for line in f: tweet = json.loads(line) if 'id' in tweet: graph.add_node(tweet['id'], tweet=tweet['text'], author=tweet['user']['screen_name'], created_at=tweet['created_at']) if tweet['in_reply_to_status_id']: reply_to = tweet['in_reply_to_status_id'] if reply_to in graph and tweet['user']['screen_name'] != graph.node[reply_to]['author']: #if the user is not replying to themselves graph.add_edge(tweet['in_reply_to_status_id'], tweet['id']) #Print some basic statsprint(nx.info(graph))#Find most replied tweet sorted_replied = sorted(graph.degree(), key=itemgetter(1), reverse=True)most_replied_id, replies = sorted_replied[0] print("Most replied tweet ({} replies:".format(replies)) print(graph.node[most_replied_id])#Find longest conversation (longest path) print("Longest discussion:") longest_path = nx.dag_longest_path(graph) for tweet_id in longest_path: node = graph.node[tweet_id] print("{} (by {} at {})".format(node['tweet'], node['author'], node['created_at']))
In-degree of a node: number of replies of a given tweet
Root: the start of a conversation
Leaf: the end of a conversation
Longest Path Algorithm: Used to find the tweet with the longest conversation.
I used networkX library because it provides efficient computation of graph structures
Dynamic Maps
Finally, to conclude my analysis, I created a visual representation of where these tweets are coming from by plotting them on a map.
Extraction of geographical data
Using GeoJSON library I extracted geometric data for each tweet from a stream file. I created an output file with a geo.json extension of this geographical data
#read dataset of tweets in jsonl file and produce a geoson file associted with geographical dataimport jsonfrom argparse import ArgumentParserdef get_parser(): parser = ArgumentParser() parser.add_argument('--tweets') parser.add_argument('--geojson') return parserif __name__ == "__main__": parser = get_parser() args = parser.parse_args()#Read tweet collection and build geo data structure. with open(args.tweets, 'r') as f: #read dataset of tweets geo_data = { 'type' : "FeatureCollection", 'features' : [] }for line in f: tweet = json.loads(line) try: if tweet['coordinates']: geo_json_feature = { "type" : "Feature", "geometry": { "type" : "Point", "coordinates" : tweet['coordinates']['coordinates'] }, "properties": { "text" : tweet['text'], "created_at" : tweet['created_at'] } } geo_data['features'].append(geo_json_feature) except KeyError: #Skip if json doc is not a tweet (errors, etc) continue #Save geo data with open(args.geojson, 'w') as fout: fout.write(json.dumps(geo_data, indent=4))
Creating Dynamic Maps
I used the Folium library to generate an interactive map. The advantage is that Folium handles the conversion between python data structures and Javascript, HTML and CSS components seamlessly.
from argparse import ArgumentParserimport foliumfrom folium.plugins import MarkerClusterimport jsondef get_parser(): parser = ArgumentParser() parser.add_argument('--geojson') parser.add_argument('--map') return parserdef make_map(geojson_file, map_file):tweet_map = folium.Map(Location=[50, 5], max_zoom=20)marker_cluster = MarkerCluster().add_to(tweet_map)geodata= json.load(open(geojson_file))for tweet in geodata['features']: tweet['geometry']['coordinates'].reverse() marker = folium.Marker(tweet['geometry']['coordinates'], popup=tweet['properties']['text']) marker.add_to(marker_cluster)#Save to HTML map file tweet_map.save(map_file)if __name__ == '__main__': parser = get_parser() args = parser.parse_args() make_map(args.geojson, args.map)
As you can see, this script visualizes the different locations from which people were tweeting about the death of NBA legend Kobe Bryant when it happened. The script clusters users tweeting from a particular area and precisely locates the exact point where each tweet was posted.
These results are generated from a 15-minute stream of the storm of tweets a few hours after the event was publicized. You may view and interact with the full map here
This was all for Mining Twitter Data. I really enjoyed working on this project. I have full source code available on my GitHub for anyone interested in implementing this project. | [
{
"code": null,
"e": 442,
"s": 172,
"text": "Twitter is a microblogging and social networking service where users post content and interact with posts known as “tweets”. Today, Twitter has popularized the use of hashtags as a way to group conversations and allow users to follow conversations on particular topics."
},
{
"code": null,
"e": 674,
"s": 442,
"text": "With over 500 million tweets per day, you can imagine how rich with information this platform is. The objective of this project is to gather and analyze twitter data in order to discover interesting information and hidden patterns."
},
{
"code": null,
"e": 922,
"s": 674,
"text": "This post serves as a “technical reflection” of my experience completing this task. I will be showing and briefly explaining relevant code snippets as well as results of my analysis. Here’s an overview of key steps I think are worth talking about."
},
{
"code": null,
"e": 1015,
"s": 922,
"text": "AuthenticationData CollectionData Cleaning and PreprocessingModelling and AnalysisConclusion"
},
{
"code": null,
"e": 1030,
"s": 1015,
"text": "Authentication"
},
{
"code": null,
"e": 1046,
"s": 1030,
"text": "Data Collection"
},
{
"code": null,
"e": 1078,
"s": 1046,
"text": "Data Cleaning and Preprocessing"
},
{
"code": null,
"e": 1101,
"s": 1078,
"text": "Modelling and Analysis"
},
{
"code": null,
"e": 1112,
"s": 1101,
"text": "Conclusion"
},
{
"code": null,
"e": 1482,
"s": 1112,
"text": "In this application the authentication step was performed using the industry standard OAuth process which involves the user, consumer (the app) and the resource provider (Twitter). The key takeaway from this is that the exchange of credentials like username and password only happens between the user and the resource provider. All other exchanges are driven by tokens."
},
{
"code": null,
"e": 1698,
"s": 1482,
"text": "Creating a Twitter Developer Account. You need a developer account to have access to the twitter API. Once you create an application you may generate the Consumer Key, Consumer Secret, Access token and Access secret"
},
{
"code": null,
"e": 1885,
"s": 1698,
"text": "I chose tweepy as my Twitter API client and I chose to create environment variables for my tokens as it promotes security and is language agnostic. Here is how I setup my twitter client."
},
{
"code": null,
"e": 2666,
"s": 1885,
"text": "import osimport sysfrom tweepy import APIfrom tweepy import OAuthHandlerdef get_twitter_auth(): #set up twitter authentication# Return: tweepy.OAuthHandler objecttry: consumer_key = os.environ['TWITTER_CONSUMER_KEY'] consumer_secret = os.environ['TWITTER_CONSUMER_SECRET'] access_token = os.environ['TWITTER_ACCESS_TOKEN'] access_secret= os.environ['TWITTER_ACCESS_SECRET'] except KeyError: sys.stderr.write(\"TWITTER_* environment variables not set\\n\") sys.exit(1) auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) return authdef get_twitter_client(): #Setup twitter API client.# Return tweepy.API objectauth = get_twitter_auth() client = API(auth) return client"
},
{
"code": null,
"e": 2768,
"s": 2666,
"text": "After the preliminary set ups. I could immediately start gathering data and interacting with the API."
},
{
"code": null,
"e": 2804,
"s": 2768,
"text": "Interacting with twitter’s REST API"
},
{
"code": null,
"e": 2915,
"s": 2804,
"text": "All REST endpoints allow you to “go back in time”, meaning we are able to search for already published tweets."
},
{
"code": null,
"e": 2956,
"s": 2915,
"text": "Interacting with twitter’s Streaming API"
},
{
"code": null,
"e": 3193,
"s": 2956,
"text": "The Streaming API looks into the future. Once you open a connection, you may leave it open and go forward in time. By keeping the HTTP connection open, we can retrieve all the tweets that match our filter criteria as they are published."
},
{
"code": null,
"e": 3269,
"s": 3193,
"text": "This is generally the preferred way of downloading a huge number of tweets."
},
{
"code": null,
"e": 3480,
"s": 3269,
"text": "In my case, I wanted to investigate realtime conversations among users during the US-Iran tension in December 2019 so I decided to stream all tweets with trending hashtags such as #USIran #USvsIran #Iranattacks"
},
{
"code": null,
"e": 3532,
"s": 3480,
"text": "Here is how I implemented a custom stream listener."
},
{
"code": null,
"e": 4512,
"s": 3532,
"text": "class CustomListener(StreamListener): \"\"\" Custom StreamListener for streaming twitter data.\"\"\"def __init__(self, fname): safe_fname = format_filename(fname) self.outfile = \"stream_%s.jsonl\" % safe_fnamedef on_data(self, data): #called when data is coming through. This method simply stores data as it is received in a .jsonl file. Each line in this file will contain a single tweet in json format try: with open(self.outfile, 'a') as f: f.write(data) return True except BaseException as e: sys.stderr.write(\"Error on_data: {}\\n\".format(e)) time.sleep(5) return True ...if __name__ == '__main__': query = sys.argv[1:] # list of CLI argumentsquery_fname query_fname = ' '.join(query) # string auth = get_twitter_auth() twitter_stream = Stream(auth, CustomListener(query_fname)) twitter_stream.filter(track=query, is_async=True)"
},
{
"code": null,
"e": 4768,
"s": 4512,
"text": "So, after streaming for about an hour, I managed to gather 13, 908 tweets from users who were talking about the US-Iran tension. I stored these tweets in a .jsonl file and it was time to pre-process the text. Here are some preprocessing tasks I performed:"
},
{
"code": null,
"e": 4800,
"s": 4768,
"text": "Tokenization using nltk library"
},
{
"code": null,
"e": 5126,
"s": 4800,
"text": "Tokenization refers to breaking down a stream of texts into tokens such as words, phrases, symbols. The content of a tweet includes emojis, user mentions, hasthags, urls etc. For this reason, when using the nltk library, I will showcase the use of the TweetTokenizer class as a tool to appropriately tokenize twitter content."
},
{
"code": null,
"e": 5144,
"s": 5126,
"text": "Stop word removal"
},
{
"code": null,
"e": 5380,
"s": 5144,
"text": "Stop words are not content bearing and so we need to remove them. This category of words include articles, adverbs, symbols, punctuation, etc. Frequency analysis shows that these strings are the most frequently occurring in a document."
},
{
"code": null,
"e": 5394,
"s": 5380,
"text": "Normalization"
},
{
"code": null,
"e": 5628,
"s": 5394,
"text": "Normalization is used to aggregate different terms in the same unit. Performing case normalization will help in automatically matching these strings with originally different casing so that they can be aggregated under the same term."
},
{
"code": null,
"e": 6886,
"s": 5628,
"text": "import sysimport stringimport jsonfrom collections import Counterfrom nltk.tokenize import TweetTokenizerfrom nltk.corpus import stopwordsimport matplotlib.pyplot as pltdef process(text, tokenizer=TweetTokenizer(), stopwords=[]): \"\"\" Process tweet text: - Lowercase - tokenize - stopword removal - digits removal Return: list of strings \"\"\"text = text.lower() tokens = tokenizer.tokenize(text) return [tok for tok in tokens if tok not in stopwords and not tok.isdigit()]if __name__ == '__main__': fname = sys.argv[1] tweet_tokenizer = TweetTokenizer() punct = list(string.punctuation) stopword_list = stopwords.words('english') + punct + ['rt', 'via', '...']tf = Counter() with open(fname, 'r') as f: for line in f: tweet = json.loads(line) tokens = process(text=tweet['text'], tokenizer=tweet_tokenizer, stopwords=stopword_list) tf.update(tokens) for tag, count in tf.most_common(20):print(\"{}: {}\".format(tag, count))#plot resultsy = [count for tag, count in tf.most_common(20)] x = range(1, len(y)+1)plt.bar(x, y) plt.title(\"Term frequencies used in US-Iran Stream Data\") plt.ylabel(\"Frequency\") plt.savefig('us-iran-term-distn.png')"
},
{
"code": null,
"e": 7050,
"s": 6886,
"text": "In the above snippet, I began the analysis by creating a visual representation of the term distribution of the 20 most common terms used in the tweets I collected."
},
{
"code": null,
"e": 7181,
"s": 7050,
"text": "Continuing the analysis, I searched the dataset for the key people everybody was talking about by finding their mention frequency."
},
{
"code": null,
"e": 7412,
"s": 7181,
"text": "With this information, I knew exactly which profiles I could start investigating to receive a more related feed. It was shocking, however, to discover that realdonaldtrump ranked 8th in popular user mentions related to this issue."
},
{
"code": null,
"e": 7433,
"s": 7412,
"text": "Time Series Analysis"
},
{
"code": null,
"e": 7543,
"s": 7433,
"text": "A time series is a sequence of data points that consists of successive observation over a given time interval"
},
{
"code": null,
"e": 7667,
"s": 7543,
"text": "It can be used to reorder tweets and track how users react to realtime events (such as — Sports, political elections, news)"
},
{
"code": null,
"e": 7974,
"s": 7667,
"text": "In this application, I performed a time series analysis to monitor how users were tweeting as more news about this topic was being released. It seems to me as though within the hour I was streaming, users were actively tweeting about the topic throughout, with a peak of 200 tweets collected around 10:45AM"
},
{
"code": null,
"e": 8003,
"s": 7974,
"text": "Users, Followers and Friends"
},
{
"code": null,
"e": 8178,
"s": 8003,
"text": "I decided to explore some of the top users’ profiles, list of followers and “following” (or friends) for further analysis. Here is how I pulled this information from twitter."
},
{
"code": null,
"e": 9563,
"s": 8178,
"text": "#get followers for a given userfname = \"Twitter_Profiles/{}/followers.jsonl\".format(screen_name) with open(fname, 'w') as f: for followers in Cursor(client.followers_ids, screen_name=screen_name).pages(max_pages): for chunk in paginate(followers, 100): users = client.lookup_users(user_ids=chunk) for user in users: f.write(json.dumps(user._json)+\"\\n\") if len(followers) == 5000: print(\"More results available. Sleeping for 60 seconds to avoid rate limit\") time.sleep(60)#get friends for a given userfname = \"Twitter_Profiles/{}/friends.jsonl\".format(screen_name) with open(fname, 'w') as f: for friends in Cursor(client.friends_ids, screen_name=screen_name).pages(max_pages): for chunk in paginate(friends, 100): users = client.lookup_users(user_ids=chunk) for user in users: f.write(json.dumps(user._json)+\"\\n\") if len(friends) == 5000: print(\"More results available. Sleeping for 60 seconds to avoid rate limit\") time.sleep(60)# get user's profile fname = \"Twitter_Profiles/{}/user_profile.json\".format(screen_name) with open(fname, 'w') as f: profile = client.get_user(screen_name=screen_name) f.write(json.dumps(profile._json, indent=4))"
},
{
"code": null,
"e": 9598,
"s": 9563,
"text": "Measuring Influence and Engagement"
},
{
"code": null,
"e": 9847,
"s": 9598,
"text": "A metric of engagement provides an assessment of users’ responses to tweets and other content, often created with the purpose to drive traffic. On twitter, users engage by means of liking or retweeting — which provides more visibility to the tweets"
},
{
"code": null,
"e": 9976,
"s": 9847,
"text": "Understanding the influence of a user involves analyzing the user’s reach in combination with their tweet engagement statistics."
},
{
"code": null,
"e": 11990,
"s": 9976,
"text": "#Build up a list of followers followers_file1 = 'Twitter_Profiles/{}/followers.jsonl'.format(screen_name1) followers_file2 = 'Twitter_Profiles/{}/followers.jsonl'.format(screen_name2)with open(followers_file1) as f1, open(followers_file2) as f2: reach1 = [] reach2 = [] for line in f1: profile = json.loads(line) reach1.append((profile['screen_name'], profile['followers_count'])) for line in f2: profile = json.loads(line) reach2.append((profile['screen_name'], profile['followers_count']))#Load basic statistics profile_file1 = 'Twitter_Profiles/{}/user_profile.json'.format(screen_name1) profile_file2 = 'Twitter_Profiles/{}/user_profile.json'.format(screen_name2) with open(profile_file1) as f1, open(profile_file2) as f2: profile1 = json.load(f1) profile2 = json.load(f2)followers1 = profile1['followers_count'] followers2 = profile2['followers_count']tweets1 = profile['statuses_count'] tweets2 = profile['statuses_count']sum_reach1 = sum([x[1] for x in reach1]) #sum up all of a user's followers, followers sum_reach2 = sum([x[1] for x in reach2]) avg_followers1 = round(sum_reach1/ followers1, 2) avg_followers2 = round(sum_reach2/ followers2, 2)#Load the timelines for two users to observe the number of times their tweets have been favorited timeline_file1 = 'user_timeline_{}.jsonl'.format(screen_name1) timeline_file2 = 'user_timeline_{}.jsonl'.format(screen_name2) with open(timeline_file1) as f1, open(timeline_file2) as f2: favorited_count1, retweet_count1 = [], [] favorited_count2, retweet_count2 = [], [] for line in f1: tweet = json.loads(line) favorited_count1.append(tweet['favorite_count']) retweet_count1.append(tweet['retweet_count'])for line in f2: tweet = json.loads(line) favorited_count2.append(tweet['favorite_count']) retweet_count2.append(tweet['retweet_count'])"
},
{
"code": null,
"e": 12048,
"s": 11990,
"text": "Complete scripts for doing this can be found on my GitHub"
},
{
"code": null,
"e": 12074,
"s": 12048,
"text": "Mining Social Communities"
},
{
"code": null,
"e": 12230,
"s": 12074,
"text": "A social community is a group of people who share some common conditions e.g geographical area, same religious beliefs, or people who share same interests."
},
{
"code": null,
"e": 12420,
"s": 12230,
"text": "Explicit community — people with common interests and explicitly know exactly whether they belong to a community or not and typically understand who other members in the said community are."
},
{
"code": null,
"e": 12562,
"s": 12420,
"text": "Implicit communities — come into existence when members share common interests without having clear and strong connections between each other"
},
{
"code": null,
"e": 12746,
"s": 12562,
"text": "In the next section, I will demonstrate how I analyzed user data in order to segment a bunch of user profiles into groups with the purpose of uncovering a user’s Implicit Communities."
},
{
"code": null,
"e": 12763,
"s": 12746,
"text": "Cluster analysis"
},
{
"code": null,
"e": 13002,
"s": 12763,
"text": "Cluster Analysis is a machine learning technique used to group items in such a way that objects in the same cluster are similar to each other and dissimilar to objects in other clusters. Here are some of the key takeaways from the script."
},
{
"code": null,
"e": 13056,
"s": 13002,
"text": "I used the K-means algorithm to achieve this purpose."
},
{
"code": null,
"e": 13219,
"s": 13056,
"text": "Each user profile is represented as a vector. Based on user description, I used the TF-IDF approach to measure the weight/ importance of a word in a given context"
},
{
"code": null,
"e": 13545,
"s": 13219,
"text": "We can limit the number of features being extracted by the TfidfVectorizer (by explicitly specifying max_features or specifying range of min_df and max_df). The idea of excluding features based on document frequency is to avoid features that are not representative. Limiting them can also be used to speed up the computation."
},
{
"code": null,
"e": 13739,
"s": 13545,
"text": "An ngram is a contiguous sequence of n items and in this context, it refers to text which is tokenized into a sequence of words. The benefit of using ngrams is its ability of capturing phrases."
},
{
"code": null,
"e": 13802,
"s": 13739,
"text": "Heres how I performed the cluster analysis based on user bios."
},
{
"code": null,
"e": 15831,
"s": 13802,
"text": "from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.cluster import KMeansdef get_parser(): parser = ArgumentParser(\"Clustering for followers\") parser.add_argument('--filename') parser.add_argument('--k', type=int) parser.add_argument('--min-df', type=int, default=2) parser.add_argument('--max-df', type=float, default=0.8) parser.add_argument('--max-features', type=int, default=None) parser.add_argument('--no-idf', dest='user_idf', default=True, action='store_false') parser.add_argument('--min-ngram', type=int, default=1) parser.add_argument('--max-ngram', type=int, default=1) return parserif __name__ == '__main__': parser = get_parser() args = parser.parse_args() if args.min_ngram > args.max_ngram: print(\"Error: incorrect value for --min--ngram ({}): it cant be higher than \\ --max--value ({})\".format(args.min_ngram, args.max_ngram)) sys.exit(1) with open(args.filename) as f: #load datausers = [] for line in f: profile = json.loads(line) users.append(profile['description']) #create vectorizer vectorizer = TfidfVectorizer(max_df=args.max_df, min_df=args.min_df, max_features=args.max_features, stop_words='english', ngram_range=(args.min_ngram, args.max_ngram), use_idf=args.user_idf)#fit data X = vectorizer.fit_transform(users) print(\"Data dimensions: {}\".format(X.shape))#perform clustering km = KMeans(n_clusters=args.k) km.fit(X) clusters = defaultdict(list) for i, label in enumerate(km.labels_): clusters[label].append(users[i])#print 10 user description of this clusterfor label, description in clusters.items(): print(\"--------- Cluster {}\".format(label+i)) for desc in description[:10]: print(desc)"
},
{
"code": null,
"e": 16343,
"s": 15831,
"text": "So you can tell that the script performed fairly well in segmenting users based on the bio they have on their profiles. I used my twitter profile for this example and you can tell that I have a couple of investors, tech enthusiasts, entrepreneurs and religious people in my community. This reminds me of a popular saying — “Show me your friends and I will tell you who you are”. The script could as well be used to delve deeper into other users’ profiles in order to uncover implicit communities they belong to."
},
{
"code": null,
"e": 16384,
"s": 16343,
"text": "Graph Mining and Analyzing Conversations"
},
{
"code": null,
"e": 16579,
"s": 16384,
"text": "When many users are engaging in conversation, a “reply to” network emerges. The image below represents a conversation model on twitter with tweets as nodes, and edges as “reply to” relationship."
},
{
"code": null,
"e": 16699,
"s": 16579,
"text": "Naturally, this kind of structure can easily be mapped onto a Graph data structure. Some key takeaways from this model:"
},
{
"code": null,
"e": 16723,
"s": 16699,
"text": "One-to-Many cardinality"
},
{
"code": null,
"e": 16733,
"s": 16723,
"text": "No cycles"
},
{
"code": null,
"e": 16940,
"s": 16733,
"text": "For these reasons I modelled a Directed Acyclic Graph and used properties of this graph and algorithms from graph theory to mine conversations. Here is the code snippet of the graph mining technique I used."
},
{
"code": null,
"e": 18561,
"s": 16940,
"text": "import sysimport jsonfrom operator import itemgetterimport networkx as nxdef usage(): print(\"Usage\") print(\"python {} <filename>\".format(sys.argv[0]))if __name__ == \"__main__\": if len(sys.argv) != 2: usage() sys.exit(1)fname = sys.argv[1] with open(fname) as f: #takes in a jsonl file of tweets as input graph = nx.DiGraph() for line in f: tweet = json.loads(line) if 'id' in tweet: graph.add_node(tweet['id'], tweet=tweet['text'], author=tweet['user']['screen_name'], created_at=tweet['created_at']) if tweet['in_reply_to_status_id']: reply_to = tweet['in_reply_to_status_id'] if reply_to in graph and tweet['user']['screen_name'] != graph.node[reply_to]['author']: #if the user is not replying to themselves graph.add_edge(tweet['in_reply_to_status_id'], tweet['id']) #Print some basic statsprint(nx.info(graph))#Find most replied tweet sorted_replied = sorted(graph.degree(), key=itemgetter(1), reverse=True)most_replied_id, replies = sorted_replied[0] print(\"Most replied tweet ({} replies:\".format(replies)) print(graph.node[most_replied_id])#Find longest conversation (longest path) print(\"Longest discussion:\") longest_path = nx.dag_longest_path(graph) for tweet_id in longest_path: node = graph.node[tweet_id] print(\"{} (by {} at {})\".format(node['tweet'], node['author'], node['created_at']))"
},
{
"code": null,
"e": 18617,
"s": 18561,
"text": "In-degree of a node: number of replies of a given tweet"
},
{
"code": null,
"e": 18651,
"s": 18617,
"text": "Root: the start of a conversation"
},
{
"code": null,
"e": 18683,
"s": 18651,
"text": "Leaf: the end of a conversation"
},
{
"code": null,
"e": 18761,
"s": 18683,
"text": "Longest Path Algorithm: Used to find the tweet with the longest conversation."
},
{
"code": null,
"e": 18847,
"s": 18761,
"text": "I used networkX library because it provides efficient computation of graph structures"
},
{
"code": null,
"e": 18860,
"s": 18847,
"text": "Dynamic Maps"
},
{
"code": null,
"e": 18993,
"s": 18860,
"text": "Finally, to conclude my analysis, I created a visual representation of where these tweets are coming from by plotting them on a map."
},
{
"code": null,
"e": 19025,
"s": 18993,
"text": "Extraction of geographical data"
},
{
"code": null,
"e": 19186,
"s": 19025,
"text": "Using GeoJSON library I extracted geometric data for each tweet from a stream file. I created an output file with a geo.json extension of this geographical data"
},
{
"code": null,
"e": 20592,
"s": 19186,
"text": "#read dataset of tweets in jsonl file and produce a geoson file associted with geographical dataimport jsonfrom argparse import ArgumentParserdef get_parser(): parser = ArgumentParser() parser.add_argument('--tweets') parser.add_argument('--geojson') return parserif __name__ == \"__main__\": parser = get_parser() args = parser.parse_args()#Read tweet collection and build geo data structure. with open(args.tweets, 'r') as f: #read dataset of tweets geo_data = { 'type' : \"FeatureCollection\", 'features' : [] }for line in f: tweet = json.loads(line) try: if tweet['coordinates']: geo_json_feature = { \"type\" : \"Feature\", \"geometry\": { \"type\" : \"Point\", \"coordinates\" : tweet['coordinates']['coordinates'] }, \"properties\": { \"text\" : tweet['text'], \"created_at\" : tweet['created_at'] } } geo_data['features'].append(geo_json_feature) except KeyError: #Skip if json doc is not a tweet (errors, etc) continue #Save geo data with open(args.geojson, 'w') as fout: fout.write(json.dumps(geo_data, indent=4))"
},
{
"code": null,
"e": 20614,
"s": 20592,
"text": "Creating Dynamic Maps"
},
{
"code": null,
"e": 20807,
"s": 20614,
"text": "I used the Folium library to generate an interactive map. The advantage is that Folium handles the conversion between python data structures and Javascript, HTML and CSS components seamlessly."
},
{
"code": null,
"e": 21602,
"s": 20807,
"text": "from argparse import ArgumentParserimport foliumfrom folium.plugins import MarkerClusterimport jsondef get_parser(): parser = ArgumentParser() parser.add_argument('--geojson') parser.add_argument('--map') return parserdef make_map(geojson_file, map_file):tweet_map = folium.Map(Location=[50, 5], max_zoom=20)marker_cluster = MarkerCluster().add_to(tweet_map)geodata= json.load(open(geojson_file))for tweet in geodata['features']: tweet['geometry']['coordinates'].reverse() marker = folium.Marker(tweet['geometry']['coordinates'], popup=tweet['properties']['text']) marker.add_to(marker_cluster)#Save to HTML map file tweet_map.save(map_file)if __name__ == '__main__': parser = get_parser() args = parser.parse_args() make_map(args.geojson, args.map)"
},
{
"code": null,
"e": 21882,
"s": 21602,
"text": "As you can see, this script visualizes the different locations from which people were tweeting about the death of NBA legend Kobe Bryant when it happened. The script clusters users tweeting from a particular area and precisely locates the exact point where each tweet was posted."
},
{
"code": null,
"e": 22050,
"s": 21882,
"text": "These results are generated from a 15-minute stream of the storm of tweets a few hours after the event was publicized. You may view and interact with the full map here"
}
]
|
Machine Learning with Python - Extra Trees | It is another extension of bagged decision tree ensemble method. In this method, the random trees are constructed from the samples of the training dataset.
In the following Python recipe, we are going to build extra tree ensemble model by using ExtraTreesClassifier class of sklearn on Pima Indians diabetes dataset.
First, import the required packages as follows −
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import ExtraTreesClassifier
Now, we need to load the Pima diabetes dataset as did in previous examples −
path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names = headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]
Next, give the input for 10-fold cross validation as follows −
seed = 7
kfold = KFold(n_splits = 10, random_state = seed)
We need to provide the number of trees we are going to build. Here we are building 150 trees with split points chosen from 5 features −
num_trees = 150
max_features = 5
Next, build the model with the help of following script −
model = ExtraTreesClassifier(n_estimators = num_trees, max_features = max_features)
Calculate and print the result as follows −
results = cross_val_score(model, X, Y, cv = kfold)
print(results.mean())
Output
0.7551435406698566
The output above shows that we got around 75.5% accuracy of our bagged extra trees classifier model.
168 Lectures
13.5 hours
Er. Himanshu Vasishta
64 Lectures
10.5 hours
Eduonix Learning Solutions
91 Lectures
10 hours
Abhilash Nelson
54 Lectures
6 hours
Abhishek And Pukhraj
49 Lectures
5 hours
Abhishek And Pukhraj
35 Lectures
4 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2460,
"s": 2304,
"text": "It is another extension of bagged decision tree ensemble method. In this method, the random trees are constructed from the samples of the training dataset."
},
{
"code": null,
"e": 2621,
"s": 2460,
"text": "In the following Python recipe, we are going to build extra tree ensemble model by using ExtraTreesClassifier class of sklearn on Pima Indians diabetes dataset."
},
{
"code": null,
"e": 2670,
"s": 2621,
"text": "First, import the required packages as follows −"
},
{
"code": null,
"e": 2842,
"s": 2670,
"text": "from pandas import read_csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import ExtraTreesClassifier"
},
{
"code": null,
"e": 2919,
"s": 2842,
"text": "Now, we need to load the Pima diabetes dataset as did in previous examples −"
},
{
"code": null,
"e": 3140,
"s": 2919,
"text": "path = r\"C:\\pima-indians-diabetes.csv\"\nheadernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names = headernames)\narray = data.values\nX = array[:,0:8]\nY = array[:,8]"
},
{
"code": null,
"e": 3203,
"s": 3140,
"text": "Next, give the input for 10-fold cross validation as follows −"
},
{
"code": null,
"e": 3263,
"s": 3203,
"text": "seed = 7\nkfold = KFold(n_splits = 10, random_state = seed)\n"
},
{
"code": null,
"e": 3399,
"s": 3263,
"text": "We need to provide the number of trees we are going to build. Here we are building 150 trees with split points chosen from 5 features −"
},
{
"code": null,
"e": 3433,
"s": 3399,
"text": "num_trees = 150\nmax_features = 5\n"
},
{
"code": null,
"e": 3491,
"s": 3433,
"text": "Next, build the model with the help of following script −"
},
{
"code": null,
"e": 3576,
"s": 3491,
"text": "model = ExtraTreesClassifier(n_estimators = num_trees, max_features = max_features)\n"
},
{
"code": null,
"e": 3620,
"s": 3576,
"text": "Calculate and print the result as follows −"
},
{
"code": null,
"e": 3694,
"s": 3620,
"text": "results = cross_val_score(model, X, Y, cv = kfold)\nprint(results.mean())\n"
},
{
"code": null,
"e": 3701,
"s": 3694,
"text": "Output"
},
{
"code": null,
"e": 3721,
"s": 3701,
"text": "0.7551435406698566\n"
},
{
"code": null,
"e": 3822,
"s": 3721,
"text": "The output above shows that we got around 75.5% accuracy of our bagged extra trees classifier model."
},
{
"code": null,
"e": 3859,
"s": 3822,
"text": "\n 168 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 3882,
"s": 3859,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 3918,
"s": 3882,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3946,
"s": 3918,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3980,
"s": 3946,
"text": "\n 91 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3997,
"s": 3980,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4030,
"s": 3997,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4052,
"s": 4030,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4085,
"s": 4052,
"text": "\n 49 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4107,
"s": 4085,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4140,
"s": 4107,
"text": "\n 35 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4162,
"s": 4140,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4169,
"s": 4162,
"text": " Print"
},
{
"code": null,
"e": 4180,
"s": 4169,
"text": " Add Notes"
}
]
|
Machine Learning Model Dashboard. Creating dashboards to interpret... | by Himanshu Sharma | Towards Data Science | Nowadays, creating a machine learning model is easy because of different python libraries that are in the market like sklearn, lazypredict, etc. These libraries are easy to use and used to create different types of models along with different types of visualizations and finding out the model performance. If you don’t know how lazy predict works, check out the article given below.
towardsdatascience.com
The main challenge nowadays is that models are not interpreted easily which makes it difficult for a non-technical person to understand and interpret the logic and how the model is working.
Explainer dashboard is an open-source python library that creates machine learning model dashboards that can be used to easily understand and analyze the important factors on which the model is working like feature importance, model performance, visualizations, etc.
In this article, we will use an explainer dashboard to create machine learning dashboards and understand how the model is working.
Let’s get started...
We will start by installing an explainer dashboard using pip. The command given below will do that.
pip install explainerdashboard
In this step, we will import the required libraries and functions to create a machine learning model and dashboard.
from sklearn.ensemble import RandomForestClassifierfrom explainerdashboard import ClassifierExplainer, ExplainerDashboardfrom explainerdashboard.datasets import titanic_survive, titanic_names
This is the final step in which we will create the machine learning model and then interpret that model by creating a dashboard.
Creating Model
Creating Model
feature_descriptions = { "Sex": "Gender of passenger", "Gender": "Gender of passenger", "Deck": "The deck the passenger had their cabin on", "PassengerClass": "The class of the ticket: 1st, 2nd or 3rd class", "Fare": "The amount of money people paid", "Embarked": "the port where the passenger boarded the Titanic. Either Southampton, Cherbourg or Queenstown", "Age": "Age of the passenger", "No_of_siblings_plus_spouses_on_board": "The sum of the number of siblings plus the number of spouses on board", "No_of_parents_plus_children_on_board" : "The sum of the number of parents plus the number of children on board",}X_train, y_train, X_test, y_test = titanic_survive()train_names, test_names = titanic_names()model = RandomForestClassifier(n_estimators=50, max_depth=5)model.fit(X_train, y_train)
2. Creating Dashboard
from sklearn.ensemble import RandomForestClassifierfrom explainerdashboard import ClassifierExplainer, ExplainerDashboardfrom explainerdashboard.datasets import titanic_survive, titanic_namesfeature_descriptions = { "Sex": "Gender of passenger", "Gender": "Gender of passenger", "Deck": "The deck the passenger had their cabin on", "PassengerClass": "The class of the ticket: 1st, 2nd or 3rd class", "Fare": "The amount of money people paid", "Embarked": "the port where the passenger boarded the Titanic. Either Southampton, Cherbourg or Queenstown", "Age": "Age of the passenger", "No_of_siblings_plus_spouses_on_board": "The sum of the number of siblings plus the number of spouses on board", "No_of_parents_plus_children_on_board" : "The sum of the number of parents plus the number of children on board",}X_train, y_train, X_test, y_test = titanic_survive()train_names, test_names = titanic_names()model = RandomForestClassifier(n_estimators=50, max_depth=5)model.fit(X_train, y_train)explainer = ClassifierExplainer(model, X_test, y_test, cats=['Deck', 'Embarked', {'Gender': ['Sex_male', 'Sex_female', 'Sex_nan']}], cats_notencoded={'Embarked': 'Stowaway'}, descriptions=feature_descriptions, labels=['Not survived', 'Survived'], idxs = test_names, index_name = "Passenger", target = "Survival", )db = ExplainerDashboard(explainer, title="Titanic Explainer", shap_interaction=False, )db.run(port=8050)
In the video given below, I have shown the dashboard created using the explainer dashboards.
Here you can clearly visualize the dashboard create using the explainer dashboard. We can clearly analyze different properties of the model and other parameters.
Go ahead try this with different datasets and create beautiful dashboards to interpret the model. In case you find any difficulty please let me know in the response section.
This article is in collaboration with Piyush Ingale.
Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science. | [
{
"code": null,
"e": 555,
"s": 172,
"text": "Nowadays, creating a machine learning model is easy because of different python libraries that are in the market like sklearn, lazypredict, etc. These libraries are easy to use and used to create different types of models along with different types of visualizations and finding out the model performance. If you don’t know how lazy predict works, check out the article given below."
},
{
"code": null,
"e": 578,
"s": 555,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 768,
"s": 578,
"text": "The main challenge nowadays is that models are not interpreted easily which makes it difficult for a non-technical person to understand and interpret the logic and how the model is working."
},
{
"code": null,
"e": 1035,
"s": 768,
"text": "Explainer dashboard is an open-source python library that creates machine learning model dashboards that can be used to easily understand and analyze the important factors on which the model is working like feature importance, model performance, visualizations, etc."
},
{
"code": null,
"e": 1166,
"s": 1035,
"text": "In this article, we will use an explainer dashboard to create machine learning dashboards and understand how the model is working."
},
{
"code": null,
"e": 1187,
"s": 1166,
"text": "Let’s get started..."
},
{
"code": null,
"e": 1287,
"s": 1187,
"text": "We will start by installing an explainer dashboard using pip. The command given below will do that."
},
{
"code": null,
"e": 1318,
"s": 1287,
"text": "pip install explainerdashboard"
},
{
"code": null,
"e": 1434,
"s": 1318,
"text": "In this step, we will import the required libraries and functions to create a machine learning model and dashboard."
},
{
"code": null,
"e": 1626,
"s": 1434,
"text": "from sklearn.ensemble import RandomForestClassifierfrom explainerdashboard import ClassifierExplainer, ExplainerDashboardfrom explainerdashboard.datasets import titanic_survive, titanic_names"
},
{
"code": null,
"e": 1755,
"s": 1626,
"text": "This is the final step in which we will create the machine learning model and then interpret that model by creating a dashboard."
},
{
"code": null,
"e": 1770,
"s": 1755,
"text": "Creating Model"
},
{
"code": null,
"e": 1785,
"s": 1770,
"text": "Creating Model"
},
{
"code": null,
"e": 2613,
"s": 1785,
"text": "feature_descriptions = { \"Sex\": \"Gender of passenger\", \"Gender\": \"Gender of passenger\", \"Deck\": \"The deck the passenger had their cabin on\", \"PassengerClass\": \"The class of the ticket: 1st, 2nd or 3rd class\", \"Fare\": \"The amount of money people paid\", \"Embarked\": \"the port where the passenger boarded the Titanic. Either Southampton, Cherbourg or Queenstown\", \"Age\": \"Age of the passenger\", \"No_of_siblings_plus_spouses_on_board\": \"The sum of the number of siblings plus the number of spouses on board\", \"No_of_parents_plus_children_on_board\" : \"The sum of the number of parents plus the number of children on board\",}X_train, y_train, X_test, y_test = titanic_survive()train_names, test_names = titanic_names()model = RandomForestClassifier(n_estimators=50, max_depth=5)model.fit(X_train, y_train)"
},
{
"code": null,
"e": 2635,
"s": 2613,
"text": "2. Creating Dashboard"
},
{
"code": null,
"e": 4432,
"s": 2635,
"text": "from sklearn.ensemble import RandomForestClassifierfrom explainerdashboard import ClassifierExplainer, ExplainerDashboardfrom explainerdashboard.datasets import titanic_survive, titanic_namesfeature_descriptions = { \"Sex\": \"Gender of passenger\", \"Gender\": \"Gender of passenger\", \"Deck\": \"The deck the passenger had their cabin on\", \"PassengerClass\": \"The class of the ticket: 1st, 2nd or 3rd class\", \"Fare\": \"The amount of money people paid\", \"Embarked\": \"the port where the passenger boarded the Titanic. Either Southampton, Cherbourg or Queenstown\", \"Age\": \"Age of the passenger\", \"No_of_siblings_plus_spouses_on_board\": \"The sum of the number of siblings plus the number of spouses on board\", \"No_of_parents_plus_children_on_board\" : \"The sum of the number of parents plus the number of children on board\",}X_train, y_train, X_test, y_test = titanic_survive()train_names, test_names = titanic_names()model = RandomForestClassifier(n_estimators=50, max_depth=5)model.fit(X_train, y_train)explainer = ClassifierExplainer(model, X_test, y_test, cats=['Deck', 'Embarked', {'Gender': ['Sex_male', 'Sex_female', 'Sex_nan']}], cats_notencoded={'Embarked': 'Stowaway'}, descriptions=feature_descriptions, labels=['Not survived', 'Survived'], idxs = test_names, index_name = \"Passenger\", target = \"Survival\", )db = ExplainerDashboard(explainer, title=\"Titanic Explainer\", shap_interaction=False, )db.run(port=8050)"
},
{
"code": null,
"e": 4525,
"s": 4432,
"text": "In the video given below, I have shown the dashboard created using the explainer dashboards."
},
{
"code": null,
"e": 4687,
"s": 4525,
"text": "Here you can clearly visualize the dashboard create using the explainer dashboard. We can clearly analyze different properties of the model and other parameters."
},
{
"code": null,
"e": 4861,
"s": 4687,
"text": "Go ahead try this with different datasets and create beautiful dashboards to interpret the model. In case you find any difficulty please let me know in the response section."
},
{
"code": null,
"e": 4914,
"s": 4861,
"text": "This article is in collaboration with Piyush Ingale."
}
]
|
How can we remove NOT NULL constraint from a column of an existing MySQL table? | We can remove a NOT NULL constraint from a column of an existing table by using the ALTER TABLE statement.
Suppose we have a table ‘test123’ having a NOT NULL constraint on column ‘ID’ as follows −
mysql> DESCRIBE test123;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| ID | int(11) | NO | | NULL | |
| Date | date | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.04 sec)
Now if we want to remove the NOT NULL constraint then we can use ALTER TABLE statement as follows −
mysql> ALTER TABLE test123 MODIFY ID INT NULL;
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> DESCRIBE test123;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------ +---------+------+-----+---------+-------+
| ID | int(11) | YES | | NULL | |
| Date | date | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.06 sec)
The above result set shows that NOT NULL constraint on column ‘ID’ has been removed.
In the query above, the keyword NULL after keyword MODIFY is optional. The following query will also produce the same result as above −
mysql> ALTER TABLE test123 MODIFY ID INT;
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0 | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "We can remove a NOT NULL constraint from a column of an existing table by using the ALTER TABLE statement."
},
{
"code": null,
"e": 1260,
"s": 1169,
"text": "Suppose we have a table ‘test123’ having a NOT NULL constraint on column ‘ID’ as follows −"
},
{
"code": null,
"e": 1616,
"s": 1260,
"text": "mysql> DESCRIBE test123;\n+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| ID | int(11) | NO | | NULL | |\n| Date | date | YES | | NULL | |\n+-------+---------+------+-----+---------+-------+\n2 rows in set (0.04 sec)"
},
{
"code": null,
"e": 1716,
"s": 1616,
"text": "Now if we want to remove the NOT NULL constraint then we can use ALTER TABLE statement as follows −"
},
{
"code": null,
"e": 2194,
"s": 1716,
"text": "mysql> ALTER TABLE test123 MODIFY ID INT NULL;\nQuery OK, 0 rows affected (0.20 sec)\nRecords: 0 Duplicates: 0 Warnings: 0\n\nmysql> DESCRIBE test123;\n+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+------ +---------+------+-----+---------+-------+\n| ID | int(11) | YES | | NULL | |\n| Date | date | YES | | NULL | |\n+-------+---------+------+-----+---------+-------+\n2 rows in set (0.06 sec)"
},
{
"code": null,
"e": 2279,
"s": 2194,
"text": "The above result set shows that NOT NULL constraint on column ‘ID’ has been removed."
},
{
"code": null,
"e": 2415,
"s": 2279,
"text": "In the query above, the keyword NULL after keyword MODIFY is optional. The following query will also produce the same result as above −"
},
{
"code": null,
"e": 2531,
"s": 2415,
"text": "mysql> ALTER TABLE test123 MODIFY ID INT;\nQuery OK, 0 rows affected (0.20 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
}
]
|
How to round correlation values in the correlation matrix to zero decimal places in R? | To find the correlation matrix, we simply need to use cor function with the data frame object name. For example, if we have a data frame named as df then the correlation matrix can be found by using cor(df). But the result will have too many decimal places to represent the correlation. If we want to avoid the values after decimal places, we can use round function.
Consider the mtcars data in base R −
Live Demo
data(mtcars)
cor(mtcars)
mpg cyl disp hp drat wt
mpg 1.0000000 -0.8521620 -0.8475514 -0.7761684 0.68117191 -0.8676594
cyl -0.8521620 1.0000000 0.9020329 0.8324475 -0.69993811 0.7824958
disp -0.8475514 0.9020329 1.0000000 0.7909486 -0.71021393 0.8879799
hp -0.7761684 0.8324475 0.7909486 1.0000000 -0.44875912 0.6587479
drat 0.6811719 -0.6999381 -0.7102139 -0.4487591 1.00000000 -0.7124406
wt -0.8676594 0.7824958 0.8879799 0.6587479 -0.71244065 1.0000000
qsec 0.4186840 -0.5912421 -0.4336979 -0.7082234 0.09120476 -0.1747159
vs 0.6640389 -0.8108118 -0.7104159 - 0.7230967 0.44027846 -0.5549157
am 0.5998324 -0.5226070 -0.5912270 -0.2432043 0.71271113 -0.6924953
gear 0.4802848 -0.4926866 -0.5555692 -0.1257043 0.69961013 -0.5832870
carb -0.5509251 0.5269883 0.3949769 0.7498125 -0.09078980 0.4276059
qsec vs am gear carb
mpg 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507
cyl -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829
disp -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686
hp -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247
drat 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980
wt -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594
qsec 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923
vs 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714
am -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435
gear -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284
carb -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000
qsec vs am gear carb
mpg 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507
cyl -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829
disp -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686
hp -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247
drat 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980
wt -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594
qsec 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923
vs 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714
am -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435
gear -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284
carb -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000
Finding the correlation matrix with correlation coefficients rounded to zero −
Live Demo
round(cor(mtcars),0)
mpg cyl disp hp drat wt qsec vs am gear carb
mpg 1 -1 -1 -1 1 -1 0 1 1 0 -1
cyl -1 1 1 1 -1 1 -1 -1 -1 0 1
disp -1 1 1 1 -1 1 0 -1 -1 -1 0
hp -1 1 1 1 0 1 -1 -1 0 0 1
drat 1 -1 -1 0 1 -1 0 0 1 1 0
wt -1 1 1 1 -1 1 0 -1 -1 -1 0
qsec 0 -1 0 -1 0 0 1 1 0 0 -1
vs 1 -1 -1 -1 0 -1 1 1 0 0 -1
am 1 -1 -1 0 1 -1 0 0 1 1 0
gear 0 0 -1 0 1 -1 0 0 1 1 0
carb -1 1 0 1 0 0 -1 -1 0 0 1
Consider the below data frame −
Live Demo
x1<-sample(rexp(5,1),20,replace=TRUE) x2<-sample(runif(5,1,2),20,replace=TRUE) x3<-sample(rnorm(4,0.95,0.04),20,replace=TRUE)
df_x<-data.frame(x1,x2,x3)
df_x
x1 x2 x3
1 2.89702241 1.764443 0.9478372
2 0.89472590 1.764443 0.9850543
3 0.89472590 1.299860 0.9850543
4 0.07786123 1.377727 0.9661181
5 2.89702241 1.452261 0.9478372
6 0.22655315 1.452261 0.9850543
7 2.89702241 1.452261 0.9478372
8 2.89702241 1.764443 0.9661181
9 0.46248476 1.764443 0.9850543
10 0.22655315 1.452261 0.9731809
11 0.89472590 1.764443 0.9731809
12 0.46248476 1.764443 0.9661181
13 2.89702241 1.452261 0.9731809
14 0.07786123 1.377727 0.9661181
15 0.89472590 1.377727 0.9478372
16 0.07786123 1.180832 0.9731809
17 0.22655315 1.377727 0.9731809
18 0.22655315 1.764443 0.9478372
19 2.89702241 1.764443 0.9731809
20 0.46248476 1.452261 0.9661181
cor(df_x)
x1 x2 x3
x1 1.00000000 0.05458349 -0.2571943
x2 0.05458349 1.00000000 -0.1760571
x3 -0.25719426 -0.17605707 1.0000000
round(cor(df_x),0)
x1 x2 x3
x1 1 0 0
x2 0 1 0
x3 0 0 1 | [
{
"code": null,
"e": 1429,
"s": 1062,
"text": "To find the correlation matrix, we simply need to use cor function with the data frame object name. For example, if we have a data frame named as df then the correlation matrix can be found by using cor(df). But the result will have too many decimal places to represent the correlation. If we want to avoid the values after decimal places, we can use round function."
},
{
"code": null,
"e": 1466,
"s": 1429,
"text": "Consider the mtcars data in base R −"
},
{
"code": null,
"e": 1477,
"s": 1466,
"text": " Live Demo"
},
{
"code": null,
"e": 1502,
"s": 1477,
"text": "data(mtcars)\ncor(mtcars)"
},
{
"code": null,
"e": 3229,
"s": 1502,
"text": " mpg cyl disp hp drat wt\nmpg 1.0000000 -0.8521620 -0.8475514 -0.7761684 0.68117191 -0.8676594\ncyl -0.8521620 1.0000000 0.9020329 0.8324475 -0.69993811 0.7824958\ndisp -0.8475514 0.9020329 1.0000000 0.7909486 -0.71021393 0.8879799\nhp -0.7761684 0.8324475 0.7909486 1.0000000 -0.44875912 0.6587479\ndrat 0.6811719 -0.6999381 -0.7102139 -0.4487591 1.00000000 -0.7124406\nwt -0.8676594 0.7824958 0.8879799 0.6587479 -0.71244065 1.0000000\nqsec 0.4186840 -0.5912421 -0.4336979 -0.7082234 0.09120476 -0.1747159\nvs 0.6640389 -0.8108118 -0.7104159 - 0.7230967 0.44027846 -0.5549157\nam 0.5998324 -0.5226070 -0.5912270 -0.2432043 0.71271113 -0.6924953\ngear 0.4802848 -0.4926866 -0.5555692 -0.1257043 0.69961013 -0.5832870\ncarb -0.5509251 0.5269883 0.3949769 0.7498125 -0.09078980 0.4276059\n qsec vs am gear carb\nmpg 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507\ncyl -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829\ndisp -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686\nhp -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247\ndrat 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980\nwt -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594\nqsec 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923\nvs 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714\nam -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435\ngear -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284\ncarb -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000"
},
{
"code": null,
"e": 3977,
"s": 3229,
"text": " qsec vs am gear carb\n mpg 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507\ncyl -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829\n disp -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686\n hp -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247\ndrat 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980\nwt -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594\nqsec 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923\nvs 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714\nam -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435\ngear -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284\ncarb -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000"
},
{
"code": null,
"e": 4056,
"s": 3977,
"text": "Finding the correlation matrix with correlation coefficients rounded to zero −"
},
{
"code": null,
"e": 4067,
"s": 4056,
"text": " Live Demo"
},
{
"code": null,
"e": 4088,
"s": 4067,
"text": "round(cor(mtcars),0)"
},
{
"code": null,
"e": 4724,
"s": 4088,
"text": "mpg cyl disp hp drat wt qsec vs am gear carb\nmpg 1 -1 -1 -1 1 -1 0 1 1 0 -1\ncyl -1 1 1 1 -1 1 -1 -1 -1 0 1\ndisp -1 1 1 1 -1 1 0 -1 -1 -1 0\nhp -1 1 1 1 0 1 -1 -1 0 0 1\ndrat 1 -1 -1 0 1 -1 0 0 1 1 0\nwt -1 1 1 1 -1 1 0 -1 -1 -1 0\nqsec 0 -1 0 -1 0 0 1 1 0 0 -1\nvs 1 -1 -1 -1 0 -1 1 1 0 0 -1\nam 1 -1 -1 0 1 -1 0 0 1 1 0\ngear 0 0 -1 0 1 -1 0 0 1 1 0\ncarb -1 1 0 1 0 0 -1 -1 0 0 1"
},
{
"code": null,
"e": 4756,
"s": 4724,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 4767,
"s": 4756,
"text": " Live Demo"
},
{
"code": null,
"e": 4925,
"s": 4767,
"text": "x1<-sample(rexp(5,1),20,replace=TRUE) x2<-sample(runif(5,1,2),20,replace=TRUE) x3<-sample(rnorm(4,0.95,0.04),20,replace=TRUE)\ndf_x<-data.frame(x1,x2,x3)\ndf_x"
},
{
"code": null,
"e": 5585,
"s": 4925,
"text": "x1 x2 x3\n1 2.89702241 1.764443 0.9478372\n2 0.89472590 1.764443 0.9850543\n3 0.89472590 1.299860 0.9850543\n4 0.07786123 1.377727 0.9661181\n5 2.89702241 1.452261 0.9478372\n6 0.22655315 1.452261 0.9850543\n7 2.89702241 1.452261 0.9478372\n8 2.89702241 1.764443 0.9661181\n9 0.46248476 1.764443 0.9850543\n10 0.22655315 1.452261 0.9731809\n11 0.89472590 1.764443 0.9731809\n12 0.46248476 1.764443 0.9661181\n13 2.89702241 1.452261 0.9731809\n14 0.07786123 1.377727 0.9661181\n15 0.89472590 1.377727 0.9478372\n16 0.07786123 1.180832 0.9731809\n17 0.22655315 1.377727 0.9731809\n18 0.22655315 1.764443 0.9478372\n19 2.89702241 1.764443 0.9731809\n20 0.46248476 1.452261 0.9661181"
},
{
"code": null,
"e": 5595,
"s": 5585,
"text": "cor(df_x)"
},
{
"code": null,
"e": 5721,
"s": 5595,
"text": " x1 x2 x3\n x1 1.00000000 0.05458349 -0.2571943\n x2 0.05458349 1.00000000 -0.1760571\n x3 -0.25719426 -0.17605707 1.0000000"
},
{
"code": null,
"e": 5740,
"s": 5721,
"text": "round(cor(df_x),0)"
},
{
"code": null,
"e": 5785,
"s": 5740,
"text": " x1 x2 x3\nx1 1 0 0\nx2 0 1 0\nx3 0 0 1"
}
]
|
Matlab program to rotate an image 180 degrees clockwise without using function - GeeksforGeeks | 07 Aug, 2020
An image is defined as two-dimensional function, f(x, y), where x and y are spatial (plane) coordinates, and the amplitude of f at any pair of coordinates(x, y) is called the Intensity or the Gray level of the image at that point. When x, y and the intensity values of f are all finite, discrete quantities, the image is digital image.
Digital image is composed of a finite number of elements, each of which has a particular location and value. These elements are called picture elements, image elements and pixels. Pixel is the smallest element of an image. Each pixel corresponds to any one value. For an 8-bit gray scale image, the value of the pixel is between 0-255.
The rows are rotated from end to -1 keeping the step size 1. To rotate the image clockwise, the columns are rotated from end to -1 keeping the step size 1.
Approach:
Read the image using imread function.
Show the image using imshow function.
Rotate the image.
Display the image using imshow.
Below is the implementation:
% Read the Imagea = imread("cameraman.png"); % Display the imageimshow(a); % Rotate the image clockwisei = a(end:-1 : 1, end:-1 : 1); % Display the rotated imagefigure, imshow(i);
Output:
Original Image –
Rotated Image –
Akanksha_Rai
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Stochastic Gradient Descent (SGD)
Copying Files to and from Docker Containers
Principal Component Analysis with Python
ML | Principal Component Analysis(PCA)
ML | Types of Learning – Supervised Learning
Q-Learning in Python
Classifying data using Support Vector Machines(SVMs) in Python
Getting Started with System Design
Deep Learning | Introduction to Long Short Term Memory
Learning Model Building in Scikit-learn : A Python Machine Learning Library | [
{
"code": null,
"e": 23837,
"s": 23809,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 24173,
"s": 23837,
"text": "An image is defined as two-dimensional function, f(x, y), where x and y are spatial (plane) coordinates, and the amplitude of f at any pair of coordinates(x, y) is called the Intensity or the Gray level of the image at that point. When x, y and the intensity values of f are all finite, discrete quantities, the image is digital image."
},
{
"code": null,
"e": 24509,
"s": 24173,
"text": "Digital image is composed of a finite number of elements, each of which has a particular location and value. These elements are called picture elements, image elements and pixels. Pixel is the smallest element of an image. Each pixel corresponds to any one value. For an 8-bit gray scale image, the value of the pixel is between 0-255."
},
{
"code": null,
"e": 24665,
"s": 24509,
"text": "The rows are rotated from end to -1 keeping the step size 1. To rotate the image clockwise, the columns are rotated from end to -1 keeping the step size 1."
},
{
"code": null,
"e": 24675,
"s": 24665,
"text": "Approach:"
},
{
"code": null,
"e": 24713,
"s": 24675,
"text": "Read the image using imread function."
},
{
"code": null,
"e": 24751,
"s": 24713,
"text": "Show the image using imshow function."
},
{
"code": null,
"e": 24769,
"s": 24751,
"text": "Rotate the image."
},
{
"code": null,
"e": 24801,
"s": 24769,
"text": "Display the image using imshow."
},
{
"code": null,
"e": 24830,
"s": 24801,
"text": "Below is the implementation:"
},
{
"code": "% Read the Imagea = imread(\"cameraman.png\"); % Display the imageimshow(a); % Rotate the image clockwisei = a(end:-1 : 1, end:-1 : 1); % Display the rotated imagefigure, imshow(i);",
"e": 25013,
"s": 24830,
"text": null
},
{
"code": null,
"e": 25021,
"s": 25013,
"text": "Output:"
},
{
"code": null,
"e": 25038,
"s": 25021,
"text": "Original Image –"
},
{
"code": null,
"e": 25054,
"s": 25038,
"text": "Rotated Image –"
},
{
"code": null,
"e": 25067,
"s": 25054,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 25084,
"s": 25067,
"text": "Image-Processing"
},
{
"code": null,
"e": 25091,
"s": 25084,
"text": "MATLAB"
},
{
"code": null,
"e": 25117,
"s": 25091,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 25215,
"s": 25117,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25224,
"s": 25215,
"text": "Comments"
},
{
"code": null,
"e": 25237,
"s": 25224,
"text": "Old Comments"
},
{
"code": null,
"e": 25276,
"s": 25237,
"text": "ML | Stochastic Gradient Descent (SGD)"
},
{
"code": null,
"e": 25320,
"s": 25276,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 25361,
"s": 25320,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 25400,
"s": 25361,
"text": "ML | Principal Component Analysis(PCA)"
},
{
"code": null,
"e": 25445,
"s": 25400,
"text": "ML | Types of Learning – Supervised Learning"
},
{
"code": null,
"e": 25466,
"s": 25445,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 25529,
"s": 25466,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 25564,
"s": 25529,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 25619,
"s": 25564,
"text": "Deep Learning | Introduction to Long Short Term Memory"
}
]
|
du command in Linux with examples - GeeksforGeeks | 17 Oct, 2019
du command, short for disk usage, is used to estimate file space usage.
The du command can be used to track the files and directories which are consuming excessive amount of space on hard disk drive.
Syntax :
du [OPTION]... [FILE]...
du [OPTION]... --files0-from=F
Examples :
du /home/mandeep/test
Output:
44 /home/mandeep/test/data
2012 /home/mandeep/test/system design
24 /home/mandeep/test/table/sample_table/tree
28 /home/mandeep/test/table/sample_table
32 /home/mandeep/test/table
100104 /home/mandeep/test
Options :
-0, –null : end each output line with NULL
-a, –all : write count of all files, not just directories
–apparent-size : print apparent sizes, rather than disk usage.
-B, –block-size=SIZE : scale sizes to SIZE before printing on console
-c, –total : produce grand total
-d, –max-depth=N : print total for directory only if it is N or fewer levels below command line argument
-h, –human-readable : print sizes in human readable format
-S, -separate-dirs : for directories, don’t include size of subdirectories
-s, –summarize : display only total for each directory
–time : show time of last modification of any file or directory.
–exclude=PATTERN : exclude files that match PATTERN
Command usage examples with options :
If we want to print sizes in human readable format(K, M, G), use -h option
du -h /home/mandeep/test
Output:
44K /home/mandeep/test/data
2.0M /home/mandeep/test/system design
24K /home/mandeep/test/table/sample_table/tree
28K /home/mandeep/test/table/sample_table
32K /home/mandeep/test/table
98M /home/mandeep/test
Use -a option for printing all files including directories.
du -a -h /home/mandeep/test
Output:
This is partial output of above command.
4.0K /home/mandeep/test/blah1-new
4.0K /home/mandeep/test/fbtest.py
8.0K /home/mandeep/test/data/4.txt
4.0K /home/mandeep/test/data/7.txt
4.0K /home/mandeep/test/data/1.txt
4.0K /home/mandeep/test/data/3.txt
4.0K /home/mandeep/test/data/6.txt
4.0K /home/mandeep/test/data/2.txt
4.0K /home/mandeep/test/data/8.txt
8.0K /home/mandeep/test/data/5.txt
44K /home/mandeep/test/data
4.0K /home/mandeep/test/notifier.py
Use -c option to print total size
du -c -h /home/mandeep/test
Output:
44K /home/mandeep/test/data
2.0M /home/mandeep/test/system design
24K /home/mandeep/test/table/sample_table/tree
28K /home/mandeep/test/table/sample_table
32K /home/mandeep/test/table
98M /home/mandeep/test
98M total
To print sizes till particular level, use -d option with level no.
du -d 1 /home/mandeep/test
Output:
44 /home/mandeep/test/data
2012 /home/mandeep/test/system design
32 /home/mandeep/test/table
100104 /home/mandeep/test
Now try with level 2, you will get some extra directories
du -d 2 /home/mandeep/test
Output:
44 /home/mandeep/test/data
2012 /home/mandeep/test/system design
28 /home/mandeep/test/table/sample_table
32 /home/mandeep/test/table
100104 /home/mandeep/test
Get summary of file system using -s option
du -s /home/mandeep/test
Output:
100104 /home/mandeep/test
Get the timestamp of last modified using --time option
du --time -h /home/mandeep/test
Output:
44K 2018-01-14 22:22 /home/mandeep/test/data
2.0M 2017-12-24 23:06 /home/mandeep/test/system design
24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree
28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table
32K 2017-12-30 10:20 /home/mandeep/test/table
98M 2018-02-02 17:32 /home/mandeep/test
If we want to print sizes in human readable format(K, M, G), use -h option
du -h /home/mandeep/test
Output:
44K /home/mandeep/test/data
2.0M /home/mandeep/test/system design
24K /home/mandeep/test/table/sample_table/tree
28K /home/mandeep/test/table/sample_table
32K /home/mandeep/test/table
98M /home/mandeep/test
du -h /home/mandeep/test
Output:
44K /home/mandeep/test/data
2.0M /home/mandeep/test/system design
24K /home/mandeep/test/table/sample_table/tree
28K /home/mandeep/test/table/sample_table
32K /home/mandeep/test/table
98M /home/mandeep/test
44K /home/mandeep/test/data
2.0M /home/mandeep/test/system design
24K /home/mandeep/test/table/sample_table/tree
28K /home/mandeep/test/table/sample_table
32K /home/mandeep/test/table
98M /home/mandeep/test
Use -a option for printing all files including directories.
du -a -h /home/mandeep/test
Output:
This is partial output of above command.
4.0K /home/mandeep/test/blah1-new
4.0K /home/mandeep/test/fbtest.py
8.0K /home/mandeep/test/data/4.txt
4.0K /home/mandeep/test/data/7.txt
4.0K /home/mandeep/test/data/1.txt
4.0K /home/mandeep/test/data/3.txt
4.0K /home/mandeep/test/data/6.txt
4.0K /home/mandeep/test/data/2.txt
4.0K /home/mandeep/test/data/8.txt
8.0K /home/mandeep/test/data/5.txt
44K /home/mandeep/test/data
4.0K /home/mandeep/test/notifier.py
du -a -h /home/mandeep/test
Output:
This is partial output of above command.
4.0K /home/mandeep/test/blah1-new
4.0K /home/mandeep/test/fbtest.py
8.0K /home/mandeep/test/data/4.txt
4.0K /home/mandeep/test/data/7.txt
4.0K /home/mandeep/test/data/1.txt
4.0K /home/mandeep/test/data/3.txt
4.0K /home/mandeep/test/data/6.txt
4.0K /home/mandeep/test/data/2.txt
4.0K /home/mandeep/test/data/8.txt
8.0K /home/mandeep/test/data/5.txt
44K /home/mandeep/test/data
4.0K /home/mandeep/test/notifier.py
Use -c option to print total size
du -c -h /home/mandeep/test
Output:
44K /home/mandeep/test/data
2.0M /home/mandeep/test/system design
24K /home/mandeep/test/table/sample_table/tree
28K /home/mandeep/test/table/sample_table
32K /home/mandeep/test/table
98M /home/mandeep/test
98M total
du -c -h /home/mandeep/test
Output:
44K /home/mandeep/test/data
2.0M /home/mandeep/test/system design
24K /home/mandeep/test/table/sample_table/tree
28K /home/mandeep/test/table/sample_table
32K /home/mandeep/test/table
98M /home/mandeep/test
98M total
To print sizes till particular level, use -d option with level no.
du -d 1 /home/mandeep/test
Output:
44 /home/mandeep/test/data
2012 /home/mandeep/test/system design
32 /home/mandeep/test/table
100104 /home/mandeep/test
Now try with level 2, you will get some extra directories
du -d 2 /home/mandeep/test
Output:
44 /home/mandeep/test/data
2012 /home/mandeep/test/system design
28 /home/mandeep/test/table/sample_table
32 /home/mandeep/test/table
100104 /home/mandeep/test
du -d 1 /home/mandeep/test
Output:
44 /home/mandeep/test/data
2012 /home/mandeep/test/system design
32 /home/mandeep/test/table
100104 /home/mandeep/test
Now try with level 2, you will get some extra directories
du -d 2 /home/mandeep/test
Output:
44 /home/mandeep/test/data
2012 /home/mandeep/test/system design
28 /home/mandeep/test/table/sample_table
32 /home/mandeep/test/table
100104 /home/mandeep/test
Get summary of file system using -s option
du -s /home/mandeep/test
Output:
100104 /home/mandeep/test
du -s /home/mandeep/test
Output:
100104 /home/mandeep/test
Get the timestamp of last modified using --time option
du --time -h /home/mandeep/test
Output:
44K 2018-01-14 22:22 /home/mandeep/test/data
2.0M 2017-12-24 23:06 /home/mandeep/test/system design
24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree
28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table
32K 2017-12-30 10:20 /home/mandeep/test/table
98M 2018-02-02 17:32 /home/mandeep/test
du --time -h /home/mandeep/test
Output:
44K 2018-01-14 22:22 /home/mandeep/test/data
2.0M 2017-12-24 23:06 /home/mandeep/test/system design
24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree
28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table
32K 2017-12-30 10:20 /home/mandeep/test/table
98M 2018-02-02 17:32 /home/mandeep/test
- Mandeep Singh
References :
1) du wikipedia
2) du man entry
Akanksha_Rai
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
Named Pipe or FIFO with example C program
ZIP command in Linux with examples
Mutex lock for Linux Thread Synchronization
Cat command in Linux with examples
Compiling with g++
Thread functions in C/C++
echo command in Linux with Examples
touch command in Linux with Examples | [
{
"code": null,
"e": 23737,
"s": 23706,
"text": " \n17 Oct, 2019\n"
},
{
"code": null,
"e": 23937,
"s": 23737,
"text": "du command, short for disk usage, is used to estimate file space usage.\nThe du command can be used to track the files and directories which are consuming excessive amount of space on hard disk drive."
},
{
"code": null,
"e": 23946,
"s": 23937,
"text": "Syntax :"
},
{
"code": null,
"e": 24003,
"s": 23946,
"text": "du [OPTION]... [FILE]...\ndu [OPTION]... --files0-from=F\n"
},
{
"code": null,
"e": 24014,
"s": 24003,
"text": "Examples :"
},
{
"code": null,
"e": 24037,
"s": 24014,
"text": "du /home/mandeep/test\n"
},
{
"code": null,
"e": 24045,
"s": 24037,
"text": "Output:"
},
{
"code": null,
"e": 24270,
"s": 24045,
"text": "44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n24 /home/mandeep/test/table/sample_table/tree\n28 /home/mandeep/test/table/sample_table\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n"
},
{
"code": null,
"e": 24280,
"s": 24270,
"text": "Options :"
},
{
"code": null,
"e": 24960,
"s": 24280,
"text": "\n-0, –null : end each output line with NULL\n-a, –all : write count of all files, not just directories\n–apparent-size : print apparent sizes, rather than disk usage.\n-B, –block-size=SIZE : scale sizes to SIZE before printing on console\n-c, –total : produce grand total\n-d, –max-depth=N : print total for directory only if it is N or fewer levels below command line argument\n-h, –human-readable : print sizes in human readable format\n-S, -separate-dirs : for directories, don’t include size of subdirectories\n-s, –summarize : display only total for each directory\n–time : show time of last modification of any file or directory.\n–exclude=PATTERN : exclude files that match PATTERN\n"
},
{
"code": null,
"e": 24998,
"s": 24960,
"text": "Command usage examples with options :"
},
{
"code": null,
"e": 27295,
"s": 24998,
"text": "\nIf we want to print sizes in human readable format(K, M, G), use -h option\ndu -h /home/mandeep/test \n\nOutput:\n44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n\n\nUse -a option for printing all files including directories.\ndu -a -h /home/mandeep/test\n\nOutput:\nThis is partial output of above command.\n4.0K /home/mandeep/test/blah1-new\n4.0K /home/mandeep/test/fbtest.py\n8.0K /home/mandeep/test/data/4.txt\n4.0K /home/mandeep/test/data/7.txt\n4.0K /home/mandeep/test/data/1.txt\n4.0K /home/mandeep/test/data/3.txt\n4.0K /home/mandeep/test/data/6.txt\n4.0K /home/mandeep/test/data/2.txt\n4.0K /home/mandeep/test/data/8.txt\n8.0K /home/mandeep/test/data/5.txt\n44K /home/mandeep/test/data\n4.0K /home/mandeep/test/notifier.py\n\n\n Use -c option to print total size\ndu -c -h /home/mandeep/test\n\nOutput:\n44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n98M total\n\n\nTo print sizes till particular level, use -d option with level no.\ndu -d 1 /home/mandeep/test\n\nOutput:\n44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n\nNow try with level 2, you will get some extra directories\ndu -d 2 /home/mandeep/test\n\nOutput:\n44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n28 /home/mandeep/test/table/sample_table\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n\n\n Get summary of file system using -s option\ndu -s /home/mandeep/test\n\nOutput:\n100104 /home/mandeep/test\n\n\nGet the timestamp of last modified using --time option\ndu --time -h /home/mandeep/test\n\nOutput:\n44K 2018-01-14 22:22 /home/mandeep/test/data\n2.0M 2017-12-24 23:06 /home/mandeep/test/system design\n24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree\n28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table\n32K 2017-12-30 10:20 /home/mandeep/test/table\n98M 2018-02-02 17:32 /home/mandeep/test\n\n\n"
},
{
"code": null,
"e": 27632,
"s": 27295,
"text": "If we want to print sizes in human readable format(K, M, G), use -h option\ndu -h /home/mandeep/test \n\nOutput:\n44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n\n"
},
{
"code": null,
"e": 27894,
"s": 27632,
"text": "du -h /home/mandeep/test \n\nOutput:\n44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n\n"
},
{
"code": null,
"e": 28120,
"s": 27894,
"text": "44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n"
},
{
"code": null,
"e": 28708,
"s": 28120,
"text": "Use -a option for printing all files including directories.\ndu -a -h /home/mandeep/test\n\nOutput:\nThis is partial output of above command.\n4.0K /home/mandeep/test/blah1-new\n4.0K /home/mandeep/test/fbtest.py\n8.0K /home/mandeep/test/data/4.txt\n4.0K /home/mandeep/test/data/7.txt\n4.0K /home/mandeep/test/data/1.txt\n4.0K /home/mandeep/test/data/3.txt\n4.0K /home/mandeep/test/data/6.txt\n4.0K /home/mandeep/test/data/2.txt\n4.0K /home/mandeep/test/data/8.txt\n8.0K /home/mandeep/test/data/5.txt\n44K /home/mandeep/test/data\n4.0K /home/mandeep/test/notifier.py\n\n"
},
{
"code": null,
"e": 28737,
"s": 28708,
"text": "du -a -h /home/mandeep/test\n"
},
{
"code": null,
"e": 28786,
"s": 28737,
"text": "Output:\nThis is partial output of above command."
},
{
"code": null,
"e": 29235,
"s": 28786,
"text": "4.0K /home/mandeep/test/blah1-new\n4.0K /home/mandeep/test/fbtest.py\n8.0K /home/mandeep/test/data/4.txt\n4.0K /home/mandeep/test/data/7.txt\n4.0K /home/mandeep/test/data/1.txt\n4.0K /home/mandeep/test/data/3.txt\n4.0K /home/mandeep/test/data/6.txt\n4.0K /home/mandeep/test/data/2.txt\n4.0K /home/mandeep/test/data/8.txt\n8.0K /home/mandeep/test/data/5.txt\n44K /home/mandeep/test/data\n4.0K /home/mandeep/test/notifier.py\n"
},
{
"code": null,
"e": 29547,
"s": 29235,
"text": " Use -c option to print total size\ndu -c -h /home/mandeep/test\n\nOutput:\n44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n98M total\n\n"
},
{
"code": null,
"e": 29576,
"s": 29547,
"text": "du -c -h /home/mandeep/test\n"
},
{
"code": null,
"e": 29584,
"s": 29576,
"text": "Output:"
},
{
"code": null,
"e": 29823,
"s": 29584,
"text": "44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n98M total\n"
},
{
"code": null,
"e": 30329,
"s": 29823,
"text": "To print sizes till particular level, use -d option with level no.\ndu -d 1 /home/mandeep/test\n\nOutput:\n44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n\nNow try with level 2, you will get some extra directories\ndu -d 2 /home/mandeep/test\n\nOutput:\n44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n28 /home/mandeep/test/table/sample_table\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n\n"
},
{
"code": null,
"e": 30357,
"s": 30329,
"text": "du -d 1 /home/mandeep/test\n"
},
{
"code": null,
"e": 30365,
"s": 30357,
"text": "Output:"
},
{
"code": null,
"e": 30497,
"s": 30365,
"text": "44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n"
},
{
"code": null,
"e": 30555,
"s": 30497,
"text": "Now try with level 2, you will get some extra directories"
},
{
"code": null,
"e": 30583,
"s": 30555,
"text": "du -d 2 /home/mandeep/test\n"
},
{
"code": null,
"e": 30591,
"s": 30583,
"text": "Output:"
},
{
"code": null,
"e": 30767,
"s": 30591,
"text": "44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n28 /home/mandeep/test/table/sample_table\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n"
},
{
"code": null,
"e": 30876,
"s": 30767,
"text": " Get summary of file system using -s option\ndu -s /home/mandeep/test\n\nOutput:\n100104 /home/mandeep/test\n\n"
},
{
"code": null,
"e": 30902,
"s": 30876,
"text": "du -s /home/mandeep/test\n"
},
{
"code": null,
"e": 30910,
"s": 30902,
"text": "Output:"
},
{
"code": null,
"e": 30940,
"s": 30910,
"text": "100104 /home/mandeep/test\n"
},
{
"code": null,
"e": 31383,
"s": 30940,
"text": "Get the timestamp of last modified using --time option\ndu --time -h /home/mandeep/test\n\nOutput:\n44K 2018-01-14 22:22 /home/mandeep/test/data\n2.0M 2017-12-24 23:06 /home/mandeep/test/system design\n24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree\n28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table\n32K 2017-12-30 10:20 /home/mandeep/test/table\n98M 2018-02-02 17:32 /home/mandeep/test\n\n"
},
{
"code": null,
"e": 31416,
"s": 31383,
"text": "du --time -h /home/mandeep/test\n"
},
{
"code": null,
"e": 31424,
"s": 31416,
"text": "Output:"
},
{
"code": null,
"e": 31770,
"s": 31424,
"text": "44K 2018-01-14 22:22 /home/mandeep/test/data\n2.0M 2017-12-24 23:06 /home/mandeep/test/system design\n24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree\n28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table\n32K 2017-12-30 10:20 /home/mandeep/test/table\n98M 2018-02-02 17:32 /home/mandeep/test\n"
},
{
"code": null,
"e": 31786,
"s": 31770,
"text": "- Mandeep Singh"
},
{
"code": null,
"e": 31831,
"s": 31786,
"text": "References :\n1) du wikipedia\n2) du man entry"
},
{
"code": null,
"e": 31844,
"s": 31831,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31860,
"s": 31844,
"text": "\nlinux-command\n"
},
{
"code": null,
"e": 31873,
"s": 31860,
"text": "\nLinux-Unix\n"
},
{
"code": null,
"e": 32078,
"s": 31873,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 32116,
"s": 32078,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 32151,
"s": 32116,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 32193,
"s": 32151,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 32228,
"s": 32193,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 32272,
"s": 32228,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 32307,
"s": 32272,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 32326,
"s": 32307,
"text": "Compiling with g++"
},
{
"code": null,
"e": 32352,
"s": 32326,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 32388,
"s": 32352,
"text": "echo command in Linux with Examples"
}
]
|
JavaScript Convert an array to JSON | To convert an array to JSON in JavaScript, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
</style>
</head>
<body>
<h1>Converting an array to JSON</h1>
<button class="Btn">CLICK HERE</button>
<p class="sample"></p>
<h3>Click the above button to convert the array into JSON</h3>
<script>
let sampleEle = document.querySelector(".sample");
let arr = [22, "A", 1, "HELLO", "J", 9, 22];
sampleEle.innerHTML = arr + "<br>";
document.querySelector(".Btn").addEventListener("click", () => {
sampleEle.innerHTML += JSON.stringify(arr);
});
</script>
</body>
</html>
On clicking the “CLICK HERE” button − | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "To convert an array to JSON in JavaScript, the code is as follows −"
},
{
"code": null,
"e": 1141,
"s": 1130,
"text": " Live Demo"
},
{
"code": null,
"e": 1750,
"s": 1141,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n</style>\n</head>\n<body>\n<h1>Converting an array to JSON</h1>\n<button class=\"Btn\">CLICK HERE</button>\n<p class=\"sample\"></p>\n<h3>Click the above button to convert the array into JSON</h3>\n<script>\n let sampleEle = document.querySelector(\".sample\");\n let arr = [22, \"A\", 1, \"HELLO\", \"J\", 9, 22];\n sampleEle.innerHTML = arr + \"<br>\";\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n sampleEle.innerHTML += JSON.stringify(arr);\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1788,
"s": 1750,
"text": "On clicking the “CLICK HERE” button −"
}
]
|
How To Design A Spam Filtering System with Machine Learning Algorithm | by Sie Huai Gan | Towards Data Science | In my day to day work in Visa as a software developer, email is one of the very important tool for communication. To have effective communication, spam filtering is one of the important feature.
So how do spam filtering system actually works? Can we design something similar from scratch?
The main goal of these two parts of article is to show how you could design a spam filtering system from scratch.
Outlines of this article are summarized as below:
EDA (Exploratory data analysis)Data PreprocessingFeature ExtractionScoring & MetricsImprovement by using Embedding + Neural Network (Part 2)Comparison of ML algorithm & Deep Learning (Part 2)
EDA (Exploratory data analysis)
Data Preprocessing
Feature Extraction
Scoring & Metrics
Improvement by using Embedding + Neural Network (Part 2)
Comparison of ML algorithm & Deep Learning (Part 2)
Let’s get started !
Exploratory Data Analysis is a very important process of data science. It helps the data scientist to understand the data at hand and relates it with the business context.
The open source tools that I will be using in visualizing and analyzing my data is Word Cloud.
Word Cloud is a data visualization tool used for representing text data. The size of the texts in the image represent the frequency or importance of the words in the training data.
Steps to take in this section:
Get the email dataExplore and analyze the dataVisualize the training data with Word Cloud & Bar Chart
Get the email data
Explore and analyze the data
Visualize the training data with Word Cloud & Bar Chart
Get the spam data
Data is the essential ingredients before we can develop any meaningful algorithm. Knowing where to get your data can be a very handy tool especially when you are just a beginner.
Below are a few of the famous repositories where you can easily get thousand kind of data set for free :
UC Irvine Machine Learning RepositoryKaggle datasetsAWS datasets
UC Irvine Machine Learning Repository
Kaggle datasets
AWS datasets
For this email spamming data set, it is distributed by Spam Assassin, you can click this link to go to the data set. There are a few categories of the data, you can read the readme.html to get more background information on the data.
In short, there is two types of data present in this repository, which is ham (non-spam) and spam data. Furthermore, in the ham data, there are easy and hard, which mean there is some non-spam data that has a very high similarity with spam data. This might pose a difficulty for our system to make a decision.
If you are using Linux or Mac, simply do this in the terminal, wget is simply a command that help you to download file given an url:
wget https://spamassassin.apache.org/old/publiccorpus/20030228_easy_ham.tar.bz2wget https://spamassassin.apache.org/old/publiccorpus/20030228_easy_ham_2.tar.bz2wget https://spamassassin.apache.org/old/publiccorpus/20030228_spam.tar.bz2wget https://spamassassin.apache.org/old/publiccorpus/20050311_spam_2.tar.bz2wget https://spamassassin.apache.org/old/publiccorpus/20030228_hard_ham.tar.bz2
Let’s run some code and see what content is inside all these emails!
Explore and Analyze the Data
Let’s take a look at the email message content and have a basic understanding of the data
This looks like a normal email reply to another person, which is not difficult to classified as a ham:
This is a bit of a messy solution but might be useful -If you have an internal zip drive (not sure about external) andyou bios supports using a zip as floppy drive, you could use a bootable zip disk with all the relevant dos utils.
Hard Ham is indeed more difficult to differentiate from the spam data, as they contain some key words such as limited time order, Special “Back to School” Offer, this make it very suspicious !
Hello Friends!We hope you had a pleasant week. Last weeks trivia questions was:What do these 3 films have in common: One Crazy Summer, Whispers in the =Dark, Moby Dick?=20Answer: Nantucket IslandCongratulations to our Winners:Caitlin O. of New Bedford, MassachusettsBrigid M. of Marblehead, MassachusettsSpecial "Back to School" Offer!For a limited time order our "Back to School" Snack Basket and receive =20% Off & FREE SHIPPING!
One of the spam training data does look like one of those spam advertisement email in our junk folder:
IMPORTANT INFORMATION:The new domain names are finally available to the general public at discount prices. Now you can register one of the exciting new .BIZ or .INFO domain names, as well as the original .COM and .NET names for just $14.95. These brand new domain extensions were recently approved by ICANN and have the same rights as the original .COM and .NET domain names. The biggest benefit is of-course that the .BIZ and .INFO domain names are currently more available. i.e. it will be much easier to register an attractive and easy-to-remember domain name for the same price. Visit: http://www.affordable-domains.com today for more info.
Wordcloud
Wordcloud is a useful visualization tool for you to have a rough estimate of the words that has the highest frequency in the data that you have.
From this visualization, you can notice something interesting about the spam email. A lot of them are having high number of “spammy” words such as: free, money, product etc. Having this awareness might help us to make better decision when it comes to designing the spam detection system.
One important thing to note is that word cloud only displays the frequency of the words, not necessarily the importance of the words. Hence it is necessary to do some data cleaning such as removing stopwords, punctuation and so on from the data before visualizing it.
N-grams model visualization
Another technique of visualization is by utilizing bar chart and display the frequency of the words that appear the most. N-gram means that how many words you are considering as a single unit when you are calculating the frequency of words.
In this article, I have shown the example of 1-gram, and 2-gram. You can definitely experiment by trying bigger n-gram model.
It is important to split your data set to training set and test set, so that you can evaluate the performance of your model using the test set before deploying it in a production environment.
One important thing to note when doing the train test split is to make sure the distribution of the data between the training set and testing set are similar.
What it means in this context is that the percentage of spam email in the training set and test set should be similar.
The distribution between train data and test data are quite similar which is around 20–21%, so we are good to go and start to process our data !
Text Cleaning
Text Cleaning is a very important step in machine learning because your data may contains a lot of noise and unwanted character such as punctuation, white space, numbers, hyperlink and etc.
Some standard procedures that people generally use are:
convert all letters to lower/upper case
removing numbers
removing punctuation
removing white spaces
removing hyperlink
removing stop words such as a, about, above, down, doing and the list goes on...
Word Stemming
Word lemmatization
The two techniques that might seem foreign to most people are word stemming and word lemmatization. Both these techniques are trying to reduce the words to its most basic form, but doing this with different approaches.
Word stemming — Stemming algorithms work by removing the end or the beginning of the words, using a list of common prefixes and suffixes that can be found in that language. Examples of Word Stemming for English words are as below:
Word Lemmatization — Lemmatization is utilizing the dictionary of a particular language and tried to convert the words back to its base form. It will try to take into account of the meaning of the verbs and convert it back to the most suitable base form.
Implementing these two algorithms might be tricky and requires a lot of thinking and design to deal with different edge cases.
Luckily NLTK library has provided the implementation of these two algorithms, so we can use it out of the box from the library!
Import the library and start designing some functions to help us understand the basic working of these two algorithms.
# Just import them and use itfrom nltk.stem import PorterStemmerfrom nltk.stem import WordNetLemmatizerstemmer = PorterStemmer()lemmatizer = WordNetLemmatizer()dirty_text = "He studies in the house yesterday, unluckily, the fans breaks down"def word_stemmer(words): stem_words = [stemmer.stem(o) for o in words] return " ".join(stem_words)def word_lemmatizer(words): lemma_words = [lemmatizer.lemmatize(o) for o in words] return " ".join(lemma_words)
The output of word stemmer is very obvious, some of the endings of the words have been chopped off
clean_text = word_stemmer(dirty_text.split(" "))clean_text#Output'He studi in the hous yesterday, unluckily, the fan break down'
The lemmatization has converted studies -> study, breaks -> break
clean_text = word_lemmatizer(dirty_text.split(" "))clean_text#Output'I study in the house yesterday, unluckily, the fan break down'
Our algorithm always expect the input to be integers/floats, so we need to have some feature extraction layer in the middle to convert the words to integers/floats.
There are a couples ways of doing this, and today I am going to introduce:
CountVectorizerTfidfVectorizerWord Embedding
CountVectorizer
TfidfVectorizer
Word Embedding
CountVectorizer
First we need to input all the training data into CountVectorizer and the CountVectorizer will keep a dictionary of every word and its respective id and this id will relate to the word count of this word inside this whole training set.
For example, a sentence like ‘I like to eat apple and drink apple juice’
from sklearn.feature_extraction.text import CountVectorizer# list of text documentstext = ["I like to eat apple and drink apple juice"]# create the transformvectorizer = CountVectorizer()# tokenize and build vocabvectorizer.fit(text)# summarizeprint(vectorizer.vocabulary_)# encode documentvector = vectorizer.transform(text)# summarize encoded vectorprint(vector.shape)print(type(vector))print(vector.toarray())# Output# The number follow by the word are the index of the word{'like': 5, 'to': 6, 'eat': 3, 'apple': 1, 'and': 0, 'drink': 2, 'juice': 4}# The index relates to the position of the word count array below# "I like to eat apple and drink apple juice" -> [1 2 1 1 1 1 1]# apple which has the index 1 correspond to the word count of 2 in the array
TfidfVectorizer
Word counts are good but can we do better? One issue with simple word count is that some words like ‘the’, ‘and’ will appear many times and they don’t really add too much meaningful information.
Another popular alternative is TfidfVectorizer. Besides of taking the word count of every words, words that often appears across multiple documents or sentences, the vectorizer will try to downscale them.
For more info about CountVectorizer and TfidfVectorizer, please read from this great piece of article, which is also where I gain most of my understanding.
Word Embedding
There is a lot of great articles online that explains the details of word embedding and the algorithm to generate them. So here, I will skip most of them and try to give you a rough idea of what it is.
Word embedding is trying to convert a word to a vectorized format and this vector represents the position of this word in a higher dimensional space.
For words that have similar meaning, the cosine distance of those two word vectors will be shorter and they will be closer to each other.
And in fact, these words are vectors, so you can even perform math operations on them ! The end results of these operation will be another vector that maps to a word. Unexpectedly, those operations produce some amazing result !
Example 1 : King- Man + Woman = Queen
Example 2: Madrid-Spain+France = Paris
Example 3: Walking-Swimming+Swam= Walked
Simply put, word embedding is a very powerful representation of the words and one of the well known techniques in generating this embedding is Word2Vec.
Hooh ! After converting all the sentences into some form of vectors, it comes to the most exciting part of our articles → Algorithm Implementation !
TfidfVectorizer + Naive Bayes Algorithm
The first approach that I take was to use the TfidfVectorizer as a feature extraction tools and Naive Bayes algorithm to do the prediction. Naive Bayes is a simple and a probabilistic traditional machine learning algorithm.
It is very popular even in the past in solving problems like spam detection. The details of Naive Bayes can be checkout at this article by Devi Soni which is a concise and clear explanation of the theory of Naive Bayes algorithm.
Using Naive Bayes library provided by sklearn library save us a lot of hassle in implementing this algorithm ourselves. We can easily get this done in a few lines of codes
from sklearn.naive_bayes import GaussianNBclf.fit(x_train_features.toarray(),y_train)# Output of the score is the accuracy of the prediction# Accuracy: 0.995clf.score(x_train_features.toarray(),y_train)# Accuracy: 0.932clf.score(x_test_features.toarray(),y_test)
We achieve an accuracy of 93.2%. But accuracy is not solely the metrics to evaluate the performance of an algorithm. Lets try out other scoring metrics and that may help us to understand thoroughly how well this model is doing.
Disadvantages of accuracy
When it comes to evaluation of a data science model’s performance, sometimes accuracy may not be the best indicator.
Some problems that we are solving in real life might have a very imbalanced class and using accuracy might not give us enough confidence to understand the algorithm’s performance.
In the email spamming problem that we are trying to solve, the spam data is approximately 20% of our data. If our algorithm predicts all the email as non-spam, it will achieve an accuracy of 80%.
And for some problem that has only 1% of positive data, predicting all the sample as negative will give them an accuracy of 99% but we all know this kind of model is useless in a real life scenario.
Precision & Recall
Precision & Recall is the common evaluation metrics that people use when they are evaluating class-imbalanced classification model.
Let’s try to understand what questions Precision & Recall is trying to answer,
Precision: What proportion of positive identifications was actually correct ?
Recall: What actual proportion of actual positives was identified correctly?
So, precision is evaluating, when a model predict something as positive, how accurate the model is. On the other hand, recall is evaluating how well a model in finding all the positive samples.
The mathematical equation for precision & recall are as respective
TP: True Positive
FP : False Positive
TN: True Negative
FN: False Negative
Confusion Matrix
Confusion Matrix is a very good way to understand results like true positive, false positive, true negative and so on.
Sklearn documentation has provided a sample code of how to plot nice looking confusion matrix to visualize your result. You can check it out here, or you can find the code in the notebook that I am sharing at the end of the articles.
Precision: 87.82%Recall: 81.01%
The recall of this model is rather low, it might not be doing a good enough job in discovering the spam email. How do we do better than this ?
In this article, I have showed you all the necessary steps needed in designing a spam detection algorithm. Just a brief recap:
Explore and understand your dataVisualize the data at hand to gain a better intuition — Wordcloud, N-gram Bar ChartText Cleaning — Word Stemmer and Word LemmatizationFeature Extraction — Count Vectorizer, Tfidf Vectorizer, Word EmbeddingAlgorithm — Naive BayesScoring & Metrics — Accuracy, Precision, Recall
Explore and understand your data
Visualize the data at hand to gain a better intuition — Wordcloud, N-gram Bar Chart
Text Cleaning — Word Stemmer and Word Lemmatization
Feature Extraction — Count Vectorizer, Tfidf Vectorizer, Word Embedding
Algorithm — Naive Bayes
Scoring & Metrics — Accuracy, Precision, Recall
Here concludes the first part of demonstration in designing spam detection algorithm.
There is a part 2 of this article! I am going to demonstrate how you could improve the performance in terms of accuracy, precision and recall of the model by using word embeddings and deep learning model. Read the article here if you are interested!
You can clone the notebook from Github or run it from Colab directly. Leave any questions you have at the comments section below or post me questions on LinkedIn ! Thanks for reading 😀
www.linkedin.com
Ant Financial Singapore is expanding and actively hiring for Java Developers and QA engineer roles.
Our team aims to create payment product that provides the best payment experience for our customer. It is a good opportunity to learn how to build highly reliable payment system under huge traffic.
These roles currently extend to candidates that are based in Singapore , China or Southeast Asia region.
If you are excited to build payment product that serves more than 20 million of users, feel free to send your CV to [email protected] or you can ping me via LinkedIn to find out more. Thanks ! | [
{
"code": null,
"e": 367,
"s": 172,
"text": "In my day to day work in Visa as a software developer, email is one of the very important tool for communication. To have effective communication, spam filtering is one of the important feature."
},
{
"code": null,
"e": 461,
"s": 367,
"text": "So how do spam filtering system actually works? Can we design something similar from scratch?"
},
{
"code": null,
"e": 575,
"s": 461,
"text": "The main goal of these two parts of article is to show how you could design a spam filtering system from scratch."
},
{
"code": null,
"e": 625,
"s": 575,
"text": "Outlines of this article are summarized as below:"
},
{
"code": null,
"e": 817,
"s": 625,
"text": "EDA (Exploratory data analysis)Data PreprocessingFeature ExtractionScoring & MetricsImprovement by using Embedding + Neural Network (Part 2)Comparison of ML algorithm & Deep Learning (Part 2)"
},
{
"code": null,
"e": 849,
"s": 817,
"text": "EDA (Exploratory data analysis)"
},
{
"code": null,
"e": 868,
"s": 849,
"text": "Data Preprocessing"
},
{
"code": null,
"e": 887,
"s": 868,
"text": "Feature Extraction"
},
{
"code": null,
"e": 905,
"s": 887,
"text": "Scoring & Metrics"
},
{
"code": null,
"e": 962,
"s": 905,
"text": "Improvement by using Embedding + Neural Network (Part 2)"
},
{
"code": null,
"e": 1014,
"s": 962,
"text": "Comparison of ML algorithm & Deep Learning (Part 2)"
},
{
"code": null,
"e": 1034,
"s": 1014,
"text": "Let’s get started !"
},
{
"code": null,
"e": 1206,
"s": 1034,
"text": "Exploratory Data Analysis is a very important process of data science. It helps the data scientist to understand the data at hand and relates it with the business context."
},
{
"code": null,
"e": 1301,
"s": 1206,
"text": "The open source tools that I will be using in visualizing and analyzing my data is Word Cloud."
},
{
"code": null,
"e": 1482,
"s": 1301,
"text": "Word Cloud is a data visualization tool used for representing text data. The size of the texts in the image represent the frequency or importance of the words in the training data."
},
{
"code": null,
"e": 1513,
"s": 1482,
"text": "Steps to take in this section:"
},
{
"code": null,
"e": 1615,
"s": 1513,
"text": "Get the email dataExplore and analyze the dataVisualize the training data with Word Cloud & Bar Chart"
},
{
"code": null,
"e": 1634,
"s": 1615,
"text": "Get the email data"
},
{
"code": null,
"e": 1663,
"s": 1634,
"text": "Explore and analyze the data"
},
{
"code": null,
"e": 1719,
"s": 1663,
"text": "Visualize the training data with Word Cloud & Bar Chart"
},
{
"code": null,
"e": 1737,
"s": 1719,
"text": "Get the spam data"
},
{
"code": null,
"e": 1916,
"s": 1737,
"text": "Data is the essential ingredients before we can develop any meaningful algorithm. Knowing where to get your data can be a very handy tool especially when you are just a beginner."
},
{
"code": null,
"e": 2021,
"s": 1916,
"text": "Below are a few of the famous repositories where you can easily get thousand kind of data set for free :"
},
{
"code": null,
"e": 2086,
"s": 2021,
"text": "UC Irvine Machine Learning RepositoryKaggle datasetsAWS datasets"
},
{
"code": null,
"e": 2124,
"s": 2086,
"text": "UC Irvine Machine Learning Repository"
},
{
"code": null,
"e": 2140,
"s": 2124,
"text": "Kaggle datasets"
},
{
"code": null,
"e": 2153,
"s": 2140,
"text": "AWS datasets"
},
{
"code": null,
"e": 2387,
"s": 2153,
"text": "For this email spamming data set, it is distributed by Spam Assassin, you can click this link to go to the data set. There are a few categories of the data, you can read the readme.html to get more background information on the data."
},
{
"code": null,
"e": 2697,
"s": 2387,
"text": "In short, there is two types of data present in this repository, which is ham (non-spam) and spam data. Furthermore, in the ham data, there are easy and hard, which mean there is some non-spam data that has a very high similarity with spam data. This might pose a difficulty for our system to make a decision."
},
{
"code": null,
"e": 2830,
"s": 2697,
"text": "If you are using Linux or Mac, simply do this in the terminal, wget is simply a command that help you to download file given an url:"
},
{
"code": null,
"e": 3222,
"s": 2830,
"text": "wget https://spamassassin.apache.org/old/publiccorpus/20030228_easy_ham.tar.bz2wget https://spamassassin.apache.org/old/publiccorpus/20030228_easy_ham_2.tar.bz2wget https://spamassassin.apache.org/old/publiccorpus/20030228_spam.tar.bz2wget https://spamassassin.apache.org/old/publiccorpus/20050311_spam_2.tar.bz2wget https://spamassassin.apache.org/old/publiccorpus/20030228_hard_ham.tar.bz2"
},
{
"code": null,
"e": 3291,
"s": 3222,
"text": "Let’s run some code and see what content is inside all these emails!"
},
{
"code": null,
"e": 3320,
"s": 3291,
"text": "Explore and Analyze the Data"
},
{
"code": null,
"e": 3410,
"s": 3320,
"text": "Let’s take a look at the email message content and have a basic understanding of the data"
},
{
"code": null,
"e": 3513,
"s": 3410,
"text": "This looks like a normal email reply to another person, which is not difficult to classified as a ham:"
},
{
"code": null,
"e": 3745,
"s": 3513,
"text": "This is a bit of a messy solution but might be useful -If you have an internal zip drive (not sure about external) andyou bios supports using a zip as floppy drive, you could use a bootable zip disk with all the relevant dos utils."
},
{
"code": null,
"e": 3938,
"s": 3745,
"text": "Hard Ham is indeed more difficult to differentiate from the spam data, as they contain some key words such as limited time order, Special “Back to School” Offer, this make it very suspicious !"
},
{
"code": null,
"e": 4370,
"s": 3938,
"text": "Hello Friends!We hope you had a pleasant week. Last weeks trivia questions was:What do these 3 films have in common: One Crazy Summer, Whispers in the =Dark, Moby Dick?=20Answer: Nantucket IslandCongratulations to our Winners:Caitlin O. of New Bedford, MassachusettsBrigid M. of Marblehead, MassachusettsSpecial \"Back to School\" Offer!For a limited time order our \"Back to School\" Snack Basket and receive =20% Off & FREE SHIPPING!"
},
{
"code": null,
"e": 4473,
"s": 4370,
"text": "One of the spam training data does look like one of those spam advertisement email in our junk folder:"
},
{
"code": null,
"e": 5119,
"s": 4473,
"text": "IMPORTANT INFORMATION:The new domain names are finally available to the general public at discount prices. Now you can register one of the exciting new .BIZ or .INFO domain names, as well as the original .COM and .NET names for just $14.95. These brand new domain extensions were recently approved by ICANN and have the same rights as the original .COM and .NET domain names. The biggest benefit is of-course that the .BIZ and .INFO domain names are currently more available. i.e. it will be much easier to register an attractive and easy-to-remember domain name for the same price. Visit: http://www.affordable-domains.com today for more info."
},
{
"code": null,
"e": 5129,
"s": 5119,
"text": "Wordcloud"
},
{
"code": null,
"e": 5274,
"s": 5129,
"text": "Wordcloud is a useful visualization tool for you to have a rough estimate of the words that has the highest frequency in the data that you have."
},
{
"code": null,
"e": 5562,
"s": 5274,
"text": "From this visualization, you can notice something interesting about the spam email. A lot of them are having high number of “spammy” words such as: free, money, product etc. Having this awareness might help us to make better decision when it comes to designing the spam detection system."
},
{
"code": null,
"e": 5830,
"s": 5562,
"text": "One important thing to note is that word cloud only displays the frequency of the words, not necessarily the importance of the words. Hence it is necessary to do some data cleaning such as removing stopwords, punctuation and so on from the data before visualizing it."
},
{
"code": null,
"e": 5858,
"s": 5830,
"text": "N-grams model visualization"
},
{
"code": null,
"e": 6099,
"s": 5858,
"text": "Another technique of visualization is by utilizing bar chart and display the frequency of the words that appear the most. N-gram means that how many words you are considering as a single unit when you are calculating the frequency of words."
},
{
"code": null,
"e": 6225,
"s": 6099,
"text": "In this article, I have shown the example of 1-gram, and 2-gram. You can definitely experiment by trying bigger n-gram model."
},
{
"code": null,
"e": 6417,
"s": 6225,
"text": "It is important to split your data set to training set and test set, so that you can evaluate the performance of your model using the test set before deploying it in a production environment."
},
{
"code": null,
"e": 6576,
"s": 6417,
"text": "One important thing to note when doing the train test split is to make sure the distribution of the data between the training set and testing set are similar."
},
{
"code": null,
"e": 6695,
"s": 6576,
"text": "What it means in this context is that the percentage of spam email in the training set and test set should be similar."
},
{
"code": null,
"e": 6840,
"s": 6695,
"text": "The distribution between train data and test data are quite similar which is around 20–21%, so we are good to go and start to process our data !"
},
{
"code": null,
"e": 6854,
"s": 6840,
"text": "Text Cleaning"
},
{
"code": null,
"e": 7044,
"s": 6854,
"text": "Text Cleaning is a very important step in machine learning because your data may contains a lot of noise and unwanted character such as punctuation, white space, numbers, hyperlink and etc."
},
{
"code": null,
"e": 7100,
"s": 7044,
"text": "Some standard procedures that people generally use are:"
},
{
"code": null,
"e": 7140,
"s": 7100,
"text": "convert all letters to lower/upper case"
},
{
"code": null,
"e": 7157,
"s": 7140,
"text": "removing numbers"
},
{
"code": null,
"e": 7178,
"s": 7157,
"text": "removing punctuation"
},
{
"code": null,
"e": 7200,
"s": 7178,
"text": "removing white spaces"
},
{
"code": null,
"e": 7219,
"s": 7200,
"text": "removing hyperlink"
},
{
"code": null,
"e": 7300,
"s": 7219,
"text": "removing stop words such as a, about, above, down, doing and the list goes on..."
},
{
"code": null,
"e": 7314,
"s": 7300,
"text": "Word Stemming"
},
{
"code": null,
"e": 7333,
"s": 7314,
"text": "Word lemmatization"
},
{
"code": null,
"e": 7552,
"s": 7333,
"text": "The two techniques that might seem foreign to most people are word stemming and word lemmatization. Both these techniques are trying to reduce the words to its most basic form, but doing this with different approaches."
},
{
"code": null,
"e": 7783,
"s": 7552,
"text": "Word stemming — Stemming algorithms work by removing the end or the beginning of the words, using a list of common prefixes and suffixes that can be found in that language. Examples of Word Stemming for English words are as below:"
},
{
"code": null,
"e": 8038,
"s": 7783,
"text": "Word Lemmatization — Lemmatization is utilizing the dictionary of a particular language and tried to convert the words back to its base form. It will try to take into account of the meaning of the verbs and convert it back to the most suitable base form."
},
{
"code": null,
"e": 8165,
"s": 8038,
"text": "Implementing these two algorithms might be tricky and requires a lot of thinking and design to deal with different edge cases."
},
{
"code": null,
"e": 8293,
"s": 8165,
"text": "Luckily NLTK library has provided the implementation of these two algorithms, so we can use it out of the box from the library!"
},
{
"code": null,
"e": 8412,
"s": 8293,
"text": "Import the library and start designing some functions to help us understand the basic working of these two algorithms."
},
{
"code": null,
"e": 8873,
"s": 8412,
"text": "# Just import them and use itfrom nltk.stem import PorterStemmerfrom nltk.stem import WordNetLemmatizerstemmer = PorterStemmer()lemmatizer = WordNetLemmatizer()dirty_text = \"He studies in the house yesterday, unluckily, the fans breaks down\"def word_stemmer(words): stem_words = [stemmer.stem(o) for o in words] return \" \".join(stem_words)def word_lemmatizer(words): lemma_words = [lemmatizer.lemmatize(o) for o in words] return \" \".join(lemma_words)"
},
{
"code": null,
"e": 8972,
"s": 8873,
"text": "The output of word stemmer is very obvious, some of the endings of the words have been chopped off"
},
{
"code": null,
"e": 9101,
"s": 8972,
"text": "clean_text = word_stemmer(dirty_text.split(\" \"))clean_text#Output'He studi in the hous yesterday, unluckily, the fan break down'"
},
{
"code": null,
"e": 9167,
"s": 9101,
"text": "The lemmatization has converted studies -> study, breaks -> break"
},
{
"code": null,
"e": 9299,
"s": 9167,
"text": "clean_text = word_lemmatizer(dirty_text.split(\" \"))clean_text#Output'I study in the house yesterday, unluckily, the fan break down'"
},
{
"code": null,
"e": 9464,
"s": 9299,
"text": "Our algorithm always expect the input to be integers/floats, so we need to have some feature extraction layer in the middle to convert the words to integers/floats."
},
{
"code": null,
"e": 9539,
"s": 9464,
"text": "There are a couples ways of doing this, and today I am going to introduce:"
},
{
"code": null,
"e": 9584,
"s": 9539,
"text": "CountVectorizerTfidfVectorizerWord Embedding"
},
{
"code": null,
"e": 9600,
"s": 9584,
"text": "CountVectorizer"
},
{
"code": null,
"e": 9616,
"s": 9600,
"text": "TfidfVectorizer"
},
{
"code": null,
"e": 9631,
"s": 9616,
"text": "Word Embedding"
},
{
"code": null,
"e": 9647,
"s": 9631,
"text": "CountVectorizer"
},
{
"code": null,
"e": 9883,
"s": 9647,
"text": "First we need to input all the training data into CountVectorizer and the CountVectorizer will keep a dictionary of every word and its respective id and this id will relate to the word count of this word inside this whole training set."
},
{
"code": null,
"e": 9956,
"s": 9883,
"text": "For example, a sentence like ‘I like to eat apple and drink apple juice’"
},
{
"code": null,
"e": 10715,
"s": 9956,
"text": "from sklearn.feature_extraction.text import CountVectorizer# list of text documentstext = [\"I like to eat apple and drink apple juice\"]# create the transformvectorizer = CountVectorizer()# tokenize and build vocabvectorizer.fit(text)# summarizeprint(vectorizer.vocabulary_)# encode documentvector = vectorizer.transform(text)# summarize encoded vectorprint(vector.shape)print(type(vector))print(vector.toarray())# Output# The number follow by the word are the index of the word{'like': 5, 'to': 6, 'eat': 3, 'apple': 1, 'and': 0, 'drink': 2, 'juice': 4}# The index relates to the position of the word count array below# \"I like to eat apple and drink apple juice\" -> [1 2 1 1 1 1 1]# apple which has the index 1 correspond to the word count of 2 in the array"
},
{
"code": null,
"e": 10731,
"s": 10715,
"text": "TfidfVectorizer"
},
{
"code": null,
"e": 10926,
"s": 10731,
"text": "Word counts are good but can we do better? One issue with simple word count is that some words like ‘the’, ‘and’ will appear many times and they don’t really add too much meaningful information."
},
{
"code": null,
"e": 11131,
"s": 10926,
"text": "Another popular alternative is TfidfVectorizer. Besides of taking the word count of every words, words that often appears across multiple documents or sentences, the vectorizer will try to downscale them."
},
{
"code": null,
"e": 11287,
"s": 11131,
"text": "For more info about CountVectorizer and TfidfVectorizer, please read from this great piece of article, which is also where I gain most of my understanding."
},
{
"code": null,
"e": 11302,
"s": 11287,
"text": "Word Embedding"
},
{
"code": null,
"e": 11504,
"s": 11302,
"text": "There is a lot of great articles online that explains the details of word embedding and the algorithm to generate them. So here, I will skip most of them and try to give you a rough idea of what it is."
},
{
"code": null,
"e": 11654,
"s": 11504,
"text": "Word embedding is trying to convert a word to a vectorized format and this vector represents the position of this word in a higher dimensional space."
},
{
"code": null,
"e": 11792,
"s": 11654,
"text": "For words that have similar meaning, the cosine distance of those two word vectors will be shorter and they will be closer to each other."
},
{
"code": null,
"e": 12020,
"s": 11792,
"text": "And in fact, these words are vectors, so you can even perform math operations on them ! The end results of these operation will be another vector that maps to a word. Unexpectedly, those operations produce some amazing result !"
},
{
"code": null,
"e": 12058,
"s": 12020,
"text": "Example 1 : King- Man + Woman = Queen"
},
{
"code": null,
"e": 12097,
"s": 12058,
"text": "Example 2: Madrid-Spain+France = Paris"
},
{
"code": null,
"e": 12138,
"s": 12097,
"text": "Example 3: Walking-Swimming+Swam= Walked"
},
{
"code": null,
"e": 12291,
"s": 12138,
"text": "Simply put, word embedding is a very powerful representation of the words and one of the well known techniques in generating this embedding is Word2Vec."
},
{
"code": null,
"e": 12440,
"s": 12291,
"text": "Hooh ! After converting all the sentences into some form of vectors, it comes to the most exciting part of our articles → Algorithm Implementation !"
},
{
"code": null,
"e": 12480,
"s": 12440,
"text": "TfidfVectorizer + Naive Bayes Algorithm"
},
{
"code": null,
"e": 12704,
"s": 12480,
"text": "The first approach that I take was to use the TfidfVectorizer as a feature extraction tools and Naive Bayes algorithm to do the prediction. Naive Bayes is a simple and a probabilistic traditional machine learning algorithm."
},
{
"code": null,
"e": 12934,
"s": 12704,
"text": "It is very popular even in the past in solving problems like spam detection. The details of Naive Bayes can be checkout at this article by Devi Soni which is a concise and clear explanation of the theory of Naive Bayes algorithm."
},
{
"code": null,
"e": 13106,
"s": 12934,
"text": "Using Naive Bayes library provided by sklearn library save us a lot of hassle in implementing this algorithm ourselves. We can easily get this done in a few lines of codes"
},
{
"code": null,
"e": 13369,
"s": 13106,
"text": "from sklearn.naive_bayes import GaussianNBclf.fit(x_train_features.toarray(),y_train)# Output of the score is the accuracy of the prediction# Accuracy: 0.995clf.score(x_train_features.toarray(),y_train)# Accuracy: 0.932clf.score(x_test_features.toarray(),y_test)"
},
{
"code": null,
"e": 13597,
"s": 13369,
"text": "We achieve an accuracy of 93.2%. But accuracy is not solely the metrics to evaluate the performance of an algorithm. Lets try out other scoring metrics and that may help us to understand thoroughly how well this model is doing."
},
{
"code": null,
"e": 13623,
"s": 13597,
"text": "Disadvantages of accuracy"
},
{
"code": null,
"e": 13740,
"s": 13623,
"text": "When it comes to evaluation of a data science model’s performance, sometimes accuracy may not be the best indicator."
},
{
"code": null,
"e": 13920,
"s": 13740,
"text": "Some problems that we are solving in real life might have a very imbalanced class and using accuracy might not give us enough confidence to understand the algorithm’s performance."
},
{
"code": null,
"e": 14116,
"s": 13920,
"text": "In the email spamming problem that we are trying to solve, the spam data is approximately 20% of our data. If our algorithm predicts all the email as non-spam, it will achieve an accuracy of 80%."
},
{
"code": null,
"e": 14315,
"s": 14116,
"text": "And for some problem that has only 1% of positive data, predicting all the sample as negative will give them an accuracy of 99% but we all know this kind of model is useless in a real life scenario."
},
{
"code": null,
"e": 14334,
"s": 14315,
"text": "Precision & Recall"
},
{
"code": null,
"e": 14466,
"s": 14334,
"text": "Precision & Recall is the common evaluation metrics that people use when they are evaluating class-imbalanced classification model."
},
{
"code": null,
"e": 14545,
"s": 14466,
"text": "Let’s try to understand what questions Precision & Recall is trying to answer,"
},
{
"code": null,
"e": 14623,
"s": 14545,
"text": "Precision: What proportion of positive identifications was actually correct ?"
},
{
"code": null,
"e": 14700,
"s": 14623,
"text": "Recall: What actual proportion of actual positives was identified correctly?"
},
{
"code": null,
"e": 14894,
"s": 14700,
"text": "So, precision is evaluating, when a model predict something as positive, how accurate the model is. On the other hand, recall is evaluating how well a model in finding all the positive samples."
},
{
"code": null,
"e": 14961,
"s": 14894,
"text": "The mathematical equation for precision & recall are as respective"
},
{
"code": null,
"e": 14979,
"s": 14961,
"text": "TP: True Positive"
},
{
"code": null,
"e": 14999,
"s": 14979,
"text": "FP : False Positive"
},
{
"code": null,
"e": 15017,
"s": 14999,
"text": "TN: True Negative"
},
{
"code": null,
"e": 15036,
"s": 15017,
"text": "FN: False Negative"
},
{
"code": null,
"e": 15053,
"s": 15036,
"text": "Confusion Matrix"
},
{
"code": null,
"e": 15172,
"s": 15053,
"text": "Confusion Matrix is a very good way to understand results like true positive, false positive, true negative and so on."
},
{
"code": null,
"e": 15406,
"s": 15172,
"text": "Sklearn documentation has provided a sample code of how to plot nice looking confusion matrix to visualize your result. You can check it out here, or you can find the code in the notebook that I am sharing at the end of the articles."
},
{
"code": null,
"e": 15438,
"s": 15406,
"text": "Precision: 87.82%Recall: 81.01%"
},
{
"code": null,
"e": 15581,
"s": 15438,
"text": "The recall of this model is rather low, it might not be doing a good enough job in discovering the spam email. How do we do better than this ?"
},
{
"code": null,
"e": 15708,
"s": 15581,
"text": "In this article, I have showed you all the necessary steps needed in designing a spam detection algorithm. Just a brief recap:"
},
{
"code": null,
"e": 16016,
"s": 15708,
"text": "Explore and understand your dataVisualize the data at hand to gain a better intuition — Wordcloud, N-gram Bar ChartText Cleaning — Word Stemmer and Word LemmatizationFeature Extraction — Count Vectorizer, Tfidf Vectorizer, Word EmbeddingAlgorithm — Naive BayesScoring & Metrics — Accuracy, Precision, Recall"
},
{
"code": null,
"e": 16049,
"s": 16016,
"text": "Explore and understand your data"
},
{
"code": null,
"e": 16133,
"s": 16049,
"text": "Visualize the data at hand to gain a better intuition — Wordcloud, N-gram Bar Chart"
},
{
"code": null,
"e": 16185,
"s": 16133,
"text": "Text Cleaning — Word Stemmer and Word Lemmatization"
},
{
"code": null,
"e": 16257,
"s": 16185,
"text": "Feature Extraction — Count Vectorizer, Tfidf Vectorizer, Word Embedding"
},
{
"code": null,
"e": 16281,
"s": 16257,
"text": "Algorithm — Naive Bayes"
},
{
"code": null,
"e": 16329,
"s": 16281,
"text": "Scoring & Metrics — Accuracy, Precision, Recall"
},
{
"code": null,
"e": 16415,
"s": 16329,
"text": "Here concludes the first part of demonstration in designing spam detection algorithm."
},
{
"code": null,
"e": 16665,
"s": 16415,
"text": "There is a part 2 of this article! I am going to demonstrate how you could improve the performance in terms of accuracy, precision and recall of the model by using word embeddings and deep learning model. Read the article here if you are interested!"
},
{
"code": null,
"e": 16850,
"s": 16665,
"text": "You can clone the notebook from Github or run it from Colab directly. Leave any questions you have at the comments section below or post me questions on LinkedIn ! Thanks for reading 😀"
},
{
"code": null,
"e": 16867,
"s": 16850,
"text": "www.linkedin.com"
},
{
"code": null,
"e": 16967,
"s": 16867,
"text": "Ant Financial Singapore is expanding and actively hiring for Java Developers and QA engineer roles."
},
{
"code": null,
"e": 17165,
"s": 16967,
"text": "Our team aims to create payment product that provides the best payment experience for our customer. It is a good opportunity to learn how to build highly reliable payment system under huge traffic."
},
{
"code": null,
"e": 17270,
"s": 17165,
"text": "These roles currently extend to candidates that are based in Singapore , China or Southeast Asia region."
}
]
|
Type Hints in Python — Everything You Need To Know In 5 Minutes | by Dario Radečić | Towards Data Science | Python has always been a dynamically typed language, which means you don’t have to specify data types for variables and function return values. PEP 484 introduced type hints — a way to make Python feel statically typed.
While type hints can help structure your projects better, they are just that — hints — and by default do not affect the runtime. However, there is a way to force type checks on runtime, and we’ll explore it today, after dialing in on some basics.
The article is structured as follows:
Introduction to Type Hints
Annotating Variables
Exploring the typing Module
Forcing Type Checks on Runtime
Final Thoughts
If you’re coming from a language like C or Java, specifying data types won’t feel new. But if you’re learning Python, almost zero online courses and books mention data type specification to keep things simple.
As the code base gets larger, type hints can help to debug and prevent some dumb mistakes. If you’re using an IDE like PyCharm, you’ll get a warning message whenever you’ve used the wrong data type, provided you’re using type hints.
Let’s start simple by exploring a function without type hints:
def add_numbers(num1, num2): return num1 + num2print(add_numbers(3, 5)) # 8
Nothing groundbreaking here, but I’ve declared a function like this on purpose, as adding numbers should work will both integers and floats. We’ll discuss later how to specify both with type hints.
Here’s how you can add type hints to our function:
Add a colon and a data type after each function parameter
Add an arrow (->) and a data type after the function to specify the return data type
Code-wise, you should make these changes:
def add_numbers(num1: int, num2: int) -> int: return num1 + num2print(add_numbers(3, 5)) # 8
Neat. If you’re working with a function that shouldn’t return anything, you can specify None as the return type:
def add_numbers(num1: int, num2: int) -> None: print(num1 + num2)add_numbers(3, 5) # 8
Finally, you can also set a default value for the parameter, as shown below:
def add_numbers(num1: int, num2: int = 10) -> int: return num1 + num2print(add_numbers(3)) # 13
It’s all great, but what if we decide to call the add_numbers() function with floating-point numbers? Let’s check:
def add_numbers(num1: int, num2: int) -> int: return num1 + num2print(add_numbers(3.5, 5.11)) # 8.61
As you can see, everything still works. Adding type hints has no runtime effect by default. A static type checker like mypy can solve this “issue”, but more about it later.
Let’s explore variable annotations next.
Just like with functions, you can add type hints to variables. While helpful, type hints on variables can be a bit too verbose for simple functions and scripts.
Let’s take a look at an example:
a: int = 3b: float = 3.14c: str = 'abc'd: bool = Falsee: list = ['a', 'b', 'c']f: tuple = (1, 2, 3)g: dict = {'a': 1, 'b': 2}
It’s a lot of typing for declaring a couple of variables. Things can get even more verbose, but more on that later.
You can also include type annotations for variables inside a function:
def greet(name: str) -> str: base: str = 'Hello, ' return f'{base}{name}'greet('Bob') # Hello, Bob
Next, let’s explore the built-in typing module.
Python’s typing module can make data type annotations even more verbose. For example, you can specifically declare a list of strings, a tuple containing three integers, and a dictionary with strings as keys and integers as values.
Here’s how:
from typing import List, Tuple, Dicte: List[str] = ['a', 'b', 'c']f: Tuple[int, int, int] = (1, 2, 3)g: Dict[str, int] = {'a': 1, 'b': 2}
Let’s see how to include these to a function. It will take a list of floats and returns the same list with the items squared:
def squre(arr: List[float]) -> List[float]: return [x ** 2 for x in arr]print(squre([1, 2, 3])) # 1, 4, 9
As you can see, it also works with integers. We’ll address that in a bit. Before doing so, let’s explore one important concept in type hints — the Union operator. Basically, it allows you to specify multiple possible data types for variables and return values.
Here’s the implementation of the previous function:
from typing import Union
def square(arr: List[Union[int, float]]) -> List[Union[int, float]]: return [x ** 2 for x in arr]print(squre([1, 2, 3])) # 1, 4, 9
The function can now both accept and return a list of integers or floats, warning-free.
Finally, let’s explore how to force type checks on runtime.
You can force type checks on runtime with mypy (documentation). Before doing so, install it with either pip or conda:
pip install mypyconda install mypy
Next, let’s make a Python file. I’ve named mine type_hints.py:
def square(number: int) -> int: return number ** 2if __name__ == '__main__': print(square(3)) print(square(3.14))
The function accepts the integer and squares it, at least according to type hints. Upon execution, the function is evaluated both with an integer and a float. Here’s what happens when using the default Python interpreter:
And now with mypy:
As you can see, mypy works as advertised, so feel free to use it when required.
Let’s wrap things up next.
Type hints in Python can be both a blessing and a curse. On the one hand, they help in code organization and debugging, but on the other can make the code stupidly verbose.
To compromise, I’m using type hints for function declaration — both parameter types and return values — but I generally avoid them for anything else, such as variables. In the end, Python should be simple to write.
What are your thoughts on type hints? Let me know in the comment section below.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Top 5 Books to Learn Data Science in 2021
How to Schedule Python Scripts With Cron — The Only Guide You’ll Ever Need
Dask Delayed — How to Parallelize Your Python Code With Ease
How to Create PDF Reports With Python — The Essential Guide
Become a Data Scientist in 2021 Even Without a College Degree
Follow me on Medium for more stories like this
Sign up for my newsletter
Connect on LinkedIn | [
{
"code": null,
"e": 392,
"s": 172,
"text": "Python has always been a dynamically typed language, which means you don’t have to specify data types for variables and function return values. PEP 484 introduced type hints — a way to make Python feel statically typed."
},
{
"code": null,
"e": 639,
"s": 392,
"text": "While type hints can help structure your projects better, they are just that — hints — and by default do not affect the runtime. However, there is a way to force type checks on runtime, and we’ll explore it today, after dialing in on some basics."
},
{
"code": null,
"e": 677,
"s": 639,
"text": "The article is structured as follows:"
},
{
"code": null,
"e": 704,
"s": 677,
"text": "Introduction to Type Hints"
},
{
"code": null,
"e": 725,
"s": 704,
"text": "Annotating Variables"
},
{
"code": null,
"e": 753,
"s": 725,
"text": "Exploring the typing Module"
},
{
"code": null,
"e": 784,
"s": 753,
"text": "Forcing Type Checks on Runtime"
},
{
"code": null,
"e": 799,
"s": 784,
"text": "Final Thoughts"
},
{
"code": null,
"e": 1009,
"s": 799,
"text": "If you’re coming from a language like C or Java, specifying data types won’t feel new. But if you’re learning Python, almost zero online courses and books mention data type specification to keep things simple."
},
{
"code": null,
"e": 1242,
"s": 1009,
"text": "As the code base gets larger, type hints can help to debug and prevent some dumb mistakes. If you’re using an IDE like PyCharm, you’ll get a warning message whenever you’ve used the wrong data type, provided you’re using type hints."
},
{
"code": null,
"e": 1305,
"s": 1242,
"text": "Let’s start simple by exploring a function without type hints:"
},
{
"code": null,
"e": 1384,
"s": 1305,
"text": "def add_numbers(num1, num2): return num1 + num2print(add_numbers(3, 5)) # 8"
},
{
"code": null,
"e": 1582,
"s": 1384,
"text": "Nothing groundbreaking here, but I’ve declared a function like this on purpose, as adding numbers should work will both integers and floats. We’ll discuss later how to specify both with type hints."
},
{
"code": null,
"e": 1633,
"s": 1582,
"text": "Here’s how you can add type hints to our function:"
},
{
"code": null,
"e": 1691,
"s": 1633,
"text": "Add a colon and a data type after each function parameter"
},
{
"code": null,
"e": 1776,
"s": 1691,
"text": "Add an arrow (->) and a data type after the function to specify the return data type"
},
{
"code": null,
"e": 1818,
"s": 1776,
"text": "Code-wise, you should make these changes:"
},
{
"code": null,
"e": 1914,
"s": 1818,
"text": "def add_numbers(num1: int, num2: int) -> int: return num1 + num2print(add_numbers(3, 5)) # 8"
},
{
"code": null,
"e": 2027,
"s": 1914,
"text": "Neat. If you’re working with a function that shouldn’t return anything, you can specify None as the return type:"
},
{
"code": null,
"e": 2117,
"s": 2027,
"text": "def add_numbers(num1: int, num2: int) -> None: print(num1 + num2)add_numbers(3, 5) # 8"
},
{
"code": null,
"e": 2194,
"s": 2117,
"text": "Finally, you can also set a default value for the parameter, as shown below:"
},
{
"code": null,
"e": 2293,
"s": 2194,
"text": "def add_numbers(num1: int, num2: int = 10) -> int: return num1 + num2print(add_numbers(3)) # 13"
},
{
"code": null,
"e": 2408,
"s": 2293,
"text": "It’s all great, but what if we decide to call the add_numbers() function with floating-point numbers? Let’s check:"
},
{
"code": null,
"e": 2512,
"s": 2408,
"text": "def add_numbers(num1: int, num2: int) -> int: return num1 + num2print(add_numbers(3.5, 5.11)) # 8.61"
},
{
"code": null,
"e": 2685,
"s": 2512,
"text": "As you can see, everything still works. Adding type hints has no runtime effect by default. A static type checker like mypy can solve this “issue”, but more about it later."
},
{
"code": null,
"e": 2726,
"s": 2685,
"text": "Let’s explore variable annotations next."
},
{
"code": null,
"e": 2887,
"s": 2726,
"text": "Just like with functions, you can add type hints to variables. While helpful, type hints on variables can be a bit too verbose for simple functions and scripts."
},
{
"code": null,
"e": 2920,
"s": 2887,
"text": "Let’s take a look at an example:"
},
{
"code": null,
"e": 3046,
"s": 2920,
"text": "a: int = 3b: float = 3.14c: str = 'abc'd: bool = Falsee: list = ['a', 'b', 'c']f: tuple = (1, 2, 3)g: dict = {'a': 1, 'b': 2}"
},
{
"code": null,
"e": 3162,
"s": 3046,
"text": "It’s a lot of typing for declaring a couple of variables. Things can get even more verbose, but more on that later."
},
{
"code": null,
"e": 3233,
"s": 3162,
"text": "You can also include type annotations for variables inside a function:"
},
{
"code": null,
"e": 3339,
"s": 3233,
"text": "def greet(name: str) -> str: base: str = 'Hello, ' return f'{base}{name}'greet('Bob') # Hello, Bob"
},
{
"code": null,
"e": 3387,
"s": 3339,
"text": "Next, let’s explore the built-in typing module."
},
{
"code": null,
"e": 3618,
"s": 3387,
"text": "Python’s typing module can make data type annotations even more verbose. For example, you can specifically declare a list of strings, a tuple containing three integers, and a dictionary with strings as keys and integers as values."
},
{
"code": null,
"e": 3630,
"s": 3618,
"text": "Here’s how:"
},
{
"code": null,
"e": 3768,
"s": 3630,
"text": "from typing import List, Tuple, Dicte: List[str] = ['a', 'b', 'c']f: Tuple[int, int, int] = (1, 2, 3)g: Dict[str, int] = {'a': 1, 'b': 2}"
},
{
"code": null,
"e": 3894,
"s": 3768,
"text": "Let’s see how to include these to a function. It will take a list of floats and returns the same list with the items squared:"
},
{
"code": null,
"e": 4003,
"s": 3894,
"text": "def squre(arr: List[float]) -> List[float]: return [x ** 2 for x in arr]print(squre([1, 2, 3])) # 1, 4, 9"
},
{
"code": null,
"e": 4264,
"s": 4003,
"text": "As you can see, it also works with integers. We’ll address that in a bit. Before doing so, let’s explore one important concept in type hints — the Union operator. Basically, it allows you to specify multiple possible data types for variables and return values."
},
{
"code": null,
"e": 4316,
"s": 4264,
"text": "Here’s the implementation of the previous function:"
},
{
"code": null,
"e": 4341,
"s": 4316,
"text": "from typing import Union"
},
{
"code": null,
"e": 4475,
"s": 4341,
"text": "def square(arr: List[Union[int, float]]) -> List[Union[int, float]]: return [x ** 2 for x in arr]print(squre([1, 2, 3])) # 1, 4, 9"
},
{
"code": null,
"e": 4563,
"s": 4475,
"text": "The function can now both accept and return a list of integers or floats, warning-free."
},
{
"code": null,
"e": 4623,
"s": 4563,
"text": "Finally, let’s explore how to force type checks on runtime."
},
{
"code": null,
"e": 4741,
"s": 4623,
"text": "You can force type checks on runtime with mypy (documentation). Before doing so, install it with either pip or conda:"
},
{
"code": null,
"e": 4776,
"s": 4741,
"text": "pip install mypyconda install mypy"
},
{
"code": null,
"e": 4839,
"s": 4776,
"text": "Next, let’s make a Python file. I’ve named mine type_hints.py:"
},
{
"code": null,
"e": 4962,
"s": 4839,
"text": "def square(number: int) -> int: return number ** 2if __name__ == '__main__': print(square(3)) print(square(3.14))"
},
{
"code": null,
"e": 5184,
"s": 4962,
"text": "The function accepts the integer and squares it, at least according to type hints. Upon execution, the function is evaluated both with an integer and a float. Here’s what happens when using the default Python interpreter:"
},
{
"code": null,
"e": 5203,
"s": 5184,
"text": "And now with mypy:"
},
{
"code": null,
"e": 5283,
"s": 5203,
"text": "As you can see, mypy works as advertised, so feel free to use it when required."
},
{
"code": null,
"e": 5310,
"s": 5283,
"text": "Let’s wrap things up next."
},
{
"code": null,
"e": 5483,
"s": 5310,
"text": "Type hints in Python can be both a blessing and a curse. On the one hand, they help in code organization and debugging, but on the other can make the code stupidly verbose."
},
{
"code": null,
"e": 5698,
"s": 5483,
"text": "To compromise, I’m using type hints for function declaration — both parameter types and return values — but I generally avoid them for anything else, such as variables. In the end, Python should be simple to write."
},
{
"code": null,
"e": 5778,
"s": 5698,
"text": "What are your thoughts on type hints? Let me know in the comment section below."
},
{
"code": null,
"e": 5961,
"s": 5778,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 5972,
"s": 5961,
"text": "medium.com"
},
{
"code": null,
"e": 6014,
"s": 5972,
"text": "Top 5 Books to Learn Data Science in 2021"
},
{
"code": null,
"e": 6089,
"s": 6014,
"text": "How to Schedule Python Scripts With Cron — The Only Guide You’ll Ever Need"
},
{
"code": null,
"e": 6150,
"s": 6089,
"text": "Dask Delayed — How to Parallelize Your Python Code With Ease"
},
{
"code": null,
"e": 6210,
"s": 6150,
"text": "How to Create PDF Reports With Python — The Essential Guide"
},
{
"code": null,
"e": 6272,
"s": 6210,
"text": "Become a Data Scientist in 2021 Even Without a College Degree"
},
{
"code": null,
"e": 6319,
"s": 6272,
"text": "Follow me on Medium for more stories like this"
},
{
"code": null,
"e": 6345,
"s": 6319,
"text": "Sign up for my newsletter"
}
]
|
Word Embeddings: Intuition behind the vector representation of the words | by Oleg Borisov | Towards Data Science | In this article I would like to talk about how the words are commonly represented in Natural Language Processing (NLP), and what are the drawbacks of the “classical” word-vector representation, which word embeddings alleviate. In the practical section of the chapter, I am going to train a simple embedding on a character level (using a similar approach, one can use to train embeddings on a word level as well).
Some of the readers might be curious: why do we need to convert words into vectors? The main reason is that, if done properly, then by using the word-vector representations we can directly apply many well known Machine Learning algorithms in order to solve a problem that we have at hand, like sentiment analysis, text classification, text generation etc.
One of the first methods, that was used in order to convert words into vectors was using the idea of One-Hot Encoding. To describe it briefly: we would have a vector of the size equal to our vocabulary which is going to contain all zeros, except in one position where we are going to have 1.
This position where we have 1 is going to denote exactly what word we have. In the figure above as we can see, if machine produces a vector with 1 in the second position (0, 1, 0, 0, ...) then the machine is referring to a cat.
This is a very simple approach towards the words vectorisation but it has multiple drawbacks. First of all, our vector is very sparse since we have mostly zeros and only one non-zero value (in a real-world case scenario we would expect to deal with a vocabulary of 10000 words or more).
Secondly, one-hot vectors do not encode any similarity or dissimilarity information about the words, if we happen to consider some similarity metrics like: cosine similarity or Euclidean distance.
In the example of Cosine Similarity we focus on the angle between two vectors.
When the similarity score is 1 (or close) then the two vectors are the similar, when 0 then two vectors are independent, when -1 then two vectors point in the opposite direction. In case of word-vector representation, we would say that when the similarity score is -1 then the words are similar but have opposite meaning, for example words “hot” and “cold”.
As you can probably see, one-hot encoding does not help us to encode cosine of Euclidean similarity measure, because all of the vectors are independent. For example in the case of cosine similarity words: “science” and “scientist” which could be represented by vectors:
science = [0, 0, 0, 1, 0, ...]scientist = [0, 1, 0, 0, 0, ...]cos(theta) = 0
Since the cosine similarity is 0, we conclude that two words are independent, which we might argue should not be the case, as two words are very similar.
To address this issue, people came up with another method, which I will briefly describe below.
The idea here is to split any word by the shingles of the size k (shingles are similar to the N-Grams but on a character level). For example, consider words: “science” and “scientist”, and shingles of size 4.
k = 4Word: "science",Shingles: ['scie', 'cien', 'ienc', 'ence']Word: "scientist"Shingles: ['scie', 'cien', 'ient', 'enti', 'nits', 'itst']
Each of the shingles would also be encoded using one-hot representation. And to achieve word-vector representation we would need to sum up all the single-vectors that the word consists of. In our example it could be:
Science_Vector = [1, 0, 1, 0, 0 ,..., 0, 0, 0, 1, 0, 0, 1]Scientist_Vector = [1, 0, 1, 1, 0 ,..., 0, 1, 0, 0, 1, 1, 0]
As we can see, using this example, we have some shingles overlap between the two words “science” and “scientist”, in particular shingles ‘scie’, ‘cien’ are common for both words in this case. Because of that, the cosine similarity is not going to be zero every single time, which is a good thing!
Of course, this approach also has some pros and cons. In fact, many applications still use this method (with some smart modifications) as it allows us to perform analysis on the words even in the case when some misspellings occur (as you could imagine one-hot encoding would not be able to tackle this issue).
One of the downsides, however, is that some words might appear to be similar based on some metric, while in fact linguistically they should not have anything in common, for example words: “right” and “write”, will have most of the shingles in common, but have a completely different meanings.
The other inconvenience, once again is that the vectors we are going to work with are still very sparse. Surely, we have more ones in the vector, but unfortunately out vectors still mostly consist of zeros.
Because of that, researchers started to think of creating some kind of compact vector representations, which are also known as dense vectors.
The main goal here is to create a word-vector representation which is not going to be of a size of couple of thousands dimensions, but much smaller, on a scale of around 300 dimensions. For the dense representations we will not longer have vectors of ones and zeros only, but rather we will allow each dimension to have any floating value.
The best thing is that if trained and obtained properly, we will have similar words pointing in the similar direction and also make use of some similarity measures. Apart from that, each of the axis will be able to also represent some abstract information like presented on the image above. Those dense representations are also referred as the word embeddings.
The main question remains however, how can we achieve and train such word embedding? In other words, given some text, how can we map it into a hyperplane to achieve some similar representation to the above one?
One of the approaches, we can use would use a simple method of predicting the next token given the previous one. In order to perform this kind of task we can a use of simple Neural Network architecture. Let’s dig a little bit deeper in this task.
The general intuition is presented in the figure above. Given some tokenized text t_1, t_2, t_3. We will take token t_1, supply it into our embedding layer, which will transform the token into its vector representation v_1, then we will use this vector and Feed Forward (FF) Layer to predict what should be the next token. In this case we would like to be get token t_2, so we will use Backpropagation algorithm to update the weights of our system. Then, of course, we keep the same training procedure for all other tokens in our text.
Of course t_1 will be represented in one-hot encoding format, but in the output of embedding layer we will transform our large sparse vector to a much denser representation.
The main thing to note here is that, after the training we actually do not care at all about the FF layer, after the training we can simply drop and forget it. The most important for us is the Embedding layer, which has trained to convert our tokens into a lower dimensional vector space!
This is of course an oversimplified example, but I hope it makes sense why this architecture is useful. Now lets shortly move to the practical part where I will implement this architecture.
In this implementation section, I am going to show how can we use the approach outlined above, in order to create character embeddings in 2-dimensional space. The reason is that for word embeddings we would have to use a much larger dataset to train on, and it would be impossible to get any sensible results using 2-dimensional embedding vectors.
As a training text I will use Frankenstein book which I have used in one of the previous stories (when I was talking about Language Modelling). The code and related material is available on my GitHub page.
As you know we have 26 letters in the english alphabet + 10 digits + 1 space character, therefore, we will be working with 37 characters in total, which is going to be our vocabulary for this task (I have removed any punctuation signs for simplicity).
Lets create our Neural Network, to do that I use PyTorch:
Before we even start training our neural network, let’s check what our embedding currently represents, of course the result is going to be random. By the way the “ * ” symbol in the figure denotes the space character, so that we can see it easily on the image.
Now, let’s train the model for 80 epochs.
And after that is done, we can visualise our character embeddings in the 2-D plane.
As we can see, the result is quite amazing, as we can observe that the numeric characters are clustered together, as well as the vowels (even though “o” ran further away). So it is still interesting that the Embedding layer that we have trained has managed to pick up some understanding of the characters relationship in the text.
Of course this is a very simplified example, which gives you a gist idea of how the embeddings are trained in the real world scenario. In some of the implementations the similar approach with a little improvement is used. The modification lies, in supplying more tokens to the neural network like t_{i–2}, t_{i–1}, t_{i+1}, t_{i+2}, with the goal of predicting t_i token. Such an architecture is called Continuous Bag of Words model.
The other idea which could be used, and which in fact if even more time efficient is Skip-Ngram model, which inverses the operation. Here we will supply to token t_i, and would want the model to output it’s neighbouring tokens t_{i–2}, t_{i–1}, t_{i+1}, t_{i+2}.
I am not going to much into details here, because on the basic conceptual level they are very similar to the model we have discussed and implemented in this article, but they are adding more context into the game which helps the embedding to learn better representations.
Are the word embeddings better than the sparse word-vector representations? Well, this depends on the application. In fact, dense word embeddings have no possibility of addressing misspelling issues, as misspellings of any word will most likely would be outside of our vocabulary.
In chat bot settings people some times use abbreviations or common phrases that might confuse the system, e.g. “lol”, “lemme”, “gimme”, “searchin”. Even differences between UK English and US english might cause confusion, e.g. “color” vs “colour”.
In research, it has been also found that the embedding vectors can magically understand that there are some relationships between the words like “a King to a Queen is a as a Man to a Woman”, as well as that if we are talking with respect to a Country-Capital hyperplane, then Spain is related to Madrid similarly as Italy is related to Rome.
While this is obviously fascinating, the important thing to look out for is that word embeddings might be biased! They might be biased on a gender, racial or some other basis. For example, if we happen to start exploring embedding space on the job plane, we might recover that “a businessman to a man is like, a babysitter to a woman”, which is incorrect and unethical thing to say. This issue arises from the data that was used to train the embedding, and if the text had some biases towards one of the genders or nationality or race, then the embedding might be learn this bias as well.
Thus depending on the application you might want to avoid using the word-embeddings to avoid discrimination against some of the groups.
Thank you very much for reading this article, stay tuned for more interesting NLP topics that will be discussed in the future stories! | [
{
"code": null,
"e": 585,
"s": 172,
"text": "In this article I would like to talk about how the words are commonly represented in Natural Language Processing (NLP), and what are the drawbacks of the “classical” word-vector representation, which word embeddings alleviate. In the practical section of the chapter, I am going to train a simple embedding on a character level (using a similar approach, one can use to train embeddings on a word level as well)."
},
{
"code": null,
"e": 941,
"s": 585,
"text": "Some of the readers might be curious: why do we need to convert words into vectors? The main reason is that, if done properly, then by using the word-vector representations we can directly apply many well known Machine Learning algorithms in order to solve a problem that we have at hand, like sentiment analysis, text classification, text generation etc."
},
{
"code": null,
"e": 1233,
"s": 941,
"text": "One of the first methods, that was used in order to convert words into vectors was using the idea of One-Hot Encoding. To describe it briefly: we would have a vector of the size equal to our vocabulary which is going to contain all zeros, except in one position where we are going to have 1."
},
{
"code": null,
"e": 1461,
"s": 1233,
"text": "This position where we have 1 is going to denote exactly what word we have. In the figure above as we can see, if machine produces a vector with 1 in the second position (0, 1, 0, 0, ...) then the machine is referring to a cat."
},
{
"code": null,
"e": 1748,
"s": 1461,
"text": "This is a very simple approach towards the words vectorisation but it has multiple drawbacks. First of all, our vector is very sparse since we have mostly zeros and only one non-zero value (in a real-world case scenario we would expect to deal with a vocabulary of 10000 words or more)."
},
{
"code": null,
"e": 1945,
"s": 1748,
"text": "Secondly, one-hot vectors do not encode any similarity or dissimilarity information about the words, if we happen to consider some similarity metrics like: cosine similarity or Euclidean distance."
},
{
"code": null,
"e": 2024,
"s": 1945,
"text": "In the example of Cosine Similarity we focus on the angle between two vectors."
},
{
"code": null,
"e": 2382,
"s": 2024,
"text": "When the similarity score is 1 (or close) then the two vectors are the similar, when 0 then two vectors are independent, when -1 then two vectors point in the opposite direction. In case of word-vector representation, we would say that when the similarity score is -1 then the words are similar but have opposite meaning, for example words “hot” and “cold”."
},
{
"code": null,
"e": 2652,
"s": 2382,
"text": "As you can probably see, one-hot encoding does not help us to encode cosine of Euclidean similarity measure, because all of the vectors are independent. For example in the case of cosine similarity words: “science” and “scientist” which could be represented by vectors:"
},
{
"code": null,
"e": 2731,
"s": 2652,
"text": "science = [0, 0, 0, 1, 0, ...]scientist = [0, 1, 0, 0, 0, ...]cos(theta) = 0"
},
{
"code": null,
"e": 2885,
"s": 2731,
"text": "Since the cosine similarity is 0, we conclude that two words are independent, which we might argue should not be the case, as two words are very similar."
},
{
"code": null,
"e": 2981,
"s": 2885,
"text": "To address this issue, people came up with another method, which I will briefly describe below."
},
{
"code": null,
"e": 3190,
"s": 2981,
"text": "The idea here is to split any word by the shingles of the size k (shingles are similar to the N-Grams but on a character level). For example, consider words: “science” and “scientist”, and shingles of size 4."
},
{
"code": null,
"e": 3329,
"s": 3190,
"text": "k = 4Word: \"science\",Shingles: ['scie', 'cien', 'ienc', 'ence']Word: \"scientist\"Shingles: ['scie', 'cien', 'ient', 'enti', 'nits', 'itst']"
},
{
"code": null,
"e": 3546,
"s": 3329,
"text": "Each of the shingles would also be encoded using one-hot representation. And to achieve word-vector representation we would need to sum up all the single-vectors that the word consists of. In our example it could be:"
},
{
"code": null,
"e": 3667,
"s": 3546,
"text": "Science_Vector = [1, 0, 1, 0, 0 ,..., 0, 0, 0, 1, 0, 0, 1]Scientist_Vector = [1, 0, 1, 1, 0 ,..., 0, 1, 0, 0, 1, 1, 0]"
},
{
"code": null,
"e": 3964,
"s": 3667,
"text": "As we can see, using this example, we have some shingles overlap between the two words “science” and “scientist”, in particular shingles ‘scie’, ‘cien’ are common for both words in this case. Because of that, the cosine similarity is not going to be zero every single time, which is a good thing!"
},
{
"code": null,
"e": 4274,
"s": 3964,
"text": "Of course, this approach also has some pros and cons. In fact, many applications still use this method (with some smart modifications) as it allows us to perform analysis on the words even in the case when some misspellings occur (as you could imagine one-hot encoding would not be able to tackle this issue)."
},
{
"code": null,
"e": 4567,
"s": 4274,
"text": "One of the downsides, however, is that some words might appear to be similar based on some metric, while in fact linguistically they should not have anything in common, for example words: “right” and “write”, will have most of the shingles in common, but have a completely different meanings."
},
{
"code": null,
"e": 4774,
"s": 4567,
"text": "The other inconvenience, once again is that the vectors we are going to work with are still very sparse. Surely, we have more ones in the vector, but unfortunately out vectors still mostly consist of zeros."
},
{
"code": null,
"e": 4916,
"s": 4774,
"text": "Because of that, researchers started to think of creating some kind of compact vector representations, which are also known as dense vectors."
},
{
"code": null,
"e": 5256,
"s": 4916,
"text": "The main goal here is to create a word-vector representation which is not going to be of a size of couple of thousands dimensions, but much smaller, on a scale of around 300 dimensions. For the dense representations we will not longer have vectors of ones and zeros only, but rather we will allow each dimension to have any floating value."
},
{
"code": null,
"e": 5617,
"s": 5256,
"text": "The best thing is that if trained and obtained properly, we will have similar words pointing in the similar direction and also make use of some similarity measures. Apart from that, each of the axis will be able to also represent some abstract information like presented on the image above. Those dense representations are also referred as the word embeddings."
},
{
"code": null,
"e": 5828,
"s": 5617,
"text": "The main question remains however, how can we achieve and train such word embedding? In other words, given some text, how can we map it into a hyperplane to achieve some similar representation to the above one?"
},
{
"code": null,
"e": 6075,
"s": 5828,
"text": "One of the approaches, we can use would use a simple method of predicting the next token given the previous one. In order to perform this kind of task we can a use of simple Neural Network architecture. Let’s dig a little bit deeper in this task."
},
{
"code": null,
"e": 6611,
"s": 6075,
"text": "The general intuition is presented in the figure above. Given some tokenized text t_1, t_2, t_3. We will take token t_1, supply it into our embedding layer, which will transform the token into its vector representation v_1, then we will use this vector and Feed Forward (FF) Layer to predict what should be the next token. In this case we would like to be get token t_2, so we will use Backpropagation algorithm to update the weights of our system. Then, of course, we keep the same training procedure for all other tokens in our text."
},
{
"code": null,
"e": 6785,
"s": 6611,
"text": "Of course t_1 will be represented in one-hot encoding format, but in the output of embedding layer we will transform our large sparse vector to a much denser representation."
},
{
"code": null,
"e": 7074,
"s": 6785,
"text": "The main thing to note here is that, after the training we actually do not care at all about the FF layer, after the training we can simply drop and forget it. The most important for us is the Embedding layer, which has trained to convert our tokens into a lower dimensional vector space!"
},
{
"code": null,
"e": 7264,
"s": 7074,
"text": "This is of course an oversimplified example, but I hope it makes sense why this architecture is useful. Now lets shortly move to the practical part where I will implement this architecture."
},
{
"code": null,
"e": 7612,
"s": 7264,
"text": "In this implementation section, I am going to show how can we use the approach outlined above, in order to create character embeddings in 2-dimensional space. The reason is that for word embeddings we would have to use a much larger dataset to train on, and it would be impossible to get any sensible results using 2-dimensional embedding vectors."
},
{
"code": null,
"e": 7818,
"s": 7612,
"text": "As a training text I will use Frankenstein book which I have used in one of the previous stories (when I was talking about Language Modelling). The code and related material is available on my GitHub page."
},
{
"code": null,
"e": 8070,
"s": 7818,
"text": "As you know we have 26 letters in the english alphabet + 10 digits + 1 space character, therefore, we will be working with 37 characters in total, which is going to be our vocabulary for this task (I have removed any punctuation signs for simplicity)."
},
{
"code": null,
"e": 8128,
"s": 8070,
"text": "Lets create our Neural Network, to do that I use PyTorch:"
},
{
"code": null,
"e": 8389,
"s": 8128,
"text": "Before we even start training our neural network, let’s check what our embedding currently represents, of course the result is going to be random. By the way the “ * ” symbol in the figure denotes the space character, so that we can see it easily on the image."
},
{
"code": null,
"e": 8431,
"s": 8389,
"text": "Now, let’s train the model for 80 epochs."
},
{
"code": null,
"e": 8515,
"s": 8431,
"text": "And after that is done, we can visualise our character embeddings in the 2-D plane."
},
{
"code": null,
"e": 8846,
"s": 8515,
"text": "As we can see, the result is quite amazing, as we can observe that the numeric characters are clustered together, as well as the vowels (even though “o” ran further away). So it is still interesting that the Embedding layer that we have trained has managed to pick up some understanding of the characters relationship in the text."
},
{
"code": null,
"e": 9280,
"s": 8846,
"text": "Of course this is a very simplified example, which gives you a gist idea of how the embeddings are trained in the real world scenario. In some of the implementations the similar approach with a little improvement is used. The modification lies, in supplying more tokens to the neural network like t_{i–2}, t_{i–1}, t_{i+1}, t_{i+2}, with the goal of predicting t_i token. Such an architecture is called Continuous Bag of Words model."
},
{
"code": null,
"e": 9543,
"s": 9280,
"text": "The other idea which could be used, and which in fact if even more time efficient is Skip-Ngram model, which inverses the operation. Here we will supply to token t_i, and would want the model to output it’s neighbouring tokens t_{i–2}, t_{i–1}, t_{i+1}, t_{i+2}."
},
{
"code": null,
"e": 9815,
"s": 9543,
"text": "I am not going to much into details here, because on the basic conceptual level they are very similar to the model we have discussed and implemented in this article, but they are adding more context into the game which helps the embedding to learn better representations."
},
{
"code": null,
"e": 10096,
"s": 9815,
"text": "Are the word embeddings better than the sparse word-vector representations? Well, this depends on the application. In fact, dense word embeddings have no possibility of addressing misspelling issues, as misspellings of any word will most likely would be outside of our vocabulary."
},
{
"code": null,
"e": 10344,
"s": 10096,
"text": "In chat bot settings people some times use abbreviations or common phrases that might confuse the system, e.g. “lol”, “lemme”, “gimme”, “searchin”. Even differences between UK English and US english might cause confusion, e.g. “color” vs “colour”."
},
{
"code": null,
"e": 10686,
"s": 10344,
"text": "In research, it has been also found that the embedding vectors can magically understand that there are some relationships between the words like “a King to a Queen is a as a Man to a Woman”, as well as that if we are talking with respect to a Country-Capital hyperplane, then Spain is related to Madrid similarly as Italy is related to Rome."
},
{
"code": null,
"e": 11275,
"s": 10686,
"text": "While this is obviously fascinating, the important thing to look out for is that word embeddings might be biased! They might be biased on a gender, racial or some other basis. For example, if we happen to start exploring embedding space on the job plane, we might recover that “a businessman to a man is like, a babysitter to a woman”, which is incorrect and unethical thing to say. This issue arises from the data that was used to train the embedding, and if the text had some biases towards one of the genders or nationality or race, then the embedding might be learn this bias as well."
},
{
"code": null,
"e": 11411,
"s": 11275,
"text": "Thus depending on the application you might want to avoid using the word-embeddings to avoid discrimination against some of the groups."
}
]
|
Java 11 - Quick Guide | Java 11 is the first LTS , Long Term Support feature release after Java 8. It followed the Java release cadence introduced Java 10 onwards and it was released on Sept 2018, just six months after Java 10 release.
Java 9 and Java 10 are non-LTS release. Java 11 release is a LTS release.
Following are the major new features which are introduced in Java 11.
JEP 321 − HTTP Client API standardized.
JEP 321 − HTTP Client API standardized.
JEP 330 − Launch Single-File Source-Code Programs without compilation
JEP 330 − Launch Single-File Source-Code Programs without compilation
JEP 323 − Local-Variable Syntax for Lambda Parameters
JEP 323 − Local-Variable Syntax for Lambda Parameters
JEP 181 − Nest-Based Access Control
JEP 181 − Nest-Based Access Control
JEP 331 − Low-Overhead Heap Profiling
JEP 331 − Low-Overhead Heap Profiling
JEP 318 − Epsilon, A No-Op Garbage Collector
JEP 318 − Epsilon, A No-Op Garbage Collector
JEP 333 − ZGC A Scalable Low-Latency Garbage Collector
JEP 333 − ZGC A Scalable Low-Latency Garbage Collector
Collection API Updates − New Collection.toArray(IntFunction) Default Method.
Collection API Updates − New Collection.toArray(IntFunction) Default Method.
String API Updates − New methods added like repeat(), isBlank(), strip() and lines().
String API Updates − New methods added like repeat(), isBlank(), strip() and lines().
Files API Updates − New methods added like readString(), and writeString().
Files API Updates − New methods added like readString(), and writeString().
Optional Updates − New method added, isEmpty().
Optional Updates − New method added, isEmpty().
Java 11 enhanced numerous APIs with new methods and options and removed deprecated APIs and options. We'll see these changes in next chapters.
We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.
Try the following example using Live Demo option available at the top right corner of the below sample code box −
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
}
}
For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning.
If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment.
Java SE is available for download for free. To download click here, please download a version compatible with your operating system.
Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin.
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin.
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH=%PATH%;C:\Program Files\java\jdk\bin
Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH=%PATH%;C:\Program Files\java\jdk\bin
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −
export PATH=/path/to/java:$PATH'
To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −
Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org.
Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org.
IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.
An enhanced HttpClient API was introduced in Java 9 as an experimental feature. With Java 11, now HttpClient is a standard. It is recommended to use instead of other HTTP Client APIs like Apache Http Client API. It is quite feature rich and now Java based applications can make HTTP requests without using any external dependency.
Following are the steps to use an HttpClient.
Create HttpClient instance using HttpClient.newBuilder() instance
Create HttpClient instance using HttpClient.newBuilder() instance
Create HttpRequest instance using HttpRequest.newBuilder() instance
Create HttpRequest instance using HttpRequest.newBuilder() instance
Make a request using httpClient.send() and get a response object.
Make a request using httpClient.send() and get a response object.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class APITester {
public static void main(String[] args) {
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
try {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.google.com"))
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println("Status code: " + response.statusCode());
System.out.println("Headers: " + response.headers().allValues("content-type"));
System.out.println("Body: " + response.body());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
It will print the following output.
Status code: 200
Headers: [text/html; charset=ISO-8859-1]
Body: <!doctype html>
...
</html>
Java 11 onwards, now a single java file can be tested easily without compiling as well. Consider the following example −
ApiTester.java
public class Tester {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
$ javac ApiTester.java
$ java Tester
Hello World!
$ java ApiTester.java
Hello World!
This new feature will help developer to quick test a functionality without need to compile before running a code.
Java 11 introduced multiple enhancements to String.
String.repeat(int) − Repeats a string given number of times. Returns the concatenated string.
String.repeat(int) − Repeats a string given number of times. Returns the concatenated string.
String.isBlank() − Checks if a string is empty or have white spaces only.
String.isBlank() − Checks if a string is empty or have white spaces only.
String.strip() − Removes the leading and trailing whitespaces.
String.strip() − Removes the leading and trailing whitespaces.
String.stripLeading() − Removes the leading whitespaces.
String.stripLeading() − Removes the leading whitespaces.
String.stripTrailing() − Removes the trailing whitespaces.
String.stripTrailing() − Removes the trailing whitespaces.
String.lines() − Return the stream of lines of multi-line string.
String.lines() − Return the stream of lines of multi-line string.
Consider the following example −
ApiTester.java
import java.util.ArrayList;
import java.util.List;
public class APITester {
public static void main(String[] args) {
String sample = " abc ";
System.out.println(sample.repeat(2)); // " abc abc "
System.out.println(sample.isBlank()); // false
System.out.println("".isBlank()); // true
System.out.println(" ".isBlank()); // true
System.out.println(sample.strip()); // "abc"
System.out.println(sample.stripLeading()); // "abc "
System.out.println(sample.stripTrailing()); // " abc"
sample = "This\nis\na\nmultiline\ntext.";
List<String> lines = new ArrayList<>();
sample.lines().forEach(line -> lines.add(line));
lines.forEach(line -> System.out.println(line));
}
}
abc abc
false
true
true
abc
abc
abc
This
is
a
multiline
text.
Java 11 introduced an easy way to convert a collection to an array.
nameArray = nameList.toArray(new String[nameList.size()]);
nameArray = nameList.toArray(String[]::new);
Consider the following example −
ApiTester.java
import java.util.Arrays;
import java.util.List;
public class APITester {
public static void main(String[] args) {
List<String> namesList = Arrays.asList("Joe", "Julie");
// Old way
String[] names = namesList.toArray(new String[namesList.size()]);
System.out.println(names.length);
// New way
names = namesList.toArray(String[]::new);
System.out.println(names.length);
}
}
2
2
Java 11 introduced an easy way to read and write files by providing new overloaded methods without writing much boiler plate code.
Consider the following example −
ApiTester.java
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class APITester {
public static void main(String[] args) {
try {
Path tempFilePath = Files.writeString(
Path.of(File.createTempFile("tempFile", ".tmp").toURI()),
"Welcome to TutorialsPoint",
Charset.defaultCharset(), StandardOpenOption.WRITE);
String fileContent = Files.readString(tempFilePath);
System.out.println(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Welcome to TutorialsPoint
Java 11 introduced new method to Optional class as isEmpty() to check if value is present. isEmpty() returns false if value is present otherwise true.
It can be used as an alternative of isPresent() method which often needs to negate to check if value is not present.
Consider the following example −
ApiTester.java
import java.util.Optional;
public class APITester {
public static void main(String[] args) {
String name = null;
System.out.println(!Optional.ofNullable(name).isPresent());
System.out.println(Optional.ofNullable(name).isEmpty());
name = "Joe";
System.out.println(!Optional.ofNullable(name).isPresent());
System.out.println(Optional.ofNullable(name).isEmpty());
}
}
true
true
false
false
Java 11 introduced new method to Predicate interface as not() to negate an existing predicate similar to negate method.
Consider the following example −
ApiTester.java
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class APITester {
public static void main(String[] args) {
List<String> tutorialsList = Arrays.asList("Java", "\n", "HTML", " ");
List<String> tutorials = tutorialsList.stream()
.filter(Predicate.not(String::isBlank))
.collect(Collectors.toList());
tutorials.forEach(tutorial -> System.out.println(tutorial));
}
}
Java
HTML
Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables.
(@NonNull var value1, @Nullable var value2) -> value1 + value2
Consider the following example −
ApiTester.java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@interface NonNull {}
public class APITester {
public static void main(String[] args) {
List<String> tutorialsList = Arrays.asList("Java", "HTML");
String tutorials = tutorialsList.stream()
.map((@NonNull var tutorial) -> tutorial.toUpperCase())
.collect(Collectors.joining(", "));
System.out.println(tutorials);
}
}
Java
HTML
There are certain limitations on using var in lambda expressions.
var parameters cannot be mixed with other parameters. Following will throw compilation error.
var parameters cannot be mixed with other parameters. Following will throw compilation error.
(var v1, v2) -> v1 + v2
var parameters cannot be mixed with other typed parameters. Following will throw compilation error.
var parameters cannot be mixed with other typed parameters. Following will throw compilation error.
(var v1, String v2) -> v1 + v2
var parameters can only be used with parenthesis. Following will throw compilation error.
var parameters can only be used with parenthesis. Following will throw compilation error.
var v1 -> v1.toLowerCase()
Java 11 introduced a concept of nested class where we can declare a class within a class. This nesting of classes allows to logically group the classes to be used in one place, making them more readable and maintainable. Nested class can be of four types −
Static nested classes
Static nested classes
Non-static nested classes
Non-static nested classes
Local classes
Local classes
Anonymous classes
Anonymous classes
Java 11 also provide the concept of nestmate to allow communication and verification of nested classes.
Consider the following example −
ApiTester.java
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class APITester {
public static void main(String[] args) {
boolean isNestMate = APITester.class.isNestmateOf(APITester.Inner.class);
boolean nestHost = APITester.Inner.class.getNestHost() == APITester.class;
System.out.println(isNestMate);
System.out.println(nestHost);
Set<String> nestedMembers = Arrays.stream(APITester.Inner.class.getNestMembers())
.map(Class::getName)
.collect(Collectors.toSet());
System.out.println(nestedMembers);
}
public class Inner{}
}
true
true
[APITester$Inner, APITester]
Java 11 has removed selected deprecated APIs. Following is the list of removed APIs.
Following deprecated Java EE and CORBA are removed from Java 11 release.
Java API for XML-Based Web Services (java.xml.ws)
Java API for XML-Based Web Services (java.xml.ws)
Java Architecture for XML Binding (java.xml.bind)
Java Architecture for XML Binding (java.xml.bind)
JavaBeans Activation Framework (java.activation)
JavaBeans Activation Framework (java.activation)
Common Annotations (java.xml.ws.annotation)
Common Annotations (java.xml.ws.annotation)
Common Object Request Broker Architecture (java.corba)
Common Object Request Broker Architecture (java.corba)
JavaTransaction API (java.transaction)
JavaTransaction API (java.transaction)
These APIs are available as standalone versions of third party site.
JDK Mission Control (JMC) is removed from standard JDK. It is available as standalone download.
JDK Mission Control (JMC) is removed from standard JDK. It is available as standalone download.
JavaFX is also removed from standard JDK. It is available as separate module to download.
JavaFX is also removed from standard JDK. It is available as separate module to download.
Nashorn JavaScript engine along with JJS tool is deprecated.
Nashorn JavaScript engine along with JJS tool is deprecated.
Pack200 compression scheme for JAR files is deprecated.
Pack200 compression scheme for JAR files is deprecated.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2285,
"s": 2073,
"text": "Java 11 is the first LTS , Long Term Support feature release after Java 8. It followed the Java release cadence introduced Java 10 onwards and it was released on Sept 2018, just six months after Java 10 release."
},
{
"code": null,
"e": 2359,
"s": 2285,
"text": "Java 9 and Java 10 are non-LTS release. Java 11 release is a LTS release."
},
{
"code": null,
"e": 2429,
"s": 2359,
"text": "Following are the major new features which are introduced in Java 11."
},
{
"code": null,
"e": 2469,
"s": 2429,
"text": "JEP 321 − HTTP Client API standardized."
},
{
"code": null,
"e": 2509,
"s": 2469,
"text": "JEP 321 − HTTP Client API standardized."
},
{
"code": null,
"e": 2579,
"s": 2509,
"text": "JEP 330 − Launch Single-File Source-Code Programs without compilation"
},
{
"code": null,
"e": 2649,
"s": 2579,
"text": "JEP 330 − Launch Single-File Source-Code Programs without compilation"
},
{
"code": null,
"e": 2703,
"s": 2649,
"text": "JEP 323 − Local-Variable Syntax for Lambda Parameters"
},
{
"code": null,
"e": 2757,
"s": 2703,
"text": "JEP 323 − Local-Variable Syntax for Lambda Parameters"
},
{
"code": null,
"e": 2793,
"s": 2757,
"text": "JEP 181 − Nest-Based Access Control"
},
{
"code": null,
"e": 2829,
"s": 2793,
"text": "JEP 181 − Nest-Based Access Control"
},
{
"code": null,
"e": 2867,
"s": 2829,
"text": "JEP 331 − Low-Overhead Heap Profiling"
},
{
"code": null,
"e": 2905,
"s": 2867,
"text": "JEP 331 − Low-Overhead Heap Profiling"
},
{
"code": null,
"e": 2950,
"s": 2905,
"text": "JEP 318 − Epsilon, A No-Op Garbage Collector"
},
{
"code": null,
"e": 2995,
"s": 2950,
"text": "JEP 318 − Epsilon, A No-Op Garbage Collector"
},
{
"code": null,
"e": 3050,
"s": 2995,
"text": "JEP 333 − ZGC A Scalable Low-Latency Garbage Collector"
},
{
"code": null,
"e": 3105,
"s": 3050,
"text": "JEP 333 − ZGC A Scalable Low-Latency Garbage Collector"
},
{
"code": null,
"e": 3182,
"s": 3105,
"text": "Collection API Updates − New Collection.toArray(IntFunction) Default Method."
},
{
"code": null,
"e": 3259,
"s": 3182,
"text": "Collection API Updates − New Collection.toArray(IntFunction) Default Method."
},
{
"code": null,
"e": 3345,
"s": 3259,
"text": "String API Updates − New methods added like repeat(), isBlank(), strip() and lines()."
},
{
"code": null,
"e": 3431,
"s": 3345,
"text": "String API Updates − New methods added like repeat(), isBlank(), strip() and lines()."
},
{
"code": null,
"e": 3507,
"s": 3431,
"text": "Files API Updates − New methods added like readString(), and writeString()."
},
{
"code": null,
"e": 3583,
"s": 3507,
"text": "Files API Updates − New methods added like readString(), and writeString()."
},
{
"code": null,
"e": 3631,
"s": 3583,
"text": "Optional Updates − New method added, isEmpty()."
},
{
"code": null,
"e": 3679,
"s": 3631,
"text": "Optional Updates − New method added, isEmpty()."
},
{
"code": null,
"e": 3822,
"s": 3679,
"text": "Java 11 enhanced numerous APIs with new methods and options and removed deprecated APIs and options. We'll see these changes in next chapters."
},
{
"code": null,
"e": 4115,
"s": 3822,
"text": "We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online."
},
{
"code": null,
"e": 4229,
"s": 4115,
"text": "Try the following example using Live Demo option available at the top right corner of the below sample code box −"
},
{
"code": null,
"e": 4355,
"s": 4229,
"text": "public class MyFirstJavaProgram {\n public static void main(String []args) {\n System.out.println(\"Hello World\");\n }\n}"
},
{
"code": null,
"e": 4578,
"s": 4355,
"text": "For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning."
},
{
"code": null,
"e": 4777,
"s": 4578,
"text": "If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment."
},
{
"code": null,
"e": 4910,
"s": 4777,
"text": "Java SE is available for download for free. To download click here, please download a version compatible with your operating system."
},
{
"code": null,
"e": 5138,
"s": 4910,
"text": "Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories."
},
{
"code": null,
"e": 5212,
"s": 5138,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 5266,
"s": 5212,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 5320,
"s": 5266,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 5390,
"s": 5320,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 5460,
"s": 5390,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 5706,
"s": 5460,
"text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way\nC:\\Windows\\System32;c:\\Program Files\\java\\jdk\\bin."
},
{
"code": null,
"e": 5901,
"s": 5706,
"text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way"
},
{
"code": null,
"e": 5952,
"s": 5901,
"text": "C:\\Windows\\System32;c:\\Program Files\\java\\jdk\\bin."
},
{
"code": null,
"e": 6026,
"s": 5952,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 6144,
"s": 6026,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −\nSET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin"
},
{
"code": null,
"e": 6216,
"s": 6144,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −"
},
{
"code": null,
"e": 6262,
"s": 6216,
"text": "SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin"
},
{
"code": null,
"e": 6425,
"s": 6262,
"text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this."
},
{
"code": null,
"e": 6536,
"s": 6425,
"text": "For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −"
},
{
"code": null,
"e": 6569,
"s": 6536,
"text": "export PATH=/path/to/java:$PATH'"
},
{
"code": null,
"e": 6733,
"s": 6569,
"text": "To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −"
},
{
"code": null,
"e": 6919,
"s": 6733,
"text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities."
},
{
"code": null,
"e": 7105,
"s": 6919,
"text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities."
},
{
"code": null,
"e": 7220,
"s": 7105,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html."
},
{
"code": null,
"e": 7335,
"s": 7220,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html."
},
{
"code": null,
"e": 7458,
"s": 7335,
"text": "Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org."
},
{
"code": null,
"e": 7581,
"s": 7458,
"text": "Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org."
},
{
"code": null,
"e": 7747,
"s": 7581,
"text": "IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc."
},
{
"code": null,
"e": 8078,
"s": 7747,
"text": "An enhanced HttpClient API was introduced in Java 9 as an experimental feature. With Java 11, now HttpClient is a standard. It is recommended to use instead of other HTTP Client APIs like Apache Http Client API. It is quite feature rich and now Java based applications can make HTTP requests without using any external dependency."
},
{
"code": null,
"e": 8124,
"s": 8078,
"text": "Following are the steps to use an HttpClient."
},
{
"code": null,
"e": 8190,
"s": 8124,
"text": "Create HttpClient instance using HttpClient.newBuilder() instance"
},
{
"code": null,
"e": 8256,
"s": 8190,
"text": "Create HttpClient instance using HttpClient.newBuilder() instance"
},
{
"code": null,
"e": 8324,
"s": 8256,
"text": "Create HttpRequest instance using HttpRequest.newBuilder() instance"
},
{
"code": null,
"e": 8392,
"s": 8324,
"text": "Create HttpRequest instance using HttpRequest.newBuilder() instance"
},
{
"code": null,
"e": 8458,
"s": 8392,
"text": "Make a request using httpClient.send() and get a response object."
},
{
"code": null,
"e": 8524,
"s": 8458,
"text": "Make a request using httpClient.send() and get a response object."
},
{
"code": null,
"e": 9606,
"s": 8524,
"text": "import java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class APITester {\n public static void main(String[] args) {\n HttpClient httpClient = HttpClient.newBuilder()\n .version(HttpClient.Version.HTTP_2)\n .connectTimeout(Duration.ofSeconds(10))\n .build(); \n try {\n HttpRequest request = HttpRequest.newBuilder()\n .GET()\n .uri(URI.create(\"https://www.google.com\"))\n .build(); \n HttpResponse<String> response = httpClient.send(request,\n HttpResponse.BodyHandlers.ofString()); \n\n System.out.println(\"Status code: \" + response.statusCode()); \n System.out.println(\"Headers: \" + response.headers().allValues(\"content-type\"));\n System.out.println(\"Body: \" + response.body());\n } catch (IOException | InterruptedException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 9642,
"s": 9606,
"text": "It will print the following output."
},
{
"code": null,
"e": 9735,
"s": 9642,
"text": "Status code: 200\nHeaders: [text/html; charset=ISO-8859-1]\nBody: <!doctype html>\n...\n</html>\n"
},
{
"code": null,
"e": 9856,
"s": 9735,
"text": "Java 11 onwards, now a single java file can be tested easily without compiling as well. Consider the following example −"
},
{
"code": null,
"e": 9871,
"s": 9856,
"text": "ApiTester.java"
},
{
"code": null,
"e": 9986,
"s": 9871,
"text": "public class Tester {\n public static void main(String[] args) {\n System.out.println(\"Hello World!\"); \n }\n}"
},
{
"code": null,
"e": 10037,
"s": 9986,
"text": "$ javac ApiTester.java\n$ java Tester\nHello World!\n"
},
{
"code": null,
"e": 10073,
"s": 10037,
"text": "$ java ApiTester.java\nHello World!\n"
},
{
"code": null,
"e": 10187,
"s": 10073,
"text": "This new feature will help developer to quick test a functionality without need to compile before running a code."
},
{
"code": null,
"e": 10239,
"s": 10187,
"text": "Java 11 introduced multiple enhancements to String."
},
{
"code": null,
"e": 10333,
"s": 10239,
"text": "String.repeat(int) − Repeats a string given number of times. Returns the concatenated string."
},
{
"code": null,
"e": 10427,
"s": 10333,
"text": "String.repeat(int) − Repeats a string given number of times. Returns the concatenated string."
},
{
"code": null,
"e": 10501,
"s": 10427,
"text": "String.isBlank() − Checks if a string is empty or have white spaces only."
},
{
"code": null,
"e": 10575,
"s": 10501,
"text": "String.isBlank() − Checks if a string is empty or have white spaces only."
},
{
"code": null,
"e": 10638,
"s": 10575,
"text": "String.strip() − Removes the leading and trailing whitespaces."
},
{
"code": null,
"e": 10701,
"s": 10638,
"text": "String.strip() − Removes the leading and trailing whitespaces."
},
{
"code": null,
"e": 10758,
"s": 10701,
"text": "String.stripLeading() − Removes the leading whitespaces."
},
{
"code": null,
"e": 10815,
"s": 10758,
"text": "String.stripLeading() − Removes the leading whitespaces."
},
{
"code": null,
"e": 10874,
"s": 10815,
"text": "String.stripTrailing() − Removes the trailing whitespaces."
},
{
"code": null,
"e": 10933,
"s": 10874,
"text": "String.stripTrailing() − Removes the trailing whitespaces."
},
{
"code": null,
"e": 10999,
"s": 10933,
"text": "String.lines() − Return the stream of lines of multi-line string."
},
{
"code": null,
"e": 11065,
"s": 10999,
"text": "String.lines() − Return the stream of lines of multi-line string."
},
{
"code": null,
"e": 11098,
"s": 11065,
"text": "Consider the following example −"
},
{
"code": null,
"e": 11113,
"s": 11098,
"text": "ApiTester.java"
},
{
"code": null,
"e": 11860,
"s": 11113,
"text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class APITester {\n public static void main(String[] args) {\n String sample = \" abc \";\n System.out.println(sample.repeat(2)); // \" abc abc \"\n System.out.println(sample.isBlank()); // false\n System.out.println(\"\".isBlank()); // true\n System.out.println(\" \".isBlank()); // true\n System.out.println(sample.strip()); // \"abc\"\n System.out.println(sample.stripLeading()); // \"abc \"\n System.out.println(sample.stripTrailing()); // \" abc\"\n sample = \"This\\nis\\na\\nmultiline\\ntext.\";\n\n List<String> lines = new ArrayList<>();\n\n sample.lines().forEach(line -> lines.add(line));\n lines.forEach(line -> System.out.println(line));\n }\n}"
},
{
"code": null,
"e": 11927,
"s": 11860,
"text": "abc abc \nfalse\ntrue\ntrue\nabc\nabc \n abc\nThis\nis\na\nmultiline\ntext.\n"
},
{
"code": null,
"e": 11995,
"s": 11927,
"text": "Java 11 introduced an easy way to convert a collection to an array."
},
{
"code": null,
"e": 12055,
"s": 11995,
"text": "nameArray = nameList.toArray(new String[nameList.size()]);\n"
},
{
"code": null,
"e": 12101,
"s": 12055,
"text": "nameArray = nameList.toArray(String[]::new);\n"
},
{
"code": null,
"e": 12134,
"s": 12101,
"text": "Consider the following example −"
},
{
"code": null,
"e": 12149,
"s": 12134,
"text": "ApiTester.java"
},
{
"code": null,
"e": 12572,
"s": 12149,
"text": "import java.util.Arrays;\nimport java.util.List;\n\npublic class APITester {\n public static void main(String[] args) {\t\t\n List<String> namesList = Arrays.asList(\"Joe\", \"Julie\");\n // Old way\n String[] names = namesList.toArray(new String[namesList.size()]);\n System.out.println(names.length);\n // New way\n names = namesList.toArray(String[]::new);\n System.out.println(names.length);\n }\n}"
},
{
"code": null,
"e": 12577,
"s": 12572,
"text": "2\n2\n"
},
{
"code": null,
"e": 12708,
"s": 12577,
"text": "Java 11 introduced an easy way to read and write files by providing new overloaded methods without writing much boiler plate code."
},
{
"code": null,
"e": 12741,
"s": 12708,
"text": "Consider the following example −"
},
{
"code": null,
"e": 12756,
"s": 12741,
"text": "ApiTester.java"
},
{
"code": null,
"e": 13426,
"s": 12756,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.StandardOpenOption;\n\npublic class APITester {\n public static void main(String[] args) {\t\t\n try {\n Path tempFilePath = Files.writeString(\n Path.of(File.createTempFile(\"tempFile\", \".tmp\").toURI()),\n \"Welcome to TutorialsPoint\", \n Charset.defaultCharset(), StandardOpenOption.WRITE);\n\n String fileContent = Files.readString(tempFilePath);\n\n System.out.println(fileContent);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 13453,
"s": 13426,
"text": "Welcome to TutorialsPoint\n"
},
{
"code": null,
"e": 13604,
"s": 13453,
"text": "Java 11 introduced new method to Optional class as isEmpty() to check if value is present. isEmpty() returns false if value is present otherwise true."
},
{
"code": null,
"e": 13721,
"s": 13604,
"text": "It can be used as an alternative of isPresent() method which often needs to negate to check if value is not present."
},
{
"code": null,
"e": 13754,
"s": 13721,
"text": "Consider the following example −"
},
{
"code": null,
"e": 13769,
"s": 13754,
"text": "ApiTester.java"
},
{
"code": null,
"e": 14181,
"s": 13769,
"text": "import java.util.Optional;\n\npublic class APITester {\n public static void main(String[] args) {\t\t\n String name = null;\n\n System.out.println(!Optional.ofNullable(name).isPresent());\n System.out.println(Optional.ofNullable(name).isEmpty());\n\n name = \"Joe\";\n System.out.println(!Optional.ofNullable(name).isPresent());\n System.out.println(Optional.ofNullable(name).isEmpty());\n }\n}"
},
{
"code": null,
"e": 14204,
"s": 14181,
"text": "true\ntrue\nfalse\nfalse\n"
},
{
"code": null,
"e": 14324,
"s": 14204,
"text": "Java 11 introduced new method to Predicate interface as not() to negate an existing predicate similar to negate method."
},
{
"code": null,
"e": 14357,
"s": 14324,
"text": "Consider the following example −"
},
{
"code": null,
"e": 14372,
"s": 14357,
"text": "ApiTester.java"
},
{
"code": null,
"e": 14861,
"s": 14372,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.function.Predicate;\nimport java.util.stream.Collectors;\n\npublic class APITester {\n public static void main(String[] args) {\t\t\n List<String> tutorialsList = Arrays.asList(\"Java\", \"\\n\", \"HTML\", \" \");\n\n List<String> tutorials = tutorialsList.stream()\n .filter(Predicate.not(String::isBlank))\n .collect(Collectors.toList());\n\n tutorials.forEach(tutorial -> System.out.println(tutorial));\n }\n}"
},
{
"code": null,
"e": 14872,
"s": 14861,
"text": "Java\nHTML\n"
},
{
"code": null,
"e": 14979,
"s": 14872,
"text": "Java 11 allows to use var in a lambda expression and it can be used to apply modifiers to local variables."
},
{
"code": null,
"e": 15043,
"s": 14979,
"text": "(@NonNull var value1, @Nullable var value2) -> value1 + value2\n"
},
{
"code": null,
"e": 15076,
"s": 15043,
"text": "Consider the following example −"
},
{
"code": null,
"e": 15091,
"s": 15076,
"text": "ApiTester.java"
},
{
"code": null,
"e": 15540,
"s": 15091,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\n@interface NonNull {}\n\npublic class APITester {\n public static void main(String[] args) {\t\t\n List<String> tutorialsList = Arrays.asList(\"Java\", \"HTML\");\n\n String tutorials = tutorialsList.stream()\n .map((@NonNull var tutorial) -> tutorial.toUpperCase())\n .collect(Collectors.joining(\", \"));\n\n System.out.println(tutorials);\n }\n}"
},
{
"code": null,
"e": 15551,
"s": 15540,
"text": "Java\nHTML\n"
},
{
"code": null,
"e": 15617,
"s": 15551,
"text": "There are certain limitations on using var in lambda expressions."
},
{
"code": null,
"e": 15711,
"s": 15617,
"text": "var parameters cannot be mixed with other parameters. Following will throw compilation error."
},
{
"code": null,
"e": 15805,
"s": 15711,
"text": "var parameters cannot be mixed with other parameters. Following will throw compilation error."
},
{
"code": null,
"e": 15830,
"s": 15805,
"text": "(var v1, v2) -> v1 + v2\n"
},
{
"code": null,
"e": 15930,
"s": 15830,
"text": "var parameters cannot be mixed with other typed parameters. Following will throw compilation error."
},
{
"code": null,
"e": 16030,
"s": 15930,
"text": "var parameters cannot be mixed with other typed parameters. Following will throw compilation error."
},
{
"code": null,
"e": 16062,
"s": 16030,
"text": "(var v1, String v2) -> v1 + v2\n"
},
{
"code": null,
"e": 16152,
"s": 16062,
"text": "var parameters can only be used with parenthesis. Following will throw compilation error."
},
{
"code": null,
"e": 16242,
"s": 16152,
"text": "var parameters can only be used with parenthesis. Following will throw compilation error."
},
{
"code": null,
"e": 16270,
"s": 16242,
"text": "var v1 -> v1.toLowerCase()\n"
},
{
"code": null,
"e": 16527,
"s": 16270,
"text": "Java 11 introduced a concept of nested class where we can declare a class within a class. This nesting of classes allows to logically group the classes to be used in one place, making them more readable and maintainable. Nested class can be of four types −"
},
{
"code": null,
"e": 16549,
"s": 16527,
"text": "Static nested classes"
},
{
"code": null,
"e": 16571,
"s": 16549,
"text": "Static nested classes"
},
{
"code": null,
"e": 16597,
"s": 16571,
"text": "Non-static nested classes"
},
{
"code": null,
"e": 16623,
"s": 16597,
"text": "Non-static nested classes"
},
{
"code": null,
"e": 16637,
"s": 16623,
"text": "Local classes"
},
{
"code": null,
"e": 16651,
"s": 16637,
"text": "Local classes"
},
{
"code": null,
"e": 16669,
"s": 16651,
"text": "Anonymous classes"
},
{
"code": null,
"e": 16687,
"s": 16669,
"text": "Anonymous classes"
},
{
"code": null,
"e": 16791,
"s": 16687,
"text": "Java 11 also provide the concept of nestmate to allow communication and verification of nested classes."
},
{
"code": null,
"e": 16824,
"s": 16791,
"text": "Consider the following example −"
},
{
"code": null,
"e": 16839,
"s": 16824,
"text": "ApiTester.java"
},
{
"code": null,
"e": 17460,
"s": 16839,
"text": "import java.util.Arrays;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\npublic class APITester {\n public static void main(String[] args) {\t\t\n boolean isNestMate = APITester.class.isNestmateOf(APITester.Inner.class);\n boolean nestHost = APITester.Inner.class.getNestHost() == APITester.class;\n\n System.out.println(isNestMate);\n System.out.println(nestHost);\n\n Set<String> nestedMembers = Arrays.stream(APITester.Inner.class.getNestMembers())\n .map(Class::getName)\n .collect(Collectors.toSet());\n System.out.println(nestedMembers);\n }\n public class Inner{}\n}"
},
{
"code": null,
"e": 17500,
"s": 17460,
"text": "true\ntrue\n[APITester$Inner, APITester]\n"
},
{
"code": null,
"e": 17585,
"s": 17500,
"text": "Java 11 has removed selected deprecated APIs. Following is the list of removed APIs."
},
{
"code": null,
"e": 17658,
"s": 17585,
"text": "Following deprecated Java EE and CORBA are removed from Java 11 release."
},
{
"code": null,
"e": 17708,
"s": 17658,
"text": "Java API for XML-Based Web Services (java.xml.ws)"
},
{
"code": null,
"e": 17758,
"s": 17708,
"text": "Java API for XML-Based Web Services (java.xml.ws)"
},
{
"code": null,
"e": 17808,
"s": 17758,
"text": "Java Architecture for XML Binding (java.xml.bind)"
},
{
"code": null,
"e": 17858,
"s": 17808,
"text": "Java Architecture for XML Binding (java.xml.bind)"
},
{
"code": null,
"e": 17907,
"s": 17858,
"text": "JavaBeans Activation Framework (java.activation)"
},
{
"code": null,
"e": 17956,
"s": 17907,
"text": "JavaBeans Activation Framework (java.activation)"
},
{
"code": null,
"e": 18000,
"s": 17956,
"text": "Common Annotations (java.xml.ws.annotation)"
},
{
"code": null,
"e": 18044,
"s": 18000,
"text": "Common Annotations (java.xml.ws.annotation)"
},
{
"code": null,
"e": 18099,
"s": 18044,
"text": "Common Object Request Broker Architecture (java.corba)"
},
{
"code": null,
"e": 18154,
"s": 18099,
"text": "Common Object Request Broker Architecture (java.corba)"
},
{
"code": null,
"e": 18193,
"s": 18154,
"text": "JavaTransaction API (java.transaction)"
},
{
"code": null,
"e": 18232,
"s": 18193,
"text": "JavaTransaction API (java.transaction)"
},
{
"code": null,
"e": 18301,
"s": 18232,
"text": "These APIs are available as standalone versions of third party site."
},
{
"code": null,
"e": 18397,
"s": 18301,
"text": "JDK Mission Control (JMC) is removed from standard JDK. It is available as standalone download."
},
{
"code": null,
"e": 18493,
"s": 18397,
"text": "JDK Mission Control (JMC) is removed from standard JDK. It is available as standalone download."
},
{
"code": null,
"e": 18583,
"s": 18493,
"text": "JavaFX is also removed from standard JDK. It is available as separate module to download."
},
{
"code": null,
"e": 18673,
"s": 18583,
"text": "JavaFX is also removed from standard JDK. It is available as separate module to download."
},
{
"code": null,
"e": 18734,
"s": 18673,
"text": "Nashorn JavaScript engine along with JJS tool is deprecated."
},
{
"code": null,
"e": 18795,
"s": 18734,
"text": "Nashorn JavaScript engine along with JJS tool is deprecated."
},
{
"code": null,
"e": 18851,
"s": 18795,
"text": "Pack200 compression scheme for JAR files is deprecated."
},
{
"code": null,
"e": 18907,
"s": 18851,
"text": "Pack200 compression scheme for JAR files is deprecated."
},
{
"code": null,
"e": 18940,
"s": 18907,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 18956,
"s": 18940,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 18989,
"s": 18956,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 19005,
"s": 18989,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 19040,
"s": 19005,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 19054,
"s": 19040,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 19088,
"s": 19054,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 19102,
"s": 19088,
"text": " Tushar Kale"
},
{
"code": null,
"e": 19139,
"s": 19102,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 19154,
"s": 19139,
"text": " Monica Mittal"
},
{
"code": null,
"e": 19187,
"s": 19154,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 19206,
"s": 19187,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 19213,
"s": 19206,
"text": " Print"
},
{
"code": null,
"e": 19224,
"s": 19213,
"text": " Add Notes"
}
]
|
Information Entropy. A layman’s introduction to information... | by A S | Towards Data Science | If you were to watch me cross the street, or watch me play Russian roulette, which one would be more exciting? The possibilities are the same- me living or dying, but we can all agree that the crossing of the street is a bit boring, and the Russian roulette... maybe too exciting. This is partially because we pretty much know what will happen when I cross the street, but we don’t really know what will happen in Russian roulette.
Another way of looking at this, is to say we gain less information observing the result of crossing the street than we do from Russian roulette. A formal way of putting that is to say the game of Russian roulette has more ‘entropy’ than crossing the street. Entropy is defined as ‘lack of order and predictability’, which seems like an apt description of the difference between the two scenarios.
Information is only useful when it can be stored and/or communicated. We have all learned this lesson the hard way when we have forgotten to save a document we were working on. In a digital form, information is stored in ‘bits’, or a series of numbers that can either be 0 or 1. The letters in your keyboard are stores in a ‘byte’, which is 8 bits, which allows for 28 =256 combinations. It is important to know that information storage and communication are almost the same thing, as you can think of storage as communication with a hard disk.
The mathematician Claude Shannon had the insight that the more predictable some information is, the less space is required to store it. Crossing the street is more predictable than Russian roulette, therefore you would need to store more information about the game of Russian roulette. Shannon had a mathematical formula for the ‘entropy’ of a probability distribution, which outputs the minimum number of bits required, on average, to store its outcomes.
Above is the formula for calculating the entropy of a probability distribution. It involves summing P*log(p) with base 2, for all the possible outcomes in a distribution. Here is a function to do this in Python:
import numpy as npdef entropy(dist): su=0 for p in dist: r= p/sum(dist) if r==0: su+=0 else: su+= -r*(np.log(r)) return su/np.log(2)
If we were to quantify the crossing the street example as having a 1 in a billion chance of death, and Russian roulette as 1 in 2, we’d get entropy([1, 999_999_999]) ≈ 3.1*10^-8 bits , and entropy([50,50])=1 bit, respectively. This means that if we repeated both experiments a trillion times, it would take at least 31,000 bits to store the results of crossing the street, and 1 trillion bits to store the results of Russian roulette, in line with our earlier intuition.
The English language has 26 letters, if you assume each letter has a probability of 1/26 of being next, the language has an entropy of 4.7 bits. However, some letters are more common than other letters, and some letters appear often together, so through clever ‘guessing’ (i.e. not assigning probabilities of 1/26), we can be much more efficient.
Random guessing on average takes us 13.5 guesses to get the correct letter. Let us say we are given the first letter of every word in this sentence:
H_ _ /A_ _ /Y_ _ /D_ _ _ _ / M_ /F_ _ _ _ _?
It would be very bad if it took us 13.5*16=216 guesses to fill in the 16 blanks. It would likely take us less than an average of two guesses per blank to figure out the sentence is “How are you doing my friend?”. So even if we exhaustively guessed the first letter and it took us 13.5 guesses, it would take us roughly 5.1 guesses/letter to fill in all the blanks, a huge improvement on random guessing.
Experiments by Shannon showed that English has an entropy between 0.6 and 1.3 bits. To put that into perspective, a 3 sided die has an entropy of 1.58 bits, and takes on average 2 guesses to predict. Also, note that the encoding system on your keyboard uses 8 bits per letter. So it could theoretically make all files in only the English language at least 6 times smaller!
Shannon’s work found uses in data storage, spaceship communication, and even communication over the internet. . Even if we are not working in any of those fields, ‘KL divergence’ is an idea derived from Shannon’s work, that is frequently used in data science. It tells you how good one distribution is at estimating another by comparing their entropies.
Communication and storage of information is what has made humans great, and Shannon’s work revolutionised the way we do so in the digital age. | [
{
"code": null,
"e": 603,
"s": 171,
"text": "If you were to watch me cross the street, or watch me play Russian roulette, which one would be more exciting? The possibilities are the same- me living or dying, but we can all agree that the crossing of the street is a bit boring, and the Russian roulette... maybe too exciting. This is partially because we pretty much know what will happen when I cross the street, but we don’t really know what will happen in Russian roulette."
},
{
"code": null,
"e": 1000,
"s": 603,
"text": "Another way of looking at this, is to say we gain less information observing the result of crossing the street than we do from Russian roulette. A formal way of putting that is to say the game of Russian roulette has more ‘entropy’ than crossing the street. Entropy is defined as ‘lack of order and predictability’, which seems like an apt description of the difference between the two scenarios."
},
{
"code": null,
"e": 1545,
"s": 1000,
"text": "Information is only useful when it can be stored and/or communicated. We have all learned this lesson the hard way when we have forgotten to save a document we were working on. In a digital form, information is stored in ‘bits’, or a series of numbers that can either be 0 or 1. The letters in your keyboard are stores in a ‘byte’, which is 8 bits, which allows for 28 =256 combinations. It is important to know that information storage and communication are almost the same thing, as you can think of storage as communication with a hard disk."
},
{
"code": null,
"e": 2001,
"s": 1545,
"text": "The mathematician Claude Shannon had the insight that the more predictable some information is, the less space is required to store it. Crossing the street is more predictable than Russian roulette, therefore you would need to store more information about the game of Russian roulette. Shannon had a mathematical formula for the ‘entropy’ of a probability distribution, which outputs the minimum number of bits required, on average, to store its outcomes."
},
{
"code": null,
"e": 2213,
"s": 2001,
"text": "Above is the formula for calculating the entropy of a probability distribution. It involves summing P*log(p) with base 2, for all the possible outcomes in a distribution. Here is a function to do this in Python:"
},
{
"code": null,
"e": 2398,
"s": 2213,
"text": "import numpy as npdef entropy(dist): su=0 for p in dist: r= p/sum(dist) if r==0: su+=0 else: su+= -r*(np.log(r)) return su/np.log(2)"
},
{
"code": null,
"e": 2869,
"s": 2398,
"text": "If we were to quantify the crossing the street example as having a 1 in a billion chance of death, and Russian roulette as 1 in 2, we’d get entropy([1, 999_999_999]) ≈ 3.1*10^-8 bits , and entropy([50,50])=1 bit, respectively. This means that if we repeated both experiments a trillion times, it would take at least 31,000 bits to store the results of crossing the street, and 1 trillion bits to store the results of Russian roulette, in line with our earlier intuition."
},
{
"code": null,
"e": 3216,
"s": 2869,
"text": "The English language has 26 letters, if you assume each letter has a probability of 1/26 of being next, the language has an entropy of 4.7 bits. However, some letters are more common than other letters, and some letters appear often together, so through clever ‘guessing’ (i.e. not assigning probabilities of 1/26), we can be much more efficient."
},
{
"code": null,
"e": 3365,
"s": 3216,
"text": "Random guessing on average takes us 13.5 guesses to get the correct letter. Let us say we are given the first letter of every word in this sentence:"
},
{
"code": null,
"e": 3410,
"s": 3365,
"text": "H_ _ /A_ _ /Y_ _ /D_ _ _ _ / M_ /F_ _ _ _ _?"
},
{
"code": null,
"e": 3814,
"s": 3410,
"text": "It would be very bad if it took us 13.5*16=216 guesses to fill in the 16 blanks. It would likely take us less than an average of two guesses per blank to figure out the sentence is “How are you doing my friend?”. So even if we exhaustively guessed the first letter and it took us 13.5 guesses, it would take us roughly 5.1 guesses/letter to fill in all the blanks, a huge improvement on random guessing."
},
{
"code": null,
"e": 4187,
"s": 3814,
"text": "Experiments by Shannon showed that English has an entropy between 0.6 and 1.3 bits. To put that into perspective, a 3 sided die has an entropy of 1.58 bits, and takes on average 2 guesses to predict. Also, note that the encoding system on your keyboard uses 8 bits per letter. So it could theoretically make all files in only the English language at least 6 times smaller!"
},
{
"code": null,
"e": 4541,
"s": 4187,
"text": "Shannon’s work found uses in data storage, spaceship communication, and even communication over the internet. . Even if we are not working in any of those fields, ‘KL divergence’ is an idea derived from Shannon’s work, that is frequently used in data science. It tells you how good one distribution is at estimating another by comparing their entropies."
}
]
|
Java Program to check if a particular key exists in TreeMap | To check if a particular key exists in TreeMap, use the containsKey() method.
Create a TreeMap first and add some elements −
TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"PHP");
m.put(2,"jQuery");
m.put(3,"JavaScript");
m.put(4,"Ruby");
m.put(5,"Java");
m.put(6,"AngularJS");
m.put(7,"ExpressJS");
Now, let’s say we need to check that key 5 exists or not. For that, set the containsKey() method like this −
m.containsKey(5)
The following is an example to check if a particular key exists in TreeMap −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"PHP");
m.put(2,"jQuery");
m.put(3,"JavaScript");
m.put(4,"Ruby");
m.put(5,"Java");
m.put(6,"AngularJS");
m.put(7,"ExpressJS");
System.out.println("TreeMap Elements...\n"+m);
System.out.println("Does key 5 exist in the TreeMap = "+m.containsKey(5));
}
}
TreeMap Elements...
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Does key 5 exist in the TreeMap = true | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "To check if a particular key exists in TreeMap, use the containsKey() method."
},
{
"code": null,
"e": 1187,
"s": 1140,
"text": "Create a TreeMap first and add some elements −"
},
{
"code": null,
"e": 1382,
"s": 1187,
"text": "TreeMap<Integer,String> m = new TreeMap<Integer,String>();\nm.put(1,\"PHP\");\nm.put(2,\"jQuery\");\nm.put(3,\"JavaScript\");\nm.put(4,\"Ruby\");\nm.put(5,\"Java\");\nm.put(6,\"AngularJS\");\nm.put(7,\"ExpressJS\");"
},
{
"code": null,
"e": 1491,
"s": 1382,
"text": "Now, let’s say we need to check that key 5 exists or not. For that, set the containsKey() method like this −"
},
{
"code": null,
"e": 1508,
"s": 1491,
"text": "m.containsKey(5)"
},
{
"code": null,
"e": 1585,
"s": 1508,
"text": "The following is an example to check if a particular key exists in TreeMap −"
},
{
"code": null,
"e": 1596,
"s": 1585,
"text": " Live Demo"
},
{
"code": null,
"e": 2064,
"s": 1596,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n TreeMap<Integer,String> m = new TreeMap<Integer,String>();\n m.put(1,\"PHP\");\n m.put(2,\"jQuery\");\n m.put(3,\"JavaScript\");\n m.put(4,\"Ruby\");\n m.put(5,\"Java\");\n m.put(6,\"AngularJS\");\n m.put(7,\"ExpressJS\");\n System.out.println(\"TreeMap Elements...\\n\"+m);\n System.out.println(\"Does key 5 exist in the TreeMap = \"+m.containsKey(5));\n }\n}"
},
{
"code": null,
"e": 2197,
"s": 2064,
"text": "TreeMap Elements...\n{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}\nDoes key 5 exist in the TreeMap = true"
}
]
|
How to create a custom unchecked exception in Java? | We can create the custom unchecked exception by extending the RuntimeException in Java.
Unchecked exceptions inherit from the Error class or the RuntimeException class. Many programmers feel that we cannot handle these exceptions in our programs because they represent the type of errors from which programs cannot be expected to recover while the program is running. When an unchecked exception is thrown, it is usually caused by misuse of code, passing a null or otherwise incorrect argument.
public class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
super(message);
}
}
The implementation of a custom unchecked exception is almost similar to a checked exception in Java. The only difference is that an unchecked exception has to extend RuntimeException instead of Exception.
public class CustomUncheckedException extends RuntimeException {
/*
* Required when we want to add a custom message when throwing the exception
* as throw new CustomUncheckedException(" Custom Unchecked Exception ");
*/
public CustomUncheckedException(String message) {
// calling super invokes the constructors of all super classes
// which helps to create the complete stacktrace.
super(message);
}
/*
* Required when we want to wrap the exception generated inside the catch block and rethrow it
* as catch(ArrayIndexOutOfBoundsException e) {
* throw new CustomUncheckedException(e);
* }
*/
public CustomUncheckedException(Throwable cause) {
// call appropriate parent constructor
super(cause);
}
/*
* Required when we want both the above
* as catch(ArrayIndexOutOfBoundsException e) {
* throw new CustomUncheckedException(e, "File not found");
* }
*/
public CustomUncheckedException(String message, Throwable throwable) {
// call appropriate parent constructor
super(message, throwable);
}
} | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "We can create the custom unchecked exception by extending the RuntimeException in Java."
},
{
"code": null,
"e": 1557,
"s": 1150,
"text": "Unchecked exceptions inherit from the Error class or the RuntimeException class. Many programmers feel that we cannot handle these exceptions in our programs because they represent the type of errors from which programs cannot be expected to recover while the program is running. When an unchecked exception is thrown, it is usually caused by misuse of code, passing a null or otherwise incorrect argument."
},
{
"code": null,
"e": 1690,
"s": 1557,
"text": "public class MyCustomException extends RuntimeException {\n public MyCustomException(String message) {\n super(message);\n }\n}"
},
{
"code": null,
"e": 1895,
"s": 1690,
"text": "The implementation of a custom unchecked exception is almost similar to a checked exception in Java. The only difference is that an unchecked exception has to extend RuntimeException instead of Exception."
},
{
"code": null,
"e": 3004,
"s": 1895,
"text": "public class CustomUncheckedException extends RuntimeException {\n /*\n * Required when we want to add a custom message when throwing the exception\n * as throw new CustomUncheckedException(\" Custom Unchecked Exception \");\n */\n public CustomUncheckedException(String message) {\n // calling super invokes the constructors of all super classes\n // which helps to create the complete stacktrace.\n super(message);\n }\n /*\n * Required when we want to wrap the exception generated inside the catch block and rethrow it\n * as catch(ArrayIndexOutOfBoundsException e) {\n * throw new CustomUncheckedException(e);\n * }\n */\n public CustomUncheckedException(Throwable cause) {\n // call appropriate parent constructor\n super(cause);\n }\n /*\n * Required when we want both the above\n * as catch(ArrayIndexOutOfBoundsException e) {\n * throw new CustomUncheckedException(e, \"File not found\");\n * }\n */\n public CustomUncheckedException(String message, Throwable throwable) {\n // call appropriate parent constructor\n super(message, throwable);\n }\n}"
}
]
|
Python String isalpha() Method | Python string method isalpha() checks whether the string consists of alphabetic characters only.
Following is the syntax for islpha() method −
str.isalpha()
NA
NA
This method returns true if all characters in the string are alphabetic and there is at least one character, false otherwise.
The following example shows the usage of isalpha() method.
#!/usr/bin/python
str = "this"; # No space & digit in this string
print str.isalpha()
str = "this is string example....wow!!!";
print str.isalpha()
When we run above program, it produces following result −
True
False
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": 2342,
"s": 2244,
"text": "Python string method isalpha() checks whether the string consists of alphabetic characters only."
},
{
"code": null,
"e": 2388,
"s": 2342,
"text": "Following is the syntax for islpha() method −"
},
{
"code": null,
"e": 2403,
"s": 2388,
"text": "str.isalpha()\n"
},
{
"code": null,
"e": 2406,
"s": 2403,
"text": "NA"
},
{
"code": null,
"e": 2409,
"s": 2406,
"text": "NA"
},
{
"code": null,
"e": 2535,
"s": 2409,
"text": "This method returns true if all characters in the string are alphabetic and there is at least one character, false otherwise."
},
{
"code": null,
"e": 2594,
"s": 2535,
"text": "The following example shows the usage of isalpha() method."
},
{
"code": null,
"e": 2745,
"s": 2594,
"text": "#!/usr/bin/python\n\nstr = \"this\"; # No space & digit in this string\nprint str.isalpha()\n\nstr = \"this is string example....wow!!!\";\nprint str.isalpha()"
},
{
"code": null,
"e": 2803,
"s": 2745,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2815,
"s": 2803,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 2852,
"s": 2815,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2868,
"s": 2852,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2901,
"s": 2868,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2920,
"s": 2901,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2955,
"s": 2920,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 2977,
"s": 2955,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3011,
"s": 2977,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3039,
"s": 3011,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3074,
"s": 3039,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3088,
"s": 3074,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3121,
"s": 3088,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3138,
"s": 3121,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3145,
"s": 3138,
"text": " Print"
},
{
"code": null,
"e": 3156,
"s": 3145,
"text": " Add Notes"
}
]
|
k-Nearest-Neighbor Classifier From Scratch in Python | by Yassine Hamdaoui | Towards Data Science | “Show me who your friends are and I’ll tell you who you are ?”
The concept of the k-nearest neighbor classifier can hardly be simpler described. This is an old saying, which can be found in many languages and many cultures. It’s also mentioned in other words in the Bible: “He who walks with wise men will be wise, but the companion of fools will suffer harm” (Proverbs 13:20 )
This means that the concept of the k-nearest neighbor classifier is part of our everyday life and judging: Imagine you meet a group of people, they are all very young, stylish and sportive. They talk about their friend Ben, who isn’t with them. So, what is your imagination of Ben? Right, you imagine him as being young, stylish and sportive as well.
If you learn that Ben lives in a neighborhood where people vote conservative and that the average income is above 200000 dollars a year? Both his neighbors make even more than 300,000 dollars per year? What do you think of Ben? Most probably, you do not consider him to be an underdog and you may suspect him to be a conservative as well?
The principle behind nearest neighbor classification consists in finding a predefined number, i.e. the ‘k’ — of training samples closest in distance to a new sample, which has to be classified. The label of the new sample will be defined from these neighbors. k-nearest neighbor classifiers have a fixed user defined constant for the number of neighbors which have to be determined. There are also radius-based neighbor learning algorithms, which have a varying number of neighbors based on the local density of points, all the samples inside of a fixed radius. The distance can, in general, be any metric measure: standard Euclidean distance is the most common choice. Neighbors-based methods are known as non-generalizing machine learning methods, since they simply “remember” all of its training data. Classification can be computed by a majority vote of the nearest neighbors of the unknown sample.
Now let’s get a little bit more mathematically:
The k-Nearest-Neighbor Classifier (k-NN) works directly on the learned samples, instead of creating rules compared to other classification methods.
Nearest Neighbor Algorithm:
Given a set of categories {c1,c2,...cn} also called classes, e.g. {“male”, “female”}. There is also a learnset LSLS consisting of labelled instances.
The task of classification consists in assigning a category or class to an arbitrary instance. If the instance oo is an element of LSLS, the label of the instance will be used.
Now, we will look at the case where oo is not in LSLS:
oo is compared with all instances of LSLS. A distance metric is used for comparison. We determine the kk closest neighbors of oo, i.e. the items with the smallest distances. kk is a user defined constant and a positive integer, which is usually small.
The most common class of LSLS will be assigned to the instance oo. If k = 1, then the object is simply assigned to the class of that single nearest neighbor.
The algorithm for the k-nearest neighbor classifier is among the simplest of all machine learning algorithms. k-NN is a type of instance-based learning, or lazy learning, where the function is only approximated locally and all the computations are performed, when we do the actual classification.
Before we actually start with writing a nearest neighbor classifier, we need to think about the data, i.e. the learnset. We will use the “iris” dataset provided by the datasets of the sklearn module.
The data set consists of 50 samples from each of three species of Iris
Iris setosa,
Iris virginica and
Iris versicolor.
Four features were measured from each sample: the length and the width of the sepals and petals, in centimetres.
import numpy as npfrom sklearn import datasetsiris = datasets.load_iris()iris_data = iris.datairis_labels = iris.targetprint(iris_data[0], iris_data[79], iris_data[100])print(iris_labels[0], iris_labels[79], iris_labels[100])
and this is the expected output :
[5.1 3.5 1.4 0.2] [5.7 2.6 3.5 1. ] [6.3 3.3 6. 2.5]0 1 2
We create a learnset from the sets above. We use permutation from np.random to split the data randomly.
np.random.seed(42)indices = np.random.permutation(len(iris_data))n_training_samples = 12learnset_data = iris_data[indices[:-n_training_samples]]learnset_labels = iris_labels[indices[:-n_training_samples]]testset_data = iris_data[indices[-n_training_samples:]]testset_labels = iris_labels[indices[-n_training_samples:]]print(learnset_data[:4], learnset_labels[:4])print(testset_data[:4], testset_labels[:4])
output :
[[6.1 2.8 4.7 1.2] [5.7 3.8 1.7 0.3] [7.7 2.6 6.9 2.3] [6. 2.9 4.5 1.5]] [1 0 2 1][[5.7 2.8 4.1 1.3] [6.5 3. 5.5 1.8] [6.3 2.3 4.4 1.3] [6.4 2.9 4.3 1.3]] [1 2 1 1]
The following code is only necessary to visualize the data of our learnset. Our data consists of four values per iris item, so we will reduce the data to three values by summing up the third and fourth value. This way, we are capable of depicting the data in 3-dimensional space:
# following line is only necessary, if you use ipython notebook!!!%matplotlib inline import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3DX = []for iclass in range(3): X.append([[], [], []]) for i in range(len(learnset_data)): if learnset_labels[i] == iclass: X[iclass][0].append(learnset_data[i][0]) X[iclass][1].append(learnset_data[i][1]) X[iclass][2].append(sum(learnset_data[i][2:]))colours = ("r", "g", "y")fig = plt.figure()ax = fig.add_subplot(111, projection='3d')for iclass in range(3): ax.scatter(X[iclass][0], X[iclass][1], X[iclass][2], c=colours[iclass])plt.show()
To determine the similarity between two instances, we need a distance function. In our example, the Euclidean distance is ideal:
def distance(instance1, instance2): # just in case, if the instances are lists or tuples: instance1 = np.array(instance1) instance2 = np.array(instance2) return np.linalg.norm(instance1 - instance2)print(distance([3, 5], [1, 1]))print(distance(learnset_data[3], learnset_data[44]))4.472135954999583.4190641994557516
The function ‘get_neighbors returns a list with ‘k’ neighbors, which are closest to the instance ‘test_instance’:
def get_neighbors(training_set, labels, test_instance, k, distance=distance): """ get_neighors calculates a list of the k nearest neighbors of an instance 'test_instance'. The list neighbors contains 3-tuples with (index, dist, label) where index is the index from the training_set, dist is the distance between the test_instance and the instance training_set[index] distance is a reference to a function used to calculate the distances """ distances = [] for index in range(len(training_set)): dist = distance(test_instance, training_set[index]) distances.append((training_set[index], dist, labels[index])) distances.sort(key=lambda x: x[1]) neighbors = distances[:k] return(neighbors)
We will test the function with our iris samples:
for i in range(5): neighbors = get_neighbors(learnset_data, learnset_labels, testset_data[i], 3, distance=distance) print(i, testset_data[i], testset_labels[i], neighbors)
output:
0 [5.7 2.8 4.1 1.3] 1 [(array([5.7, 2.9, 4.2, 1.3]), 0.14142135623730995, 1), (array([5.6, 2.7, 4.2, 1.3]), 0.17320508075688815, 1), (array([5.6, 3. , 4.1, 1.3]), 0.22360679774997935, 1)]1 [6.5 3. 5.5 1.8] 2 [(array([6.4, 3.1, 5.5, 1.8]), 0.1414213562373093, 2), (array([6.3, 2.9, 5.6, 1.8]), 0.24494897427831783, 2), (array([6.5, 3. , 5.2, 2. ]), 0.3605551275463988, 2)]2 [6.3 2.3 4.4 1.3] 1 [(array([6.2, 2.2, 4.5, 1.5]), 0.2645751311064586, 1), (array([6.3, 2.5, 4.9, 1.5]), 0.574456264653803, 1), (array([6. , 2.2, 4. , 1. ]), 0.5916079783099617, 1)]3 [6.4 2.9 4.3 1.3] 1 [(array([6.2, 2.9, 4.3, 1.3]), 0.20000000000000018, 1), (array([6.6, 3. , 4.4, 1.4]), 0.2645751311064587, 1), (array([6.6, 2.9, 4.6, 1.3]), 0.3605551275463984, 1)]4 [5.6 2.8 4.9 2. ] 2 [(array([5.8, 2.7, 5.1, 1.9]), 0.3162277660168375, 2), (array([5.8, 2.7, 5.1, 1.9]), 0.3162277660168375, 2), (array([5.7, 2.5, 5. , 2. ]), 0.33166247903553986, 2)]
We will write a vote function now. This function uses the class ‘Counter’ from collections to count the quantity of the classes inside of an instance list. This instance list will be the neighbors of course. The function ‘vote’ returns the most common class:
from collections import Counterdef vote(neighbors): class_counter = Counter() for neighbor in neighbors: class_counter[neighbor[2]] += 1 return class_counter.most_common(1)[0][0]
We will test ‘vote’ on our training samples:
for i in range(n_training_samples): neighbors = get_neighbors(learnset_data, learnset_labels, testset_data[i], 3, distance=distance) print("index: ", i, ", result of vote: ", vote(neighbors), ", label: ", testset_labels[i], ", data: ", testset_data[i])
...
index: 0 , result of vote: 1 , label: 1 , data: [5.7 2.8 4.1 1.3]index: 1 , result of vote: 2 , label: 2 , data: [6.5 3. 5.5 1.8]index: 2 , result of vote: 1 , label: 1 , data: [6.3 2.3 4.4 1.3]index: 3 , result of vote: 1 , label: 1 , data: [6.4 2.9 4.3 1.3]index: 4 , result of vote: 2 , label: 2 , data: [5.6 2.8 4.9 2. ]index: 5 , result of vote: 2 , label: 2 , data: [5.9 3. 5.1 1.8]index: 6 , result of vote: 0 , label: 0 , data: [5.4 3.4 1.7 0.2]index: 7 , result of vote: 1 , label: 1 , data: [6.1 2.8 4. 1.3]index: 8 , result of vote: 1 , label: 2 , data: [4.9 2.5 4.5 1.7]index: 9 , result of vote: 0 , label: 0 , data: [5.8 4. 1.2 0.2]index: 10 , result of vote: 1 , label: 1 , data: [5.8 2.6 4. 1.2]index: 11 , result of vote: 2 , label: 2 , data: [7.1 3. 5.9 2.1]
We can see that the predictions correspond to the labelled results, except in case of the item with the index 8.
‘vote_prob’ is a function like ‘vote’ but returns the class name and the probability for this class:
def vote_prob(neighbors): class_counter = Counter() for neighbor in neighbors: class_counter[neighbor[2]] += 1 labels, votes = zip(*class_counter.most_common()) winner = class_counter.most_common(1)[0][0] votes4winner = class_counter.most_common(1)[0][1] return(winner, votes4winner/sum(votes))
...
for i in range(n_training_samples): neighbors = get_neighbors(learnset_data, learnset_labels, testset_data[i], 5, distance=distance) print("index: ", i, ", vote_prob: ", vote_prob(neighbors), ", label: ", testset_labels[i], ", data: ", testset_data[i])
...
index: 0 , vote_prob: (1, 1.0) , label: 1 , data: [5.7 2.8 4.1 1.3]index: 1 , vote_prob: (2, 1.0) , label: 2 , data: [6.5 3. 5.5 1.8]index: 2 , vote_prob: (1, 1.0) , label: 1 , data: [6.3 2.3 4.4 1.3]index: 3 , vote_prob: (1, 1.0) , label: 1 , data: [6.4 2.9 4.3 1.3]index: 4 , vote_prob: (2, 1.0) , label: 2 , data: [5.6 2.8 4.9 2. ]index: 5 , vote_prob: (2, 0.8) , label: 2 , data: [5.9 3. 5.1 1.8]index: 6 , vote_prob: (0, 1.0) , label: 0 , data: [5.4 3.4 1.7 0.2]index: 7 , vote_prob: (1, 1.0) , label: 1 , data: [6.1 2.8 4. 1.3]index: 8 , vote_prob: (1, 1.0) , label: 2 , data: [4.9 2.5 4.5 1.7]index: 9 , vote_prob: (0, 1.0) , label: 0 , data: [5.8 4. 1.2 0.2]index: 10 , vote_prob: (1, 1.0) , label: 1 , data: [5.8 2.6 4. 1.2]index: 11 , vote_prob: (2, 1.0) , label: 2 , data: [7.1 3. 5.9 2.1]
In this tutorial, you discovered how to implement the k-Nearest Neighbors algorithm from scratch with Python.
Specifically, you learned:
How to code the k-Nearest Neighbors algorithm step-by-step.
How to evaluate k-Nearest Neighbors on a real dataset.
How to use k-Nearest Neighbors to make a prediction for new data.
Remember that you can find the fully working code in my github repository here.
Thanks for reading and I will be glad to discuss any questions or corrections you may have :) Find me on LinkedIn if you want to discuss Machine Learning or anything else. | [
{
"code": null,
"e": 235,
"s": 172,
"text": "“Show me who your friends are and I’ll tell you who you are ?”"
},
{
"code": null,
"e": 550,
"s": 235,
"text": "The concept of the k-nearest neighbor classifier can hardly be simpler described. This is an old saying, which can be found in many languages and many cultures. It’s also mentioned in other words in the Bible: “He who walks with wise men will be wise, but the companion of fools will suffer harm” (Proverbs 13:20 )"
},
{
"code": null,
"e": 901,
"s": 550,
"text": "This means that the concept of the k-nearest neighbor classifier is part of our everyday life and judging: Imagine you meet a group of people, they are all very young, stylish and sportive. They talk about their friend Ben, who isn’t with them. So, what is your imagination of Ben? Right, you imagine him as being young, stylish and sportive as well."
},
{
"code": null,
"e": 1240,
"s": 901,
"text": "If you learn that Ben lives in a neighborhood where people vote conservative and that the average income is above 200000 dollars a year? Both his neighbors make even more than 300,000 dollars per year? What do you think of Ben? Most probably, you do not consider him to be an underdog and you may suspect him to be a conservative as well?"
},
{
"code": null,
"e": 2143,
"s": 1240,
"text": "The principle behind nearest neighbor classification consists in finding a predefined number, i.e. the ‘k’ — of training samples closest in distance to a new sample, which has to be classified. The label of the new sample will be defined from these neighbors. k-nearest neighbor classifiers have a fixed user defined constant for the number of neighbors which have to be determined. There are also radius-based neighbor learning algorithms, which have a varying number of neighbors based on the local density of points, all the samples inside of a fixed radius. The distance can, in general, be any metric measure: standard Euclidean distance is the most common choice. Neighbors-based methods are known as non-generalizing machine learning methods, since they simply “remember” all of its training data. Classification can be computed by a majority vote of the nearest neighbors of the unknown sample."
},
{
"code": null,
"e": 2191,
"s": 2143,
"text": "Now let’s get a little bit more mathematically:"
},
{
"code": null,
"e": 2339,
"s": 2191,
"text": "The k-Nearest-Neighbor Classifier (k-NN) works directly on the learned samples, instead of creating rules compared to other classification methods."
},
{
"code": null,
"e": 2367,
"s": 2339,
"text": "Nearest Neighbor Algorithm:"
},
{
"code": null,
"e": 2517,
"s": 2367,
"text": "Given a set of categories {c1,c2,...cn} also called classes, e.g. {“male”, “female”}. There is also a learnset LSLS consisting of labelled instances."
},
{
"code": null,
"e": 2694,
"s": 2517,
"text": "The task of classification consists in assigning a category or class to an arbitrary instance. If the instance oo is an element of LSLS, the label of the instance will be used."
},
{
"code": null,
"e": 2749,
"s": 2694,
"text": "Now, we will look at the case where oo is not in LSLS:"
},
{
"code": null,
"e": 3001,
"s": 2749,
"text": "oo is compared with all instances of LSLS. A distance metric is used for comparison. We determine the kk closest neighbors of oo, i.e. the items with the smallest distances. kk is a user defined constant and a positive integer, which is usually small."
},
{
"code": null,
"e": 3159,
"s": 3001,
"text": "The most common class of LSLS will be assigned to the instance oo. If k = 1, then the object is simply assigned to the class of that single nearest neighbor."
},
{
"code": null,
"e": 3456,
"s": 3159,
"text": "The algorithm for the k-nearest neighbor classifier is among the simplest of all machine learning algorithms. k-NN is a type of instance-based learning, or lazy learning, where the function is only approximated locally and all the computations are performed, when we do the actual classification."
},
{
"code": null,
"e": 3656,
"s": 3456,
"text": "Before we actually start with writing a nearest neighbor classifier, we need to think about the data, i.e. the learnset. We will use the “iris” dataset provided by the datasets of the sklearn module."
},
{
"code": null,
"e": 3727,
"s": 3656,
"text": "The data set consists of 50 samples from each of three species of Iris"
},
{
"code": null,
"e": 3740,
"s": 3727,
"text": "Iris setosa,"
},
{
"code": null,
"e": 3759,
"s": 3740,
"text": "Iris virginica and"
},
{
"code": null,
"e": 3776,
"s": 3759,
"text": "Iris versicolor."
},
{
"code": null,
"e": 3889,
"s": 3776,
"text": "Four features were measured from each sample: the length and the width of the sepals and petals, in centimetres."
},
{
"code": null,
"e": 4115,
"s": 3889,
"text": "import numpy as npfrom sklearn import datasetsiris = datasets.load_iris()iris_data = iris.datairis_labels = iris.targetprint(iris_data[0], iris_data[79], iris_data[100])print(iris_labels[0], iris_labels[79], iris_labels[100])"
},
{
"code": null,
"e": 4149,
"s": 4115,
"text": "and this is the expected output :"
},
{
"code": null,
"e": 4208,
"s": 4149,
"text": "[5.1 3.5 1.4 0.2] [5.7 2.6 3.5 1. ] [6.3 3.3 6. 2.5]0 1 2"
},
{
"code": null,
"e": 4312,
"s": 4208,
"text": "We create a learnset from the sets above. We use permutation from np.random to split the data randomly."
},
{
"code": null,
"e": 4719,
"s": 4312,
"text": "np.random.seed(42)indices = np.random.permutation(len(iris_data))n_training_samples = 12learnset_data = iris_data[indices[:-n_training_samples]]learnset_labels = iris_labels[indices[:-n_training_samples]]testset_data = iris_data[indices[-n_training_samples:]]testset_labels = iris_labels[indices[-n_training_samples:]]print(learnset_data[:4], learnset_labels[:4])print(testset_data[:4], testset_labels[:4])"
},
{
"code": null,
"e": 4728,
"s": 4719,
"text": "output :"
},
{
"code": null,
"e": 4895,
"s": 4728,
"text": "[[6.1 2.8 4.7 1.2] [5.7 3.8 1.7 0.3] [7.7 2.6 6.9 2.3] [6. 2.9 4.5 1.5]] [1 0 2 1][[5.7 2.8 4.1 1.3] [6.5 3. 5.5 1.8] [6.3 2.3 4.4 1.3] [6.4 2.9 4.3 1.3]] [1 2 1 1]"
},
{
"code": null,
"e": 5175,
"s": 4895,
"text": "The following code is only necessary to visualize the data of our learnset. Our data consists of four values per iris item, so we will reduce the data to three values by summing up the third and fourth value. This way, we are capable of depicting the data in 3-dimensional space:"
},
{
"code": null,
"e": 5823,
"s": 5175,
"text": "# following line is only necessary, if you use ipython notebook!!!%matplotlib inline import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3DX = []for iclass in range(3): X.append([[], [], []]) for i in range(len(learnset_data)): if learnset_labels[i] == iclass: X[iclass][0].append(learnset_data[i][0]) X[iclass][1].append(learnset_data[i][1]) X[iclass][2].append(sum(learnset_data[i][2:]))colours = (\"r\", \"g\", \"y\")fig = plt.figure()ax = fig.add_subplot(111, projection='3d')for iclass in range(3): ax.scatter(X[iclass][0], X[iclass][1], X[iclass][2], c=colours[iclass])plt.show()"
},
{
"code": null,
"e": 5952,
"s": 5823,
"text": "To determine the similarity between two instances, we need a distance function. In our example, the Euclidean distance is ideal:"
},
{
"code": null,
"e": 6285,
"s": 5952,
"text": "def distance(instance1, instance2): # just in case, if the instances are lists or tuples: instance1 = np.array(instance1) instance2 = np.array(instance2) return np.linalg.norm(instance1 - instance2)print(distance([3, 5], [1, 1]))print(distance(learnset_data[3], learnset_data[44]))4.472135954999583.4190641994557516"
},
{
"code": null,
"e": 6399,
"s": 6285,
"text": "The function ‘get_neighbors returns a list with ‘k’ neighbors, which are closest to the instance ‘test_instance’:"
},
{
"code": null,
"e": 7254,
"s": 6399,
"text": "def get_neighbors(training_set, labels, test_instance, k, distance=distance): \"\"\" get_neighors calculates a list of the k nearest neighbors of an instance 'test_instance'. The list neighbors contains 3-tuples with (index, dist, label) where index is the index from the training_set, dist is the distance between the test_instance and the instance training_set[index] distance is a reference to a function used to calculate the distances \"\"\" distances = [] for index in range(len(training_set)): dist = distance(test_instance, training_set[index]) distances.append((training_set[index], dist, labels[index])) distances.sort(key=lambda x: x[1]) neighbors = distances[:k] return(neighbors)"
},
{
"code": null,
"e": 7303,
"s": 7254,
"text": "We will test the function with our iris samples:"
},
{
"code": null,
"e": 7631,
"s": 7303,
"text": "for i in range(5): neighbors = get_neighbors(learnset_data, learnset_labels, testset_data[i], 3, distance=distance) print(i, testset_data[i], testset_labels[i], neighbors)"
},
{
"code": null,
"e": 7639,
"s": 7631,
"text": "output:"
},
{
"code": null,
"e": 8565,
"s": 7639,
"text": "0 [5.7 2.8 4.1 1.3] 1 [(array([5.7, 2.9, 4.2, 1.3]), 0.14142135623730995, 1), (array([5.6, 2.7, 4.2, 1.3]), 0.17320508075688815, 1), (array([5.6, 3. , 4.1, 1.3]), 0.22360679774997935, 1)]1 [6.5 3. 5.5 1.8] 2 [(array([6.4, 3.1, 5.5, 1.8]), 0.1414213562373093, 2), (array([6.3, 2.9, 5.6, 1.8]), 0.24494897427831783, 2), (array([6.5, 3. , 5.2, 2. ]), 0.3605551275463988, 2)]2 [6.3 2.3 4.4 1.3] 1 [(array([6.2, 2.2, 4.5, 1.5]), 0.2645751311064586, 1), (array([6.3, 2.5, 4.9, 1.5]), 0.574456264653803, 1), (array([6. , 2.2, 4. , 1. ]), 0.5916079783099617, 1)]3 [6.4 2.9 4.3 1.3] 1 [(array([6.2, 2.9, 4.3, 1.3]), 0.20000000000000018, 1), (array([6.6, 3. , 4.4, 1.4]), 0.2645751311064587, 1), (array([6.6, 2.9, 4.6, 1.3]), 0.3605551275463984, 1)]4 [5.6 2.8 4.9 2. ] 2 [(array([5.8, 2.7, 5.1, 1.9]), 0.3162277660168375, 2), (array([5.8, 2.7, 5.1, 1.9]), 0.3162277660168375, 2), (array([5.7, 2.5, 5. , 2. ]), 0.33166247903553986, 2)]"
},
{
"code": null,
"e": 8824,
"s": 8565,
"text": "We will write a vote function now. This function uses the class ‘Counter’ from collections to count the quantity of the classes inside of an instance list. This instance list will be the neighbors of course. The function ‘vote’ returns the most common class:"
},
{
"code": null,
"e": 9019,
"s": 8824,
"text": "from collections import Counterdef vote(neighbors): class_counter = Counter() for neighbor in neighbors: class_counter[neighbor[2]] += 1 return class_counter.most_common(1)[0][0]"
},
{
"code": null,
"e": 9064,
"s": 9019,
"text": "We will test ‘vote’ on our training samples:"
},
{
"code": null,
"e": 9473,
"s": 9064,
"text": "for i in range(n_training_samples): neighbors = get_neighbors(learnset_data, learnset_labels, testset_data[i], 3, distance=distance) print(\"index: \", i, \", result of vote: \", vote(neighbors), \", label: \", testset_labels[i], \", data: \", testset_data[i])"
},
{
"code": null,
"e": 9477,
"s": 9473,
"text": "..."
},
{
"code": null,
"e": 10308,
"s": 9477,
"text": "index: 0 , result of vote: 1 , label: 1 , data: [5.7 2.8 4.1 1.3]index: 1 , result of vote: 2 , label: 2 , data: [6.5 3. 5.5 1.8]index: 2 , result of vote: 1 , label: 1 , data: [6.3 2.3 4.4 1.3]index: 3 , result of vote: 1 , label: 1 , data: [6.4 2.9 4.3 1.3]index: 4 , result of vote: 2 , label: 2 , data: [5.6 2.8 4.9 2. ]index: 5 , result of vote: 2 , label: 2 , data: [5.9 3. 5.1 1.8]index: 6 , result of vote: 0 , label: 0 , data: [5.4 3.4 1.7 0.2]index: 7 , result of vote: 1 , label: 1 , data: [6.1 2.8 4. 1.3]index: 8 , result of vote: 1 , label: 2 , data: [4.9 2.5 4.5 1.7]index: 9 , result of vote: 0 , label: 0 , data: [5.8 4. 1.2 0.2]index: 10 , result of vote: 1 , label: 1 , data: [5.8 2.6 4. 1.2]index: 11 , result of vote: 2 , label: 2 , data: [7.1 3. 5.9 2.1]"
},
{
"code": null,
"e": 10421,
"s": 10308,
"text": "We can see that the predictions correspond to the labelled results, except in case of the item with the index 8."
},
{
"code": null,
"e": 10522,
"s": 10421,
"text": "‘vote_prob’ is a function like ‘vote’ but returns the class name and the probability for this class:"
},
{
"code": null,
"e": 10842,
"s": 10522,
"text": "def vote_prob(neighbors): class_counter = Counter() for neighbor in neighbors: class_counter[neighbor[2]] += 1 labels, votes = zip(*class_counter.most_common()) winner = class_counter.most_common(1)[0][0] votes4winner = class_counter.most_common(1)[0][1] return(winner, votes4winner/sum(votes))"
},
{
"code": null,
"e": 10846,
"s": 10842,
"text": "..."
},
{
"code": null,
"e": 11255,
"s": 10846,
"text": "for i in range(n_training_samples): neighbors = get_neighbors(learnset_data, learnset_labels, testset_data[i], 5, distance=distance) print(\"index: \", i, \", vote_prob: \", vote_prob(neighbors), \", label: \", testset_labels[i], \", data: \", testset_data[i])"
},
{
"code": null,
"e": 11259,
"s": 11255,
"text": "..."
},
{
"code": null,
"e": 12114,
"s": 11259,
"text": "index: 0 , vote_prob: (1, 1.0) , label: 1 , data: [5.7 2.8 4.1 1.3]index: 1 , vote_prob: (2, 1.0) , label: 2 , data: [6.5 3. 5.5 1.8]index: 2 , vote_prob: (1, 1.0) , label: 1 , data: [6.3 2.3 4.4 1.3]index: 3 , vote_prob: (1, 1.0) , label: 1 , data: [6.4 2.9 4.3 1.3]index: 4 , vote_prob: (2, 1.0) , label: 2 , data: [5.6 2.8 4.9 2. ]index: 5 , vote_prob: (2, 0.8) , label: 2 , data: [5.9 3. 5.1 1.8]index: 6 , vote_prob: (0, 1.0) , label: 0 , data: [5.4 3.4 1.7 0.2]index: 7 , vote_prob: (1, 1.0) , label: 1 , data: [6.1 2.8 4. 1.3]index: 8 , vote_prob: (1, 1.0) , label: 2 , data: [4.9 2.5 4.5 1.7]index: 9 , vote_prob: (0, 1.0) , label: 0 , data: [5.8 4. 1.2 0.2]index: 10 , vote_prob: (1, 1.0) , label: 1 , data: [5.8 2.6 4. 1.2]index: 11 , vote_prob: (2, 1.0) , label: 2 , data: [7.1 3. 5.9 2.1]"
},
{
"code": null,
"e": 12224,
"s": 12114,
"text": "In this tutorial, you discovered how to implement the k-Nearest Neighbors algorithm from scratch with Python."
},
{
"code": null,
"e": 12251,
"s": 12224,
"text": "Specifically, you learned:"
},
{
"code": null,
"e": 12311,
"s": 12251,
"text": "How to code the k-Nearest Neighbors algorithm step-by-step."
},
{
"code": null,
"e": 12366,
"s": 12311,
"text": "How to evaluate k-Nearest Neighbors on a real dataset."
},
{
"code": null,
"e": 12432,
"s": 12366,
"text": "How to use k-Nearest Neighbors to make a prediction for new data."
},
{
"code": null,
"e": 12512,
"s": 12432,
"text": "Remember that you can find the fully working code in my github repository here."
}
]
|
Can we have a private method or private static method in an interface in Java 9?
| Yes, we can have private methods or private static methods in an interface in Java 9. We can use these methods to remove the code redundancy. Private methods can be useful or accessible only within that interface only. We can't access or inherit private methods from one interface to another interface or class.
interface <interface-name> {
private static void methodName() {
// some statements
}
private void methodName() {
// some statements
}
}
interface Java9Interface {
public abstract void method1();
public default void method2() {
method4();
method5();
System.out.println("Inside default method");
}
public static void method3() {
method5(); // static method inside other static method
System.out.println("Inside static method");
}
private void method4() { // private method
System.out.println("Inside private method");
}
private static void method5() { // private static method
System.out.println("Inside private static method");
}
}
public class PrivateStaticMethodTest implements Java9Interface {
@Override
public void method1() {
System.out.println("Inside abstract method");
}
public static void main(String args[]) {
Java9Interface instance = new PrivateStaticMethodTest();
instance.method1();
instance.method2();
Java9Interface.method3();
}
}
Inside abstract method
Inside private method
Inside private static method
Inside default method
Inside private static method
Inside static method | [
{
"code": null,
"e": 1374,
"s": 1062,
"text": "Yes, we can have private methods or private static methods in an interface in Java 9. We can use these methods to remove the code redundancy. Private methods can be useful or accessible only within that interface only. We can't access or inherit private methods from one interface to another interface or class."
},
{
"code": null,
"e": 1534,
"s": 1374,
"text": "interface <interface-name> {\n private static void methodName() {\n // some statements\n }\n private void methodName() {\n // some statements\n }\n}"
},
{
"code": null,
"e": 2469,
"s": 1534,
"text": "interface Java9Interface {\n public abstract void method1();\n public default void method2() {\n method4();\n method5();\n System.out.println(\"Inside default method\");\n }\n public static void method3() {\n method5(); // static method inside other static method\n System.out.println(\"Inside static method\");\n }\n private void method4() { // private method\n System.out.println(\"Inside private method\");\n }\n private static void method5() { // private static method\n System.out.println(\"Inside private static method\");\n }\n}\npublic class PrivateStaticMethodTest implements Java9Interface {\n @Override\n public void method1() {\n System.out.println(\"Inside abstract method\");\n }\n public static void main(String args[]) {\n Java9Interface instance = new PrivateStaticMethodTest();\n instance.method1();\n instance.method2();\n Java9Interface.method3();\n }\n}"
},
{
"code": null,
"e": 2615,
"s": 2469,
"text": "Inside abstract method\nInside private method\nInside private static method\nInside default method\nInside private static method\nInside static method"
}
]
|
Convert text to uppercase with CSS | To convert text to uppercase with CSS, use the text-transform property with value uppercase.
You can try to run the following code to convert text to uppercase:
<html>
<head>
</head>
<body>
<p>Normal Text</p>
<p style = "text-transform:uppercase;">
Normal Text! This will be in uppercase!
</p>
</body>
</html> | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To convert text to uppercase with CSS, use the text-transform property with value uppercase."
},
{
"code": null,
"e": 1223,
"s": 1155,
"text": "You can try to run the following code to convert text to uppercase:"
},
{
"code": null,
"e": 1411,
"s": 1223,
"text": "<html>\n <head>\n </head>\n <body>\n <p>Normal Text</p>\n <p style = \"text-transform:uppercase;\">\n Normal Text! This will be in uppercase!\n </p>\n </body>\n</html>"
}
]
|
Docker - HEALTHCHECK Instruction - GeeksforGeeks | 28 Oct, 2020
A HEATHCHECK instruction determines the state of a Docker Container. It determines whether the Container is running in a normal state or not. It performs health checks at regular intervals. The initial state is starting and after a successful checkup, the state becomes healthy. If the test remains unsuccessful, it turns into an unhealthy state.
Some options provided by the HEALTHCHECK instruction are –
–interval=: It determines the interval between 2 health check-ups. The default interval is the 30s.
–timeout=: If the HEALTHCHECK command exceeds the specified duration, it is categorized as a failure. The default duration is the 30s.
–retries=: If it reaches the specified number of retries, the state is considered to be unhealthy. The default number of retries is 3.
In this article, we will see practical examples of how to use the HEALTHCHECK command in your Dockerfile. We will create an Nginx Container and determine it states. Follow the below steps to Check the health of your dockerfile:
You can use the following template to create the Dockerfile.
FROM nginx:latest
HEALTHCHECK --interval=35s --timeout=4s CMD curl -f https://localhost/ || exit 1
EXPOSE 80
In the above Dockerfile, we pull the nginx base image and perform a HEALTHCHECK with the specified interval and timeout.
We can build the Docker Image using the build command.
sudo docker build -t healthcheck-demo .
Here, we will check whether the nginx.conf file exists or not. We will set the Command while running the Docker Container.
sudo docker run --name=healthcheck-demo -d
--health-cmd='stat /etc/nginx/nginx.conf
|| exit 1' healthcheck-demo
/* This line must be without the breaks, it's done for viewing purpose*/
You can use the inspect command to determine the state of the Container.
sudo docker inspect --format='' healthcheck-demo
You will get all the details regarding the Container along with the states during all the health checkups.
To conclude, in this article we discussed what is HEALTHCHECK instructions, what are its uses, the various options you can use along with it. We used the nginx container to demonstrate the same with practical examples.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
ML | Stochastic Gradient Descent (SGD)
Principal Component Analysis with Python
Fuzzy Logic | Introduction
How to create a REST API using Java Spring Boot
Classifying data using Support Vector Machines(SVMs) in Python
ML | Data Preprocessing in Python
Q-Learning in Python
Basics of API Testing Using Postman
Monolithic vs Microservices architecture | [
{
"code": null,
"e": 24148,
"s": 24120,
"text": "\n28 Oct, 2020"
},
{
"code": null,
"e": 24496,
"s": 24148,
"text": "A HEATHCHECK instruction determines the state of a Docker Container. It determines whether the Container is running in a normal state or not. It performs health checks at regular intervals. The initial state is starting and after a successful checkup, the state becomes healthy. If the test remains unsuccessful, it turns into an unhealthy state. "
},
{
"code": null,
"e": 24556,
"s": 24496,
"text": "Some options provided by the HEALTHCHECK instruction are – "
},
{
"code": null,
"e": 24656,
"s": 24556,
"text": "–interval=: It determines the interval between 2 health check-ups. The default interval is the 30s."
},
{
"code": null,
"e": 24791,
"s": 24656,
"text": "–timeout=: If the HEALTHCHECK command exceeds the specified duration, it is categorized as a failure. The default duration is the 30s."
},
{
"code": null,
"e": 24926,
"s": 24791,
"text": "–retries=: If it reaches the specified number of retries, the state is considered to be unhealthy. The default number of retries is 3."
},
{
"code": null,
"e": 25154,
"s": 24926,
"text": "In this article, we will see practical examples of how to use the HEALTHCHECK command in your Dockerfile. We will create an Nginx Container and determine it states. Follow the below steps to Check the health of your dockerfile:"
},
{
"code": null,
"e": 25215,
"s": 25154,
"text": "You can use the following template to create the Dockerfile."
},
{
"code": null,
"e": 25325,
"s": 25215,
"text": "FROM nginx:latest\nHEALTHCHECK --interval=35s --timeout=4s CMD curl -f https://localhost/ || exit 1\nEXPOSE 80\n"
},
{
"code": null,
"e": 25447,
"s": 25325,
"text": "In the above Dockerfile, we pull the nginx base image and perform a HEALTHCHECK with the specified interval and timeout. "
},
{
"code": null,
"e": 25502,
"s": 25447,
"text": "We can build the Docker Image using the build command."
},
{
"code": null,
"e": 25543,
"s": 25502,
"text": "sudo docker build -t healthcheck-demo .\n"
},
{
"code": null,
"e": 25666,
"s": 25543,
"text": "Here, we will check whether the nginx.conf file exists or not. We will set the Command while running the Docker Container."
},
{
"code": null,
"e": 25853,
"s": 25666,
"text": "sudo docker run --name=healthcheck-demo -d\n--health-cmd='stat /etc/nginx/nginx.conf \n|| exit 1' healthcheck-demo\n\n/* This line must be without the breaks, it's done for viewing purpose*/"
},
{
"code": null,
"e": 25926,
"s": 25853,
"text": "You can use the inspect command to determine the state of the Container."
},
{
"code": null,
"e": 25976,
"s": 25926,
"text": "sudo docker inspect --format='' healthcheck-demo\n"
},
{
"code": null,
"e": 26083,
"s": 25976,
"text": "You will get all the details regarding the Container along with the states during all the health checkups."
},
{
"code": null,
"e": 26302,
"s": 26083,
"text": "To conclude, in this article we discussed what is HEALTHCHECK instructions, what are its uses, the various options you can use along with it. We used the nginx container to demonstrate the same with practical examples."
},
{
"code": null,
"e": 26319,
"s": 26302,
"text": "Docker Container"
},
{
"code": null,
"e": 26325,
"s": 26319,
"text": "linux"
},
{
"code": null,
"e": 26351,
"s": 26325,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 26449,
"s": 26351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26458,
"s": 26449,
"text": "Comments"
},
{
"code": null,
"e": 26471,
"s": 26458,
"text": "Old Comments"
},
{
"code": null,
"e": 26515,
"s": 26471,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 26554,
"s": 26515,
"text": "ML | Stochastic Gradient Descent (SGD)"
},
{
"code": null,
"e": 26595,
"s": 26554,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 26622,
"s": 26595,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 26670,
"s": 26622,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 26733,
"s": 26670,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 26767,
"s": 26733,
"text": "ML | Data Preprocessing in Python"
},
{
"code": null,
"e": 26788,
"s": 26767,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 26824,
"s": 26788,
"text": "Basics of API Testing Using Postman"
}
]
|
Cordova - Quick Guide | Cordova is a platform for building hybrid mobile applications using HTML, CSS and JavaScript.
The official documentation gives us the definition of the Cordova −
"Apache Cordova is an open-source mobile development framework. It allows you to use standard web technologies such as HTML5, CSS3, and JavaScript for crossplatform development, avoiding each mobile platform native development language. Applications execute within wrappers targeted to each platform, and rely on standards-compliant API bindings to access each device's sensors, data, and network status."
Let us now understand the features of Cordova in brief.
This tool can be used for starting projects, building processes for different platforms, installing plugins and lot of other useful things that make the development process easier. You will learn how to use the Command Line Interface in the subsequent chapters.
Cordova offers a set of core components that every mobile application needs. These components will be used for creating base of the app so we can spend more time to implement our own logic.
Cordova offers API that will be used for implementing native mobile functions to our JavaScript app.
Cordova is licensed under the Apache License, Version 2.0. Apache and the Apache feather logos are trademarks of The Apache Software Foundation.
We will now discuss the advantages of Cordova.
Cordova offers one platform for building hybrid mobile apps so we can develop one app that will be used on different mobile platforms – IOS, Android, Windows Phone, Amazon-fireos, blackberry, Firefox OS, Ubuntu and tizien.
Cordova offers one platform for building hybrid mobile apps so we can develop one app that will be used on different mobile platforms – IOS, Android, Windows Phone, Amazon-fireos, blackberry, Firefox OS, Ubuntu and tizien.
It is faster to develop hybrid app then native app so Cordova can save on the development time.
It is faster to develop hybrid app then native app so Cordova can save on the development time.
Since we are using JavaScript when working with Cordova, we don't need to learn platform specific programming languages.
Since we are using JavaScript when working with Cordova, we don't need to learn platform specific programming languages.
There are many community add-ons that can be used with Cordova, these have several libraries and frameworks, which are optimized for working with it.
There are many community add-ons that can be used with Cordova, these have several libraries and frameworks, which are optimized for working with it.
Following are the limitations of Cordova.
Hybrid apps are slower than native ones so it is not optimal to use Cordova for large apps that require lots of data and functionality.
Hybrid apps are slower than native ones so it is not optimal to use Cordova for large apps that require lots of data and functionality.
Cross browser compatibility can create lots of issues. Most of the time we are building apps for different platforms so the testing and optimizing can be time consuming since we need to cover large number of devices and operating systems.
Cross browser compatibility can create lots of issues. Most of the time we are building apps for different platforms so the testing and optimizing can be time consuming since we need to cover large number of devices and operating systems.
Some plugins have compatibility issues with different devices and platforms. There are also some native APIs that are not yet supported by Cordova.
Some plugins have compatibility issues with different devices and platforms. There are also some native APIs that are not yet supported by Cordova.
In this chapter, we will understand the Environment Setup of Cordova. To begin with the setup, we need to first install a few components. The components are listed in the following table.
NodeJS and NPM
NodeJS is the platform needed for Cordova development. Check out our NodeJS Environment Setup for more details.
Android SDK
For Android platform, you need to have Android SDK installed on your machine. Check out Android Environment Setup for more details.
XCode
For iOS platform, you need to have xCode installed on your machine. Check out iOS Environment Setup for more details
Before we start, you need to know that we will use Windows command prompt in our tutorial.
Even if you don't use git, it should be installed since Cordova is using it for some background processes. You can download git here. After you install git, open your environment variable.
Right-Click on Computer
Properties
Advanced System settings
Environment Variables
System Variables
Edit
Copy the following at the end of the variable value field. This is default path of the git installation. If you installed it on a different path you should use that instead of our example code below.
;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd
Now you can type git in your command prompt to test if the installation is successful.
This step will download and install Cordova module globally. Open the command prompt and run the following −
C:\Users\username>npm install -g cordova
You can check the installed version by running −
C:\Users\username>cordova -v
This is everything you need to start developing the Cordova apps on Windows operating system. In our next tutorial, we will show you how to create first application.
We have understood how to install Cordova and set up the environment for it. Once everything is ready, we can create our first hybrid Cordova application.
Open the directory where you want the app to be installed in command prompt. We will create it on desktop.
C:\Users\username\Desktop>cordova
create CordovaProject io.cordova.hellocordova CordovaApp
CordovaProject is the directory name where the app is created.
CordovaProject is the directory name where the app is created.
io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible.
io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible.
CordovaApp is the title of your app.
CordovaApp is the title of your app.
You need to open your project directory in the command prompt. In our example, it is the CordovaProject. You should only choose platforms that you need. To be able to use the specified platform, you need to have installed the specific platform SDK. Since we are developing on windows, we can use the following platforms. We have already installed Android SDK, so we will only install android platform for this tutorial.
C:\Users\username\Desktop\CordovaProject>cordova platform add android
There are other platforms that can be used on Windows OS.
C:\Users\username\Desktop\CordovaProject>cordova platform add wp8
C:\Users\username\Desktop\CordovaProject>cordova platform add amazon-fireos
C:\Users\username\Desktop\CordovaProject>cordova platform add windows
C:\Users\username\Desktop\CordovaProject>cordova platform add blackberry10
C:\Users\username\Desktop\CordovaProject>cordova platform add firefoxos
If you are developing on Mac, you can use −
$ cordova platform add IOS
$ cordova platform add amazon-fireos
$ cordova platform add android
$ cordova platform add blackberry10
$ cordova platform add firefoxos
You can also remove platform from your project by using −
C:\Users\username\Desktop\CordovaProject>cordova platform rm android
In this step we will build the app for a specified platform so we can run it on mobile device or emulator.
C:\Users\username\Desktop\CordovaProject>cordova build android
Now we can run our app. If you are using the default emulator you should use −
C:\Users\username\Desktop\CordovaProject>cordova emulate android
If you want to use the external emulator or real device you should use −
C:\Users\username\Desktop\CordovaProject>cordova run android
NOTE − We will use the Genymotion android emulator since it is faster and more responsive than the default one. You can find the emulator here. You can also use real device for testing by enabling USB debugging from the options and connecting it to your computer via USB cable. For some devices, you will also need to install the USB driver.
Once we run the app, it will install it on the platform we specified. If everything is finished without errors, the output should show the default start screen of the app.
In our next tutorial, we will show you how to configure the Cordova Application.
The config.xml file is the place where we can change the configuration of the app. When we created our app in the last tutorial, we set reverse domain and name. The values can be changed in the config.xml file. When we create the app, the default config file will also be created.
The following table explains configuration elements in config.xml.
widget
The app reverse domain value that we specified when creating the app.
name
The name of the app that we specified when creating the app.
description
Description for the app.
author
Author of the app.
content
The app's starting page. It is placed inside the www directory.
plugin
The plugins that are currently installed.
access
Used to control access to external domains. The default origin value is set to * which means that access is allowed to any domain. This value will not allow some specific URLs to be opened to protect information.
allow-intent
Allows specific URLs to ask the app to open. For example, <allow-intent href = "tel:*" /> will allow tel: links to open the dialer.
platform
The platforms for building the app.
We can use storage API available for storing data on the client apps. This will help the usage of the app when the user is offline and it can also improve performance. Since this tutorial is for beginners, we will show you how to use local storage. In one of our later tutorials, we will show you the other plugins that can be used.
We will create four buttons in the index.html file. The buttons will be located inside the div class = "app" element.
<button id = "setLocalStorage">SET LOCAL STORAGE</button>
<button id = "showLocalStorage">SHOW LOCAL STORAGE</button>
<button id = "removeProjectFromLocalStorage">REMOVE PROJECT</button>
<button id = "getLocalStorageByKey">GET BY KEY</button>
It will produce the following screen −
Cordova security policy doesn't allow inline events so we will add event listeners inside index.js files. We will also assign window.localStorage to a localStorage variable that we will use later.
document.getElementById("setLocalStorage").addEventListener("click", setLocalStorage);
document.getElementById("showLocalStorage").addEventListener("click", showLocalStorage);
document.getElementById("removeProjectFromLocalStorage").addEventListener
("click", removeProjectFromLocalStorage);
document.getElementById("getLocalStorageByKey").addEventListener
("click", getLocalStorageByKey);
var localStorage = window.localStorage;
Now we need to create functions that will be called when the buttons are tapped. First function is used for adding data to local storage.
function setLocalStorage() {
localStorage.setItem("Name", "John");
localStorage.setItem("Job", "Developer");
localStorage.setItem("Project", "Cordova Project");
}
The next one will log the data we added to console.
function showLocalStorage() {
console.log(localStorage.getItem("Name"));
console.log(localStorage.getItem("Job"));
console.log(localStorage.getItem("Project"));
}
If we tap SET LOCAL STORAGE button, we will set three items to local storage. If we tap SHOW LOCAL STORAGE afterwards, the console will log items that we want.
Let us now create function that will delete the project from local storage.
function removeProjectFromLocalStorage() {
localStorage.removeItem("Project");
}
If we click the SHOW LOCAL STORAGE button after we deleted the project, the output will show null value for the project field.
We can also get the local storage elements by using the key() method which will take the index as an argument and return the element with corresponding index value.
function getLocalStorageByKey() {
console.log(localStorage.key(0));
}
Now when we tap the GET BY KEY button, the following output will be displayed.
When we use the key() method, the console will log the job instead of the name even though we passed argument 0 to retrieve the first object. This is because the local storage is storing data in alphabetical order.
The following table shows all the available local storage methods.
setItem(key, value)
Used for setting the item to local storage.
getItem(key)
Used for getting the item from local storage.
removeItem(key)
Used for removing the item from local storage.
key(index)
Used for getting the item by using the index of the item in local storage. This helps sort the items alphabetically.
length()
Used for retrieving the number of items that exists in local storage.
clear()
Used for removing all the key/value pairs from local storage.
There are various events that can be used in Cordova projects. The following table shows the available events.
deviceReady
This event is triggered once Cordova is fully loaded. This helps to ensure that no Cordova functions are called before everything is loaded.
pause
This event is triggered when the app is put into background.
resume
This event is triggered when the app is returned from background.
backbutton
This event is triggered when the back button is pressed.
menubutton
This event is triggered when the menu button is pressed.
searchbutton
This event is triggered when the Android search button is pressed.
startcallbutton
This event is triggered when the start call button is pressed.
endcallbutton
This event is triggered when the end call button is pressed.
volumedownbutton
This event is triggered when the volume down button is pressed.
volumeupbutton
This event is triggered when the volume up button is pressed.
All of the events are used almost the same way. We should always add event listeners in our js instead of the inline event calling since the Cordova Content Security Policy doesn't allow inline Javascript. If we try to call event inline, the following error will be displayed.
The right way of working with events is by using addEventListener. We will understand how to use the volumeupbutton event through an example.
document.addEventListener("volumeupbutton", callbackFunction, false);
function callbackFunction() {
alert('Volume Up Button is pressed!');
}
Once we press the volume up button, the screen will display the following alert.
We should use the Android back button for app functionalities like returning to the previous screen. To implement your own functionality, we should first disable the back button that is used to exit the App.
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(e) {
e.preventDefault();
alert('Back Button is Pressed!');
}
Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using the e.preventDefault() command.
You will usually want to use Android back button for some app functionality like returning to previous screen. To be able to implement your own functionality, you first need to disable exiting the app when the back button is pressed.
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(e) {
e.preventDefault();
alert('Back Button is Pressed!');
}
Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using e.preventDefault().
Cordova Plugman is a useful command line tool for installing and managing plugins. You should use plugman if your app needs to run on one specific platform. If you want to create a cross-platform app you should use cordova-cli which will modify plugins for different platforms.
Open the command prompt window and run the following code snippet to install plugman.
C:\Users\username\Desktop\CordovaProject>npm install -g plugman
To understand how to install the Cordova plugin using plugman, we will use the Camera plugin as an example.
C:\Users\username\Desktop\CordovaProject>plugman
install --platform android --project platforms\android
--plugin cordova-plugin-camera
plugman uninstall --platform android --project platforms\android
--plugin cordova-plugin-camera
We need to consider three parameters as shown above.
--platform − platform that we are using (android, ios, amazon-fireos, wp8, blackberry10).
--platform − platform that we are using (android, ios, amazon-fireos, wp8, blackberry10).
--project − path where the project is built. In our case, it is platforms\android directory.
--project − path where the project is built. In our case, it is platforms\android directory.
--plugin − the plugin that we want to install.
--plugin − the plugin that we want to install.
If you set valid parameters, the command prompt window should display the following output.
You can use the uninstall method in similar way.
C:\Users\username\Desktop\CordovaProject>plugman uninstall
--platform android --project platforms\android --plugin cordova-plugin-camera
The command prompt console will display the following output.
Plugman offers some additional methods that can be used. The methods are listed in the following table.
install
Used for installing Cordova plugins.
uninstall
Used for uninstalling Cordova plugins.
fetch
Used for copying Cordova plugin to specific location.
prepare
Used for updating configuration file to help JS module support.
adduser
Used for adding user account to the registry.
publish
Used for publishing plugin to the registry.
unpublish
Used for unpublishing plugin from the registry.
search
Used for searching the plugins in the registry.
config
Used for registry settings configuration.
create
Used for creating custom plugin.
platform
Used for adding or removing platform from the custom created plugin.
If you are stuck, you can always use the plugman -help command. The version can be checked by using plugman -v. To search for the plugin, you can use plugman search and finally you can change the plugin registry by using the plugman config set registry command.
Since Cordova is used for cross platform development, in our subsequent chapters we will use Cordova CLI instead of Plugman for installing plugins.
This Cordova plugin is used for monitoring device's battery status. The plugin will monitor every change that happens to device's battery.
To install this plugin, we need to open the command prompt window and run the following code.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-pluginbattery-status
When you open the index.js file, you will find the onDeviceReady function. This is where the event listener should be added.
window.addEventListener("batterystatus", onBatteryStatus, false);
We will create the onBatteryStatus callback function at the bottom of the index.js file.
function onBatteryStatus(info) {
alert("BATTERY STATUS: Level: " + info.level + " isPlugged: " + info.isPlugged);
}
When we run the app, an alert will be triggered. At the moment, the battery is 100% charged.
When the status is changed, a new alert will be displayed. The battery status shows that the battery is now charged 99%.
If we plug in the device to the charger, the new alert will show that the isPlugged value is changed to true.
This plugin offers two additional events besides the batterystatus event. These events can be used in the same way as the batterystatus event.
batterylow
The event is triggered when the battery charge percentage reaches low value. This value varies with different devices.
batterycritical
The event is triggered when the battery charge percentage reaches critical value. This value varies with different devices.
This plugin is used for taking photos or using files from the image gallery.
Run the following code in the command prompt window to install this plugin.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugincamera
Now, we will create the button for calling the camera and img where the image will be displayed once taken. This will be added to index.html inside the div class = "app" element.
<button id = "cameraTakePicture">TAKE PICTURE</button>
<img id = "myImage"></img>
The event listener is added inside the onDeviceReady function to ensure that Cordova is loaded before we start using it.
document.getElementById("cameraTakePicture").addEventListener
("click", cameraTakePicture);
We will create the cameraTakePicture function that is passed as a callback to our event listener. It will be fired when the button is tapped. Inside this function, we will call the navigator.camera global object provided by the plugin API. If taking picture is successful, the data will be sent to the onSuccess callback function, if not, the alert with error message will be shown. We will place this code at the bottom of index.js.
function cameraTakePicture() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
When we run the app and press the button, native camera will be triggered.
When we take and save picture, it will be displayed on screen.
The same procedure can be used for getting image from the local file system. The only difference is the function created in the last step. You can see that the sourceType optional parameter has been added.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugincamera
<button id = "cameraGetPicture">GET PICTURE</button>
document.getElementById("cameraGetPicture").addEventListener("click", cameraGetPicture);
function cameraGetPicture() {
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
});
function onSuccess(imageURL) {
var image = document.getElementById('myImage');
image.src = imageURL;
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
When we press the second button, the file system will open instead of the camera so we can choose the image that is to be displayed.
This plugin offers lots of optional parameters for customization.
quality
Quality of the image in the range of 0-100. Default is 50.
destinationType
DATA_URL or 0 Returns base64 encoded string.
FILE_URI or 1 Returns image file URI.
NATIVE_URI or 2 Returns image native URI.
sourceType
PHOTOLIBRARY or 0 Opens photo library.
CAMERA or 1 Opens native camera.
SAVEDPHOTOALBUM or 2 Opens saved photo album.
allowEdit
Allows image editing.
encodingType
JPEG or 0 Returns JPEG encoded image.
PNG or 1 Returns PNG encoded image.
targetWidth
Image scaling width in pixels.
targetHeight
Image scaling height in pixels.
mediaType
PICTURE or 0 Allows only picture selection.
VIDEO or 1 Allows only video selection.
ALLMEDIA or 2 Allows all media type selection.
correctOrientation
Used for correcting orientation of the image.
saveToPhotoAlbum
Used to save the image to the photo album.
popoverOptions
Used for setting popover location on IOS.
cameraDirection
FRONT or 0 Front camera.
BACK or 1 Back camera.
ALLMEDIA
This plugin is used for accessing the contacts database of the device. In this tutorial we will show you how to create, query and delete contacts.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugincontacts
The button will be used for calling the createContact function. We will place it in the div class = "app" in index.html file.
<button id = "createContact">ADD CONTACT</button>
<button id = "findContact">FIND CONTACT</button>
<button id = "deleteContact">DELETE CONTACT</button>
Open index.js and copy the following code snippet into the onDeviceReady function.
document.getElementById("createContact").addEventListener("click", createContact);
document.getElementById("findContact").addEventListener("click", findContact);
document.getElementById("deleteContact").addEventListener("click", deleteContact);
Now, we do not have any contacts stored on the device.
Our first callback function will call the navigator.contacts.create method where we can specify the new contact data. This will create a contact and assign it to the myContact variable but it will not be stored on the device. To store it, we need to call the save method and create success and error callback functions.
function createContact() {
var myContact = navigator.contacts.create({"displayName": "Test User"});
myContact.save(contactSuccess, contactError);
function contactSuccess() {
alert("Contact is saved!");
}
function contactError(message) {
alert('Failed because: ' + message);
}
}
When we click the ADD CONTACT button, new contact will be stored to the device contact list.
Our second callback function will query all contacts. We will use the navigator.contacts.find method. The options object has filter parameter which is used to specify the search filter. multiple = true is used since we want to return all contacts from device. The field key to search contacts by displayName since we used it when saving contact.
After the options are set, we are using find method to query contacts. The alert message will be triggered for every contact that is found.
function findContacts() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
fields = ["displayName"];
navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);
function contactfindSuccess(contacts) {
for (var i = 0; i < contacts.length; i++) {
alert("Display Name = " + contacts[i].displayName);
}
}
function contactfindError(message) {
alert('Failed because: ' + message);
}
}
When we press the FIND CONTACT button, one alert popup will be triggered since we have saved only one contact.
In this step, we will use the find method again but this time we will set different options. The options.filter is set to search that Test User which has to be deleted. After the contactfindSuccess callback function has returned the contact we want, we will delete it by using the remove method that requires its own success and error callbacks.
function deleteContact() {
var options = new ContactFindOptions();
options.filter = "Test User";
options.multiple = false;
fields = ["displayName"];
navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);
function contactfindSuccess(contacts) {
var contact = contacts[0];
contact.remove(contactRemoveSuccess, contactRemoveError);
function contactRemoveSuccess(contact) {
alert("Contact Deleted");
}
function contactRemoveError(message) {
alert('Failed because: ' + message);
}
}
function contactfindError(message) {
alert('Failed because: ' + message);
}
}
Now, we have only one contact stored on the device. We will manually add one more to show you the deleting process.
We will now click the DELETE CONTACT button to delete the Test User. If we check the contact list again, we will see that the Test User does not exist anymore.
This plugin is used for getting information about the user’s device.
To install this plugin, we need to run the following snippet in the command prompt.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device
We will be using this plugin the same way we used the other Cordova plugins. Let us add a button in the index.html file. This button will be used for getting information about the device.
<button id = "cordovaDevice">CORDOVA DEVICE</button>
Cordova plugins are available after the deviceready event so we will place the event listener inside the onDeviceReady function in index.js.
document.getElementById("cordovaDevice").addEventListener("click", cordovaDevice);
The following function will show how to use all possibilities the plugin provides. We will place it in index.js.
function cordovaDevice() {
alert("Cordova version: " + device.cordova + "\n" +
"Device model: " + device.model + "\n" +
"Device platform: " + device.platform + "\n" +
"Device UUID: " + device.uuid + "\n" +
"Device version: " + device.version);
}
When we click the CORDOVA DEVICE button, the alert will display the Cordova version, device model, platform, UUID and device version.
The Accelerometer plugin is also called the device-motion. It is used to track device motion in three dimensions.
We will install this plugin by using cordova-CLI. Type the following code in the command prompt window.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device-motion
In this step, we will add two buttons in the index.html file. One will be used for getting the current acceleration and the other will watch for the acceleration changes.
<button id = "getAcceleration">GET ACCELERATION</button>
<button id = "watchAcceleration">WATCH ACCELERATION</button>
Let us now add event listeners for our buttons to onDeviceReady function inside index.js.
document.getElementById("getAcceleration").addEventListener("click", getAcceleration);
document.getElementById("watchAcceleration").addEventListener(
"click", watchAcceleration);
Now, we will create two functions. The first function will be used to get the current acceleration and the second function will watch the acceleration and the information about the acceleration will be triggered every three seconds. We will also add the clearWatch function wrapped by the setTimeout function to stop watching acceleration after the specified time frame. The frequency parameter is used to trigger the callback function every three seconds.
function getAcceleration() {
navigator.accelerometer.getCurrentAcceleration(
accelerometerSuccess, accelerometerError);
function accelerometerSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
};
function accelerometerError() {
alert('onError!');
};
}
function watchAcceleration() {
var accelerometerOptions = {
frequency: 3000
}
var watchID = navigator.accelerometer.watchAcceleration(
accelerometerSuccess, accelerometerError, accelerometerOptions);
function accelerometerSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
setTimeout(function() {
navigator.accelerometer.clearWatch(watchID);
}, 10000);
};
function accelerometerError() {
alert('onError!');
};
}
Now if we press the GET ACCELERATION button, we will get the current acceleration value. If we press the WATCH ACCELERATION button, the alert will be triggered every three seconds. After third alert is shown the clearWatch function will be called and we will not get any more alerts since we set timeout to 10000 milliseconds.
Compass is used to show direction relative to geographic north cardinal point.
Open the command prompt window and run the following.
C:\Users\username\Desktop\CordovaProject>cordova plugin
add cordova-plugindevice-orientation
This plugin is similar to the acceleration plugin. Let us now create two buttons in index.html.
<button id = "getOrientation">GET ORIENTATION</button>
<button id = "watchOrientation">WATCH ORIENTATION</button>
Now, we will add event listeners inside the onDeviceReady function in index.js.
document.getElementById("getOrientation").addEventListener("click", getOrientation);
document.getElementById("watchOrientation").addEventListener("click", watchOrientation);
We will create two functions; the first function will generate the current acceleration and the other will check on the orientation changes. You can see that we are using the frequency option again to keep a watch on changes that occur every three seconds.
function getOrientation() {
navigator.compass.getCurrentHeading(compassSuccess, compassError);
function compassSuccess(heading) {
alert('Heading: ' + heading.magneticHeading);
};
function compassError(error) {
alert('CompassError: ' + error.code);
};
}
function watchOrientation(){
var compassOptions = {
frequency: 3000
}
var watchID = navigator.compass.watchHeading(compassSuccess,
compassError, compassOptions);
function compassSuccess(heading) {
alert('Heading: ' + heading.magneticHeading);
setTimeout(function() {
navigator.compass.clearWatch(watchID);
}, 10000);
};
function compassError(error) {
alert('CompassError: ' + error.code);
};
}
Since the compass plugin is almost the same as the acceleration plugin, we will show you an error code this time. Some devices do not have the magnetic sensor that is needed for the compass to work. If your device doesn't have it, the following error will be displayed.
The Cordova Dialogs plugin will call the platform native dialog UI element.
Type the following command in the command prompt window to install this plugin.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-dialogs
Let us now open index.html and add four buttons, one for every type of dialog.
<button id = "dialogAlert">ALERT</button>
<button id = "dialogConfirm">CONFIRM</button>
<button id = "dialogPrompt">PROMPT</button>
<button id = "dialogBeep">BEEP</button>
Now we will add the event listeners inside the onDeviceReady function in index.js. The listeners will call the callback function once the corresponding button is clicked.
document.getElementById("dialogAlert").addEventListener("click", dialogAlert);
document.getElementById("dialogConfirm").addEventListener("click", dialogConfirm);
document.getElementById("dialogPrompt").addEventListener("click", dialogPrompt);
document.getElementById("dialogBeep").addEventListener("click", dialogBeep);
Since we added four event listeners, we will now create the callback functions for all of them in index.js. The first one is dialogAlert.
function dialogAlert() {
var message = "I am Alert Dialog!";
var title = "ALERT";
var buttonName = "Alert Button";
navigator.notification.alert(message, alertCallback, title, buttonName);
function alertCallback() {
console.log("Alert is Dismissed!");
}
}
If we click the ALERT button, we will get see the alert dialog box.
When we click the dialog button, the following output will be displayed on the console.
The second function we need to create is the dialogConfirm function.
function dialogConfirm() {
var message = "Am I Confirm Dialog?";
var title = "CONFIRM";
var buttonLabels = "YES,NO";
navigator.notification.confirm(message, confirmCallback, title, buttonLabels);
function confirmCallback(buttonIndex) {
console.log("You clicked " + buttonIndex + " button!");
}
}
When the CONFIRM button is pressed, the new dialog will pop up.
We will click the YES button to answer the question. The following output will be displayed on the console.
The third function is the dialogPrompt function. This allows the users to type text into the dialog input element.
function dialogPrompt() {
var message = "Am I Prompt Dialog?";
var title = "PROMPT";
var buttonLabels = ["YES","NO"];
var defaultText = "Default"
navigator.notification.prompt(message, promptCallback,
title, buttonLabels, defaultText);
function promptCallback(result) {
console.log("You clicked " + result.buttonIndex + " button! \n" +
"You entered " + result.input1);
}
}
The PROMPT button will trigger a dialog box as in the following screenshot.
In this dialog box, we have an option to type the text. We will log this text in the console, together with a button that is clicked.
The last one is the dialogBeep function. This is used for calling the audio beep notification. The times parameter will set the number of repeats for the beep signal.
function dialogBeep() {
var times = 2;
navigator.notification.beep(times);
}
When we click the BEEP button, we will hear the notification sound twice, since the times value is set to 2.
This plugin is used for manipulating the native file system on the user's device.
We need to run the following code in the command prompt to install this plugin.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-file
In this example, we will show you how to create file, write to file, read it and delete it. For this reason, we will create four buttons in index.html. We will also add textarea wherein, the content of our file will be shown.
<button id = "createFile">CREATE FILE</button>
<button id = "writeFile">WRITE FILE</button>
<button id = "readFile">READ FILE</button>
<button id = "removeFile">DELETE FILE</button>
<textarea id = "textarea"></textarea>
We will add event listeners in index.js inside the onDeviceReady function to ensure that everything has started before the plugin is used.
document.getElementById("createFile").addEventListener("click", createFile);
document.getElementById("writeFile").addEventListener("click", writeFile);
document.getElementById("readFile").addEventListener("click", readFile);
document.getElementById("removeFile").addEventListener("click", removeFile);
The file will be created in the apps root folder on the device. To be able to access the root folder you need to provide superuser access to your folders. In our case, the path to root folder is \data\data\com.example.hello\cache. At the moment this folder is empty.
Let us now add a function that will create the log.txt file. We will write this code in index.js and send a request to the file system. This method uses WINDOW.TEMPORARY or WINDOW.PERSISTENT. The size that will be required for storage is valued in bytes (5MB in our case).
function createFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;
window.requestFileSystem(type, size, successCallback, errorCallback)
function successCallback(fs) {
fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
alert('File creation successfull!')
}, errorCallback);
}
function errorCallback(error) {
alert("ERROR: " + error.code)
}
}
Now we can press the CREATE FILE button and the alert will confirm that we successfully created the file.
Now, we can check our apps root folder again and we can find our new file there.
In this step, we will write some text to our file. We will again send a request to the file system, and then create the file writer to be able to write Lorem Ipsum text that we assigned to the blob variable.
function writeFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;
window.requestFileSystem(type, size, successCallback, errorCallback)
function successCallback(fs) {
fs.root.getFile('log.txt', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
alert('Write completed.');
};
fileWriter.onerror = function(e) {
alert('Write failed: ' + e.toString());
};
var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});
fileWriter.write(blob);
}, errorCallback);
}, errorCallback);
}
function errorCallback(error) {
alert("ERROR: " + error.code)
}
}
After pressing the WRITE FILE button, the alert will inform us that the writing is successful as in the following screenshot.
Now we can open log.txt and see that Lorem Ipsum is written inside.
In this step, we will read the log.txt file and display it in the textarea element. We will send a request to the file system and get the file object, then we are creating reader. When the reader is loaded, we will assign the returned value to textarea.
function readFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;
window.requestFileSystem(type, size, successCallback, errorCallback)
function successCallback(fs) {
fs.root.getFile('log.txt', {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var txtArea = document.getElementById('textarea');
txtArea.value = this.result;
};
reader.readAsText(file);
}, errorCallback);
}, errorCallback);
}
function errorCallback(error) {
alert("ERROR: " + error.code)
}
}
When we click the READ FILE button, the text from the file will be written inside textarea.
And finally we will create function for deleting log.txt file.
function removeFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;
window.requestFileSystem(type, size, successCallback, errorCallback)
function successCallback(fs) {
fs.root.getFile('log.txt', {create: false}, function(fileEntry) {
fileEntry.remove(function() {
alert('File removed.');
}, errorCallback);
}, errorCallback);
}
function errorCallback(error) {
alert("ERROR: " + error.code)
}
}
We can now press the DELETE FILE button to remove the file from the apps root folder. The alert will notify us that the delete operation is successful.
If we check the apps root folder, we will see that it is empty.
This plugin is used for uploading and downloading files.
We need to open command prompt and run the following command to install the plugin.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-file-transfer
In this chapter, we will show you how to upload and download files. Let's create two buttons in index.html
<button id = "uploadFile">UPLOAD</button>
<button id = "downloadFile">DOWNLOAD</button>
Event listeners will be created in index.js inside the onDeviceReady function. We are adding click events and callback functions.
document.getElementById("uploadFile").addEventListener("click", uploadFile);
document.getElementById("downloadFile").addEventListener("click", downloadFile);
This function will be used for downloading the files from server to device. We uploaded file to postimage.org to make things more simple. You will probably want to use your own server. The function is placed in index.js and will be triggered when the corresponding button is pressed. uri is the server download link and fileURI is the path to the DCIM folder on our device.
function downloadFile() {
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://s14.postimg.org/i8qvaxyup/bitcoin1.jpg");
var fileURL = "///storage/emulated/0/DCIM/myFile";
fileTransfer.download(
uri, fileURL, function(entry) {
console.log("download complete: " + entry.toURL());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
},
false, {
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}
Once we press the DOWNLOAD button, the file will be downloaded from the postimg.org server to our mobile device. We can check the specified folder and see that myFile is there.
The console output will look like this −
Now let's create a function that will take the file and upload it to the server. Again, we want to simplify this as much as possible, so we will use posttestserver.com online server for testing. The uri value will be linked for posting to posttestserver.
function uploadFile() {
var fileURL = "///storage/emulated/0/DCIM/myFile"
var uri = encodeURI("http://posttestserver.com/post.php");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType = "text/plain";
var headers = {'headerParam':'headerValue'};
options.headers = headers;
var ft = new FileTransfer();
ft.upload(fileURL, uri, onSuccess, onError, options);
function onSuccess(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function onError(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
}
Now we can press the UPLOAD button to trigger this function. We will get a console output as confirmation that the uploading was successful.
We can also check the server to make sure that the file was uploaded.
Geolocation is used for getting info about device's latitude and longitude.
We can install this plugin by typing the following code to command prompt window.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-geolocation
In this tutorial we will show you how to get current position and how to watch for changes. We first need to create buttons that will call these functions.
<button id = "getPosition">CURRENT POSITION</button>
<button id = "watchPosition">WATCH POSITION</button>
Now we want to add event listeners when the device is ready. We will add the code sample below to onDeviceReady function in index.js.
document.getElementById("getPosition").addEventListener("click", getPosition);
document.getElementById("watchPosition").addEventListener("click", watchPosition);
Two functions have to be created for two event listeners. One will be used for getting the current position and the other for watching the position.
function getPosition() {
var options = {
enableHighAccuracy: true,
maximumAge: 3600000
}
var watchID = navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
function onSuccess(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
function onError(error) {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
}
function watchPosition() {
var options = {
maximumAge: 3600000,
timeout: 3000,
enableHighAccuracy: true,
}
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
function onSuccess(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
function onError(error) {
alert('code: ' + error.code + '\n' +'message: ' + error.message + '\n');
}
}
In example above we are using two methods − getCurrentPosition and watchPosition. Both functions are using three parameters. Once we click CURRENT POSITION button, the alert will show geolocation values.
If we click WATCH POSITION button, the same alert will be triggered every three seconds. This way we can track movement changes of the user's device.
This plugin is using GPS. Sometimes it can't return the values on time and the request will return timeout error. This is why we specified enableHighAccuracy: true and maximumAge: 3600000. This means that if a request isn't completed on time, we will use the last known value instead. In our example, we are setting maximumAge to 3600000 milliseconds.
This plugin is used for getting information about users’ locale language, date and time zone, currency, etc.
Open command prompt and install the plugin by typing the following code
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-globalization
We will add several buttons to index.html to be able to call different methods that we will create later.
<button id = "getLanguage">LANGUAGE</button>
<button id = "getLocaleName">LOCALE NAME</button>
<button id = "getDate">DATE</button>
<button id = "getCurrency">CURRENCY</button>
Event listeners will be added inside getDeviceReady function in index.js file to ensure that our app and Cordova are loaded before we start using it.
document.getElementById("getLanguage").addEventListener("click", getLanguage);
document.getElementById("getLocaleName").addEventListener("click", getLocaleName);
document.getElementById("getDate").addEventListener("click", getDate);
document.getElementById("getCurrency").addEventListener("click", getCurrency);
The first function that we are using returns BCP 47 language tag of the client's device. We will use getPreferredLanguage method. The function has two parameters onSuccess and onError. We are adding this function in index.js.
function getLanguage() {
navigator.globalization.getPreferredLanguage(onSuccess, onError);
function onSuccess(language) {
alert('language: ' + language.value + '\n');
}
function onError(){
alert('Error getting language');
}
}
Once we press the LANGUAGE button, the alert will be shown on screen.
This function returns BCP 47 tag for the client's local settings. This function is similar as the one we created before. The only difference is that we are using getLocaleName method this time.
function getLocaleName() {
navigator.globalization.getLocaleName(onSuccess, onError);
function onSuccess(locale) {
alert('locale: ' + locale.value);
}
function onError(){
alert('Error getting locale');
}
}
When we click the LOCALE button, the alert will show our locale tag.
This function is used for returning date according to client's locale and timezone setting. date parameter is the current date and options parameter is optional.
function getDate() {
var date = new Date();
var options = {
formatLength:'short',
selector:'date and time'
}
navigator.globalization.dateToString(date, onSuccess, onError, options);
function onSuccess(date) {
alert('date: ' + date.value);
}
function onError(){
alert('Error getting dateString');
}
}
We can now run the app and press DATE button to see the current date.
The last function that we will show is returning currency values according to client's device settings and ISO 4217 currency code. You can see that the concept is the same.
function getCurrency() {
var currencyCode = 'EUR';
navigator.globalization.getCurrencyPattern(currencyCode, onSuccess, onError);
function onSuccess(pattern) {
alert('pattern: ' + pattern.pattern + '\n' +
'code: ' + pattern.code + '\n' +
'fraction: ' + pattern.fraction + '\n' +
'rounding: ' + pattern.rounding + '\n' +
'decimal: ' + pattern.decimal + '\n' +
'grouping: ' + pattern.grouping);
}
function onError(){
alert('Error getting pattern');
}
}
The CURRENCY button will trigger alert that will show users currency pattern.
This plugin offers other methods. You can see all of it in the table below.
This plugin is used for opening web browser inside Cordova app.
We need to install this plugin in command prompt window before we are able to use it.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-inappbrowser
We will add one button that will be used for opening inAppBrowser window in index.html.
Now let's add event listener for our button in onDeviceReady function in index.js.
document.getElementById("openBrowser").addEventListener("click", openBrowser);
In this step we are creating function that will open browser inside our app. We are assigning it to the ref variable that we can use later to add event listeners.
function openBrowser() {
var url = 'https://cordova.apache.org';
var target = '_blank';
var options = "location = yes"
var ref = cordova.InAppBrowser.open(url, target, options);
ref.addEventListener('loadstart', loadstartCallback);
ref.addEventListener('loadstop', loadstopCallback);
ref.addEventListener('loaderror', loaderrorCallback);
ref.addEventListener('exit', exitCallback);
function loadstartCallback(event) {
console.log('Loading started: ' + event.url)
}
function loadstopCallback(event) {
console.log('Loading finished: ' + event.url)
}
function loaderrorCallback(error) {
console.log('Loading error: ' + error.message)
}
function exitCallback() {
console.log('Browser is closed...')
}
}
If we press BROWSER button, we will see the following output on screen.
Console will also listen to events. loadstart event will fire when URL is started loading and loadstop will fire when URL is loaded. We can see it in console.
Once we close the browser, exit event will fire.
There are other possible options for InAppBrowser window. We will explain it in the table below.
location
Used to turn the browser location bar on or off. Values are yes or no.
hidden
Used to hide or show inAppBrowser. Values are yes or no.
clearCache
Used to clear browser cookie cache. Values are yes or no.
clearsessioncache
Used to clear session cookie cache. Values are yes or no.
zoom
Used to hide or show Android browser's zoom controls. Values are yes or no.
hardwareback
yes to use the hardware back button to navigate back through the browser history. no to close the browser once back button is clicked.
We can use ref (reference) variable for some other functionalities. We will show you just quick examples of it. For removing event listeners we can use −
ref.removeEventListener(eventname, callback);
For closing InAppBrowser we can use −
ref.close();
If we opened hidden window, we can show it −
ref.show();
Even JavaScript code can be injected to the InAppBrowser −
var details = "javascript/file/url"
ref.executeScript(details, callback);
The same concept can be used for injecting CSS −
var details = "css/file/url"
ref.inserCSS(details, callback);
Cordova media plugin is used for recording and playing audio sounds in Cordova apps.
Media plugin can be installed by running the following code in command prompt window.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-media
In this tutorial, we will create simple audio player. Let's create buttons that we need in index.html.
<button id = "playAudio">PLAY</button>
<button id = "pauseAudio">PAUSE</button>
<button id = "stopAudio">STOP</button>
<button id = "volumeUp">VOLUME UP</button>
<button id = "volumeDown">VOLUME DOWN</button>
Now we need to add event listeners for our buttons inside onDeviceReady function inside index.js.
document.getElementById("playAudio").addEventListener("click", playAudio);
document.getElementById("pauseAudio").addEventListener("click", pauseAudio);
document.getElementById("stopAudio").addEventListener("click", stopAudio);
document.getElementById("volumeUp").addEventListener("click", volumeUp);
document.getElementById("volumeDown").addEventListener("click", volumeDown);
The first function that we are going to add is playAudio. We are defining myMedia outside of the function because we want to use it in functions that are going to be added later (pause, stop, volumeUp and volumeDown). This code is placed in index.js file.
var myMedia = null;
function playAudio() {
var src = "/android_asset/www/audio/piano.mp3";
if(myMedia === null) {
myMedia = new Media(src, onSuccess, onError);
function onSuccess() {
console.log("playAudio Success");
}
function onError(error) {
console.log("playAudio Error: " + error.code);
}
}
myMedia.play();
}
We can click PLAY button to start the piano music from the src path.
The next functions that we need is pauseAudio and stopAudio.
function pauseAudio() {
if(myMedia) {
myMedia.pause();
}
}
function stopAudio() {
if(myMedia) {
myMedia.stop();
}
myMedia = null;
}
Now we can pause or stop the piano sound by clicking PAUSE or STOP buttons.
To set the volume, we can use setVolume method. This method takes parameter with values from 0 to 1. We will set starting value to 0.5.
var volumeValue = 0.5;
function volumeUp() {
if(myMedia && volumeValue < 1) {
myMedia.setVolume(volumeValue += 0.1);
}
}
function volumeDown() {
if(myMedia && volumeValue > 0) {
myMedia.setVolume(volumeValue -= 0.1);
}
}
Once we press VOLUME UP or VOLUME DOWN we can change the volume value by 0.1.
The following table shows other methods that this plugin provides.
getCurrentPosition
Returns current position of an audio.
getDuration
Returns duration of an audio.
play
Used for starting or resuming audio.
pause
Used for pausing audio.
release
Releases the underlying operating system's audio resources.
seekTo
Used for changing position of an audio.
setVolume
Used for setting volume for audio.
startRecord
Start recording an audio file.
stopRecord
Stop recording an audio file.
stop
Stop playing an audio file.
This plugin is used for accessing device's capture options.
To install this plugin, we will open command prompt and run the following code −
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-media-capture
Since we want to show you how to capture audio, image and video, we will create three buttons in index.html.
<button id = "audioCapture">AUDIO</button>
<button id = "imageCapture">IMAGE</button>
<button id = "videoCapture">VIDEO</button>
The next step is adding event listeners inside onDeviceReady in index.js.
document.getElementById("audioCapture").addEventListener("click", audioCapture);
document.getElementById("imageCapture").addEventListener("click", imageCapture);
document.getElementById("videoCapture").addEventListener("click", videoCapture);
The first callback function in index.js is audioCapture. To start sound recorder, we will use captureAudio method. We are using two options − limit will allow recording only one audio clip per single capture operation and duration is number of seconds of a sound clip.
function audioCapture() {
var options = {
limit: 1,
duration: 10
};
navigator.device.capture.captureAudio(onSuccess, onError, options);
function onSuccess(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
console.log(mediaFiles);
}
}
function onError(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
}
}
When we press AUDIO button, sound recorder will open.
Console will show returned array of objects that users captured.
The function for capturing image will be the same as the last one. The only difference is that we are using captureImage method this time.
function imageCapture() {
var options = {
limit: 1
};
navigator.device.capture.captureImage(onSuccess, onError, options);
function onSuccess(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
console.log(mediaFiles);
}
}
function onError(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
}
}
Now we can click IMAGE button to start the camera.
When we take picture, the console will log the array with image object.
Let's repeat the same concept for capturing video. We will use videoCapture method this time.
function videoCapture() {
var options = {
limit: 1,
duration: 10
};
navigator.device.capture.captureVideo(onSuccess, onError, options);
function onSuccess(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
console.log(mediaFiles);
}
}
function onError(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
}
}
If we press VIDEO button, the camera will open and we can record the video.
Once the video is saved, the console will return array once more. This time with video object inside.
This plugin provides information about device's network.
To install this plugin, we will open command prompt and run the following code −
C:\Users\username\Desktop\CordovaProject>cordova plugin
add cordova-plugin-network-information
Let's create one button in index.html that will be used for getting info about network.
<button id = "networkInfo">INFO</button>
We will add three event listeners inside onDeviceReady function in index.js. One will listen for clicks on the button we created before and the other two will listen for changes in connection status.
document.getElementById("networkInfo").addEventListener("click", networkInfo);
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);
networkInfo function will return info about current network connection once button is clicked. We are calling type method. The other functions are onOffline and onOnline. These functions are listening to the connection changes and any change will trigger the corresponding alert message.
function networkInfo() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
function onOffline() {
alert('You are now offline!');
}
function onOnline() {
alert('You are now online!');
}
When we start the app connected to the network, onOnline function will trigger alert.
If we press INFO button the alert will show our network state.
If we disconnect from the network, onOffline function will be called.
This plugin is used to display a splash screen on application launch.
Splash screen plugin can be installed in command prompt window by running the following code.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-splashscreen
Adding splash screen is different from adding the other Cordova plugins. We need to open config.xml and add the following code snippets inside the widget element.
First snippet is SplashScreen. It has value property which is the name of the images in platform/android/res/drawable- folders. Cordova offers default screen.png images that we are using in this example, but you will probably want to add your own images. Important thing is to add images for portrait and landscape view and also to cover different screen sizes.
<preference name = "SplashScreen" value = "screen" />
Second snippet we need to add is SplashScreenDelay. We are setting value to 3000 to hide the splash screen after three seconds.
<preference name = "SplashScreenDelay" value = "3000" />
The last preference is optional. If value is set to true, the image will not be stretched to fit screen. If it is set to false, it will be stretched.
<preference name = "SplashMaintainAspectRatio" value = "true" />
Now when we run the app, we will see the splash screen.
This plugin is used for connecting to device's vibration functionality.
We can install this plugin in command prompt window by running the following code −
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-vibration
Once the plugin is installed we can add buttons in index.html that will be used later to trigger the vibration.
<button id = "vibration">VIBRATION</button>
<button id = "vibrationPattern">PATTERN</button>
Now we are going to add event listeners inside onDeviceReady in index.js.
document.getElementById("vibration").addEventListener("click", vibration);
document.getElementById("vibrationPattern").addEventListener("click", vibrationPattern);
This plugin is very easy to use. We will create two functions.
function vibration() {
var time = 3000;
navigator.vibrate(time);
}
function vibrationPattern() {
var pattern = [1000, 1000, 1000, 1000];
navigator.vibrate(pattern);
}
The first function is taking time parameter. This parameter is used for setting the duration of the vibration. Device will vibrate for three seconds once we press VIBRATION button.
The second function is using pattern parameter. This array will ask device to vibrate for one second, then wait for one second, then repeat the process again.
This plugin allows us to implement whitelist policy for app's navigation. When we create a new Cordova project, the whitelist plugin is installed and implemented by default. You can open the config.xml file to see allow-intent default settings provided by Cordova.
In the simple example below we are allowing links to some external URL. This code is placed in config.xml. Navigation to file:// URLs is allowed by default.
<allow-navigation href = "http://example.com/*" />
The asterix sign, *, is used to allow navigation to multiple values. In the above example, we are allowing navigation to all sub-domains of the example.com. The same can be applied to protocol or prefix to the host.
<allow-navigation href = "*://*.example.com/*" />
There is also the allow-intent element which is used to specify which URLs are allowed to open the system. You can see in the config.xml that Cordova already allowed most of the needed links for us.
When you look inside config.xml file, there is <access origin="*" /> element. This element allows all network requests to our app via Cordova hooks. If you want to allow only specific requests, you can delete it from the config.xml and set it yourself.
The same principle is used as in previous examples.
<access origin = "http://example.com" />
This will allow all network requests from http://example.com.
You can see the current security policy for your app inside the head element in index.html.
<meta http-equiv = "Content-Security-Policy" content = "default-src
'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src
'self' 'unsafe-inline'; media-src *">
This is default configuration. If you want to allow everything from the same origin and example.com, then you can use −
<meta http-equiv = "Content-Security-Policy" content = "default-src 'self' foo.com">
You can also allow everything, but restrict CSS and JavaScript to the same origin.
<meta http-equiv = "Content-Security-Policy" content = "default-src *;
style-src 'self' 'unsafe-inline'; script-src 'self'
'unsafe-inline' 'unsafe-eval'">
Since this is a beginners’ tutorial, we are recommending the default Cordova options. Once you get familiar with Cordova, you can try some different values.
Cordova is used for creating hybrid mobile apps, so you need to consider this before you choose it for your project. Below are the best practices for Cordova apps development.
This is the recommended design for all Cordova apps. SPA is using client-side router and navigation loaded on the single page (usually index.html). The routing is handled via AJAX. If you have followed our tutorials, you probably noticed that almost every Cordova plugin needs to wait until the device is ready before it can be used. SPA design will improve loading speed and overall performance.
Since Cordova is used for mobile world it is natural to use touchstart and touchend events instead of click events. The click events have 300ms delay, so the clicks don’t feel native. On the other hand, touch events aren't supported on every platform. You should take this into consideration before you decide what to use.
You should always use hardware accelerated CSS Transitions instead of JavaScript animations since they will perform better on mobile devices.
Use storage caching as much as possible. Mobile network connections are usually bad, so you should minimize network calls inside your app. You should also handle offline status of the app, since there will be times when user's devices are offline.
Most of the time the first slow part inside your app will be scrolling lists. There are couple of ways to improve scrolling performance of the app. Our recommendation is to use native scrolling. When there are lots of items in the list, you should load them partially. Use loaders when necessary.
Images can also slow the mobile app. You should use CSS image sprites whenever possible. Try to fit the images perfectly instead of scaling it.
You should avoid shadows and gradients, since they slow the rendering time of the page.
Browser's DOM is slow, so you should try to minimize DOM manipulation and number of DOM elements.
Ensure that you test your app on as many devices and operating system versions as possible. If app works flawlessly on one device, it doesn't necessary mean that it will work on some other device or platform.
45 Lectures
2 hours
Skillbakerystudios
16 Lectures
1 hours
Nilay Mehta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2274,
"s": 2180,
"text": "Cordova is a platform for building hybrid mobile applications using HTML, CSS and JavaScript."
},
{
"code": null,
"e": 2342,
"s": 2274,
"text": "The official documentation gives us the definition of the Cordova −"
},
{
"code": null,
"e": 2748,
"s": 2342,
"text": "\"Apache Cordova is an open-source mobile development framework. It allows you to use standard web technologies such as HTML5, CSS3, and JavaScript for crossplatform development, avoiding each mobile platform native development language. Applications execute within wrappers targeted to each platform, and rely on standards-compliant API bindings to access each device's sensors, data, and network status.\""
},
{
"code": null,
"e": 2804,
"s": 2748,
"text": "Let us now understand the features of Cordova in brief."
},
{
"code": null,
"e": 3066,
"s": 2804,
"text": "This tool can be used for starting projects, building processes for different platforms, installing plugins and lot of other useful things that make the development process easier. You will learn how to use the Command Line Interface in the subsequent chapters."
},
{
"code": null,
"e": 3256,
"s": 3066,
"text": "Cordova offers a set of core components that every mobile application needs. These components will be used for creating base of the app so we can spend more time to implement our own logic."
},
{
"code": null,
"e": 3357,
"s": 3256,
"text": "Cordova offers API that will be used for implementing native mobile functions to our JavaScript app."
},
{
"code": null,
"e": 3502,
"s": 3357,
"text": "Cordova is licensed under the Apache License, Version 2.0. Apache and the Apache feather logos are trademarks of The Apache Software Foundation."
},
{
"code": null,
"e": 3549,
"s": 3502,
"text": "We will now discuss the advantages of Cordova."
},
{
"code": null,
"e": 3772,
"s": 3549,
"text": "Cordova offers one platform for building hybrid mobile apps so we can develop one app that will be used on different mobile platforms – IOS, Android, Windows Phone, Amazon-fireos, blackberry, Firefox OS, Ubuntu and tizien."
},
{
"code": null,
"e": 3995,
"s": 3772,
"text": "Cordova offers one platform for building hybrid mobile apps so we can develop one app that will be used on different mobile platforms – IOS, Android, Windows Phone, Amazon-fireos, blackberry, Firefox OS, Ubuntu and tizien."
},
{
"code": null,
"e": 4091,
"s": 3995,
"text": "It is faster to develop hybrid app then native app so Cordova can save on the development time."
},
{
"code": null,
"e": 4187,
"s": 4091,
"text": "It is faster to develop hybrid app then native app so Cordova can save on the development time."
},
{
"code": null,
"e": 4308,
"s": 4187,
"text": "Since we are using JavaScript when working with Cordova, we don't need to learn platform specific programming languages."
},
{
"code": null,
"e": 4429,
"s": 4308,
"text": "Since we are using JavaScript when working with Cordova, we don't need to learn platform specific programming languages."
},
{
"code": null,
"e": 4579,
"s": 4429,
"text": "There are many community add-ons that can be used with Cordova, these have several libraries and frameworks, which are optimized for working with it."
},
{
"code": null,
"e": 4729,
"s": 4579,
"text": "There are many community add-ons that can be used with Cordova, these have several libraries and frameworks, which are optimized for working with it."
},
{
"code": null,
"e": 4771,
"s": 4729,
"text": "Following are the limitations of Cordova."
},
{
"code": null,
"e": 4907,
"s": 4771,
"text": "Hybrid apps are slower than native ones so it is not optimal to use Cordova for large apps that require lots of data and functionality."
},
{
"code": null,
"e": 5043,
"s": 4907,
"text": "Hybrid apps are slower than native ones so it is not optimal to use Cordova for large apps that require lots of data and functionality."
},
{
"code": null,
"e": 5282,
"s": 5043,
"text": "Cross browser compatibility can create lots of issues. Most of the time we are building apps for different platforms so the testing and optimizing can be time consuming since we need to cover large number of devices and operating systems."
},
{
"code": null,
"e": 5521,
"s": 5282,
"text": "Cross browser compatibility can create lots of issues. Most of the time we are building apps for different platforms so the testing and optimizing can be time consuming since we need to cover large number of devices and operating systems."
},
{
"code": null,
"e": 5669,
"s": 5521,
"text": "Some plugins have compatibility issues with different devices and platforms. There are also some native APIs that are not yet supported by Cordova."
},
{
"code": null,
"e": 5817,
"s": 5669,
"text": "Some plugins have compatibility issues with different devices and platforms. There are also some native APIs that are not yet supported by Cordova."
},
{
"code": null,
"e": 6005,
"s": 5817,
"text": "In this chapter, we will understand the Environment Setup of Cordova. To begin with the setup, we need to first install a few components. The components are listed in the following table."
},
{
"code": null,
"e": 6020,
"s": 6005,
"text": "NodeJS and NPM"
},
{
"code": null,
"e": 6132,
"s": 6020,
"text": "NodeJS is the platform needed for Cordova development. Check out our NodeJS Environment Setup for more details."
},
{
"code": null,
"e": 6144,
"s": 6132,
"text": "Android SDK"
},
{
"code": null,
"e": 6276,
"s": 6144,
"text": "For Android platform, you need to have Android SDK installed on your machine. Check out Android Environment Setup for more details."
},
{
"code": null,
"e": 6282,
"s": 6276,
"text": "XCode"
},
{
"code": null,
"e": 6399,
"s": 6282,
"text": "For iOS platform, you need to have xCode installed on your machine. Check out iOS Environment Setup for more details"
},
{
"code": null,
"e": 6490,
"s": 6399,
"text": "Before we start, you need to know that we will use Windows command prompt in our tutorial."
},
{
"code": null,
"e": 6679,
"s": 6490,
"text": "Even if you don't use git, it should be installed since Cordova is using it for some background processes. You can download git here. After you install git, open your environment variable."
},
{
"code": null,
"e": 6703,
"s": 6679,
"text": "Right-Click on Computer"
},
{
"code": null,
"e": 6714,
"s": 6703,
"text": "Properties"
},
{
"code": null,
"e": 6739,
"s": 6714,
"text": "Advanced System settings"
},
{
"code": null,
"e": 6761,
"s": 6739,
"text": "Environment Variables"
},
{
"code": null,
"e": 6778,
"s": 6761,
"text": "System Variables"
},
{
"code": null,
"e": 6783,
"s": 6778,
"text": "Edit"
},
{
"code": null,
"e": 6983,
"s": 6783,
"text": "Copy the following at the end of the variable value field. This is default path of the git installation. If you installed it on a different path you should use that instead of our example code below."
},
{
"code": null,
"e": 7047,
"s": 6983,
"text": ";C:\\Program Files (x86)\\Git\\bin;C:\\Program Files (x86)\\Git\\cmd\n"
},
{
"code": null,
"e": 7134,
"s": 7047,
"text": "Now you can type git in your command prompt to test if the installation is successful."
},
{
"code": null,
"e": 7243,
"s": 7134,
"text": "This step will download and install Cordova module globally. Open the command prompt and run the following −"
},
{
"code": null,
"e": 7286,
"s": 7243,
"text": "C:\\Users\\username>npm install -g cordova \n"
},
{
"code": null,
"e": 7335,
"s": 7286,
"text": "You can check the installed version by running −"
},
{
"code": null,
"e": 7366,
"s": 7335,
"text": "C:\\Users\\username>cordova -v \n"
},
{
"code": null,
"e": 7532,
"s": 7366,
"text": "This is everything you need to start developing the Cordova apps on Windows operating system. In our next tutorial, we will show you how to create first application."
},
{
"code": null,
"e": 7687,
"s": 7532,
"text": "We have understood how to install Cordova and set up the environment for it. Once everything is ready, we can create our first hybrid Cordova application."
},
{
"code": null,
"e": 7794,
"s": 7687,
"text": "Open the directory where you want the app to be installed in command prompt. We will create it on desktop."
},
{
"code": null,
"e": 7890,
"s": 7794,
"text": "C:\\Users\\username\\Desktop>cordova \n create CordovaProject io.cordova.hellocordova CordovaApp\n"
},
{
"code": null,
"e": 7953,
"s": 7890,
"text": "CordovaProject is the directory name where the app is created."
},
{
"code": null,
"e": 8016,
"s": 7953,
"text": "CordovaProject is the directory name where the app is created."
},
{
"code": null,
"e": 8127,
"s": 8016,
"text": "io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible."
},
{
"code": null,
"e": 8238,
"s": 8127,
"text": "io.cordova.hellocordova is the default reverse domain value. You should use your own domain value if possible."
},
{
"code": null,
"e": 8275,
"s": 8238,
"text": "CordovaApp is the title of your app."
},
{
"code": null,
"e": 8312,
"s": 8275,
"text": "CordovaApp is the title of your app."
},
{
"code": null,
"e": 8732,
"s": 8312,
"text": "You need to open your project directory in the command prompt. In our example, it is the CordovaProject. You should only choose platforms that you need. To be able to use the specified platform, you need to have installed the specific platform SDK. Since we are developing on windows, we can use the following platforms. We have already installed Android SDK, so we will only install android platform for this tutorial."
},
{
"code": null,
"e": 8804,
"s": 8732,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add android \n"
},
{
"code": null,
"e": 8862,
"s": 8804,
"text": "There are other platforms that can be used on Windows OS."
},
{
"code": null,
"e": 8930,
"s": 8862,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add wp8 \n"
},
{
"code": null,
"e": 9008,
"s": 8930,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add amazon-fireos \n"
},
{
"code": null,
"e": 9080,
"s": 9008,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add windows \n"
},
{
"code": null,
"e": 9156,
"s": 9080,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add blackberry10\n"
},
{
"code": null,
"e": 9230,
"s": 9156,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform add firefoxos \n"
},
{
"code": null,
"e": 9274,
"s": 9230,
"text": "If you are developing on Mac, you can use −"
},
{
"code": null,
"e": 9303,
"s": 9274,
"text": "$ cordova platform add IOS \n"
},
{
"code": null,
"e": 9342,
"s": 9303,
"text": "$ cordova platform add amazon-fireos \n"
},
{
"code": null,
"e": 9375,
"s": 9342,
"text": "$ cordova platform add android \n"
},
{
"code": null,
"e": 9413,
"s": 9375,
"text": "$ cordova platform add blackberry10 \n"
},
{
"code": null,
"e": 9448,
"s": 9413,
"text": "$ cordova platform add firefoxos \n"
},
{
"code": null,
"e": 9506,
"s": 9448,
"text": "You can also remove platform from your project by using −"
},
{
"code": null,
"e": 9577,
"s": 9506,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova platform rm android \n"
},
{
"code": null,
"e": 9684,
"s": 9577,
"text": "In this step we will build the app for a specified platform so we can run it on mobile device or emulator."
},
{
"code": null,
"e": 9749,
"s": 9684,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova build android \n"
},
{
"code": null,
"e": 9828,
"s": 9749,
"text": "Now we can run our app. If you are using the default emulator you should use −"
},
{
"code": null,
"e": 9895,
"s": 9828,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova emulate android \n"
},
{
"code": null,
"e": 9968,
"s": 9895,
"text": "If you want to use the external emulator or real device you should use −"
},
{
"code": null,
"e": 10031,
"s": 9968,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova run android \n"
},
{
"code": null,
"e": 10373,
"s": 10031,
"text": "NOTE − We will use the Genymotion android emulator since it is faster and more responsive than the default one. You can find the emulator here. You can also use real device for testing by enabling USB debugging from the options and connecting it to your computer via USB cable. For some devices, you will also need to install the USB driver."
},
{
"code": null,
"e": 10545,
"s": 10373,
"text": "Once we run the app, it will install it on the platform we specified. If everything is finished without errors, the output should show the default start screen of the app."
},
{
"code": null,
"e": 10626,
"s": 10545,
"text": "In our next tutorial, we will show you how to configure the Cordova Application."
},
{
"code": null,
"e": 10907,
"s": 10626,
"text": "The config.xml file is the place where we can change the configuration of the app. When we created our app in the last tutorial, we set reverse domain and name. The values can be changed in the config.xml file. When we create the app, the default config file will also be created."
},
{
"code": null,
"e": 10974,
"s": 10907,
"text": "The following table explains configuration elements in config.xml."
},
{
"code": null,
"e": 10981,
"s": 10974,
"text": "widget"
},
{
"code": null,
"e": 11051,
"s": 10981,
"text": "The app reverse domain value that we specified when creating the app."
},
{
"code": null,
"e": 11056,
"s": 11051,
"text": "name"
},
{
"code": null,
"e": 11117,
"s": 11056,
"text": "The name of the app that we specified when creating the app."
},
{
"code": null,
"e": 11129,
"s": 11117,
"text": "description"
},
{
"code": null,
"e": 11154,
"s": 11129,
"text": "Description for the app."
},
{
"code": null,
"e": 11161,
"s": 11154,
"text": "author"
},
{
"code": null,
"e": 11180,
"s": 11161,
"text": "Author of the app."
},
{
"code": null,
"e": 11188,
"s": 11180,
"text": "content"
},
{
"code": null,
"e": 11252,
"s": 11188,
"text": "The app's starting page. It is placed inside the www directory."
},
{
"code": null,
"e": 11259,
"s": 11252,
"text": "plugin"
},
{
"code": null,
"e": 11301,
"s": 11259,
"text": "The plugins that are currently installed."
},
{
"code": null,
"e": 11308,
"s": 11301,
"text": "access"
},
{
"code": null,
"e": 11521,
"s": 11308,
"text": "Used to control access to external domains. The default origin value is set to * which means that access is allowed to any domain. This value will not allow some specific URLs to be opened to protect information."
},
{
"code": null,
"e": 11534,
"s": 11521,
"text": "allow-intent"
},
{
"code": null,
"e": 11666,
"s": 11534,
"text": "Allows specific URLs to ask the app to open. For example, <allow-intent href = \"tel:*\" /> will allow tel: links to open the dialer."
},
{
"code": null,
"e": 11675,
"s": 11666,
"text": "platform"
},
{
"code": null,
"e": 11711,
"s": 11675,
"text": "The platforms for building the app."
},
{
"code": null,
"e": 12044,
"s": 11711,
"text": "We can use storage API available for storing data on the client apps. This will help the usage of the app when the user is offline and it can also improve performance. Since this tutorial is for beginners, we will show you how to use local storage. In one of our later tutorials, we will show you the other plugins that can be used."
},
{
"code": null,
"e": 12162,
"s": 12044,
"text": "We will create four buttons in the index.html file. The buttons will be located inside the div class = \"app\" element."
},
{
"code": null,
"e": 12405,
"s": 12162,
"text": "<button id = \"setLocalStorage\">SET LOCAL STORAGE</button>\n<button id = \"showLocalStorage\">SHOW LOCAL STORAGE</button>\n<button id = \"removeProjectFromLocalStorage\">REMOVE PROJECT</button>\n<button id = \"getLocalStorageByKey\">GET BY KEY</button>"
},
{
"code": null,
"e": 12444,
"s": 12405,
"text": "It will produce the following screen −"
},
{
"code": null,
"e": 12641,
"s": 12444,
"text": "Cordova security policy doesn't allow inline events so we will add event listeners inside index.js files. We will also assign window.localStorage to a localStorage variable that we will use later."
},
{
"code": null,
"e": 13086,
"s": 12641,
"text": "document.getElementById(\"setLocalStorage\").addEventListener(\"click\", setLocalStorage); \ndocument.getElementById(\"showLocalStorage\").addEventListener(\"click\", showLocalStorage); \ndocument.getElementById(\"removeProjectFromLocalStorage\").addEventListener \n (\"click\", removeProjectFromLocalStorage); \ndocument.getElementById(\"getLocalStorageByKey\").addEventListener \n (\"click\", getLocalStorageByKey); \nvar localStorage = window.localStorage; \t"
},
{
"code": null,
"e": 13224,
"s": 13086,
"text": "Now we need to create functions that will be called when the buttons are tapped. First function is used for adding data to local storage."
},
{
"code": null,
"e": 13401,
"s": 13224,
"text": "function setLocalStorage() { \n localStorage.setItem(\"Name\", \"John\"); \n localStorage.setItem(\"Job\", \"Developer\"); \n localStorage.setItem(\"Project\", \"Cordova Project\"); \n} "
},
{
"code": null,
"e": 13453,
"s": 13401,
"text": "The next one will log the data we added to console."
},
{
"code": null,
"e": 13631,
"s": 13453,
"text": "function showLocalStorage() { \n console.log(localStorage.getItem(\"Name\")); \n console.log(localStorage.getItem(\"Job\")); \n console.log(localStorage.getItem(\"Project\")); \n} \t"
},
{
"code": null,
"e": 13791,
"s": 13631,
"text": "If we tap SET LOCAL STORAGE button, we will set three items to local storage. If we tap SHOW LOCAL STORAGE afterwards, the console will log items that we want."
},
{
"code": null,
"e": 13867,
"s": 13791,
"text": "Let us now create function that will delete the project from local storage."
},
{
"code": null,
"e": 13951,
"s": 13867,
"text": "function removeProjectFromLocalStorage() {\n localStorage.removeItem(\"Project\");\n}"
},
{
"code": null,
"e": 14078,
"s": 13951,
"text": "If we click the SHOW LOCAL STORAGE button after we deleted the project, the output will show null value for the project field."
},
{
"code": null,
"e": 14243,
"s": 14078,
"text": "We can also get the local storage elements by using the key() method which will take the index as an argument and return the element with corresponding index value."
},
{
"code": null,
"e": 14316,
"s": 14243,
"text": "function getLocalStorageByKey() {\n console.log(localStorage.key(0));\n}"
},
{
"code": null,
"e": 14395,
"s": 14316,
"text": "Now when we tap the GET BY KEY button, the following output will be displayed."
},
{
"code": null,
"e": 14611,
"s": 14395,
"text": "When we use the key() method, the console will log the job instead of the name even though we passed argument 0 to retrieve the first object. This is because the local storage is storing data in alphabetical order."
},
{
"code": null,
"e": 14678,
"s": 14611,
"text": "The following table shows all the available local storage methods."
},
{
"code": null,
"e": 14698,
"s": 14678,
"text": "setItem(key, value)"
},
{
"code": null,
"e": 14742,
"s": 14698,
"text": "Used for setting the item to local storage."
},
{
"code": null,
"e": 14755,
"s": 14742,
"text": "getItem(key)"
},
{
"code": null,
"e": 14801,
"s": 14755,
"text": "Used for getting the item from local storage."
},
{
"code": null,
"e": 14817,
"s": 14801,
"text": "removeItem(key)"
},
{
"code": null,
"e": 14864,
"s": 14817,
"text": "Used for removing the item from local storage."
},
{
"code": null,
"e": 14875,
"s": 14864,
"text": "key(index)"
},
{
"code": null,
"e": 14992,
"s": 14875,
"text": "Used for getting the item by using the index of the item in local storage. This helps sort the items alphabetically."
},
{
"code": null,
"e": 15001,
"s": 14992,
"text": "length()"
},
{
"code": null,
"e": 15071,
"s": 15001,
"text": "Used for retrieving the number of items that exists in local storage."
},
{
"code": null,
"e": 15079,
"s": 15071,
"text": "clear()"
},
{
"code": null,
"e": 15141,
"s": 15079,
"text": "Used for removing all the key/value pairs from local storage."
},
{
"code": null,
"e": 15252,
"s": 15141,
"text": "There are various events that can be used in Cordova projects. The following table shows the available events."
},
{
"code": null,
"e": 15264,
"s": 15252,
"text": "deviceReady"
},
{
"code": null,
"e": 15405,
"s": 15264,
"text": "This event is triggered once Cordova is fully loaded. This helps to ensure that no Cordova functions are called before everything is loaded."
},
{
"code": null,
"e": 15411,
"s": 15405,
"text": "pause"
},
{
"code": null,
"e": 15472,
"s": 15411,
"text": "This event is triggered when the app is put into background."
},
{
"code": null,
"e": 15479,
"s": 15472,
"text": "resume"
},
{
"code": null,
"e": 15545,
"s": 15479,
"text": "This event is triggered when the app is returned from background."
},
{
"code": null,
"e": 15556,
"s": 15545,
"text": "backbutton"
},
{
"code": null,
"e": 15613,
"s": 15556,
"text": "This event is triggered when the back button is pressed."
},
{
"code": null,
"e": 15624,
"s": 15613,
"text": "menubutton"
},
{
"code": null,
"e": 15681,
"s": 15624,
"text": "This event is triggered when the menu button is pressed."
},
{
"code": null,
"e": 15694,
"s": 15681,
"text": "searchbutton"
},
{
"code": null,
"e": 15761,
"s": 15694,
"text": "This event is triggered when the Android search button is pressed."
},
{
"code": null,
"e": 15777,
"s": 15761,
"text": "startcallbutton"
},
{
"code": null,
"e": 15840,
"s": 15777,
"text": "This event is triggered when the start call button is pressed."
},
{
"code": null,
"e": 15854,
"s": 15840,
"text": "endcallbutton"
},
{
"code": null,
"e": 15915,
"s": 15854,
"text": "This event is triggered when the end call button is pressed."
},
{
"code": null,
"e": 15932,
"s": 15915,
"text": "volumedownbutton"
},
{
"code": null,
"e": 15996,
"s": 15932,
"text": "This event is triggered when the volume down button is pressed."
},
{
"code": null,
"e": 16011,
"s": 15996,
"text": "volumeupbutton"
},
{
"code": null,
"e": 16073,
"s": 16011,
"text": "This event is triggered when the volume up button is pressed."
},
{
"code": null,
"e": 16350,
"s": 16073,
"text": "All of the events are used almost the same way. We should always add event listeners in our js instead of the inline event calling since the Cordova Content Security Policy doesn't allow inline Javascript. If we try to call event inline, the following error will be displayed."
},
{
"code": null,
"e": 16492,
"s": 16350,
"text": "The right way of working with events is by using addEventListener. We will understand how to use the volumeupbutton event through an example."
},
{
"code": null,
"e": 16639,
"s": 16492,
"text": "document.addEventListener(\"volumeupbutton\", callbackFunction, false); \nfunction callbackFunction() { \n alert('Volume Up Button is pressed!');\n}"
},
{
"code": null,
"e": 16720,
"s": 16639,
"text": "Once we press the volume up button, the screen will display the following alert."
},
{
"code": null,
"e": 16928,
"s": 16720,
"text": "We should use the Android back button for app functionalities like returning to the previous screen. To implement your own functionality, we should first disable the back button that is used to exit the App."
},
{
"code": null,
"e": 17087,
"s": 16928,
"text": "document.addEventListener(\"backbutton\", onBackKeyDown, false); \nfunction onBackKeyDown(e) { \n e.preventDefault(); \n alert('Back Button is Pressed!'); \n} "
},
{
"code": null,
"e": 17255,
"s": 17087,
"text": "Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using the e.preventDefault() command."
},
{
"code": null,
"e": 17489,
"s": 17255,
"text": "You will usually want to use Android back button for some app functionality like returning to previous screen. To be able to implement your own functionality, you first need to disable exiting the app when the back button is pressed."
},
{
"code": null,
"e": 17647,
"s": 17489,
"text": "document.addEventListener(\"backbutton\", onBackKeyDown, false); \nfunction onBackKeyDown(e) { \n e.preventDefault(); \n alert('Back Button is Pressed!'); \n}"
},
{
"code": null,
"e": 17803,
"s": 17647,
"text": "Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using e.preventDefault()."
},
{
"code": null,
"e": 18081,
"s": 17803,
"text": "Cordova Plugman is a useful command line tool for installing and managing plugins. You should use plugman if your app needs to run on one specific platform. If you want to create a cross-platform app you should use cordova-cli which will modify plugins for different platforms."
},
{
"code": null,
"e": 18167,
"s": 18081,
"text": "Open the command prompt window and run the following code snippet to install plugman."
},
{
"code": null,
"e": 18232,
"s": 18167,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>npm install -g plugman\n"
},
{
"code": null,
"e": 18340,
"s": 18232,
"text": "To understand how to install the Cordova plugin using plugman, we will use the Camera plugin as an example."
},
{
"code": null,
"e": 18592,
"s": 18340,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>plugman \n install --platform android --project platforms\\android \n --plugin cordova-plugin-camera \n plugman uninstall --platform android --project platforms\\android \n --plugin cordova-plugin-camera \n"
},
{
"code": null,
"e": 18645,
"s": 18592,
"text": "We need to consider three parameters as shown above."
},
{
"code": null,
"e": 18735,
"s": 18645,
"text": "--platform − platform that we are using (android, ios, amazon-fireos, wp8, blackberry10)."
},
{
"code": null,
"e": 18825,
"s": 18735,
"text": "--platform − platform that we are using (android, ios, amazon-fireos, wp8, blackberry10)."
},
{
"code": null,
"e": 18919,
"s": 18825,
"text": "--project − path where the project is built. In our case, it is platforms\\android directory."
},
{
"code": null,
"e": 19013,
"s": 18919,
"text": "--project − path where the project is built. In our case, it is platforms\\android directory."
},
{
"code": null,
"e": 19060,
"s": 19013,
"text": "--plugin − the plugin that we want to install."
},
{
"code": null,
"e": 19107,
"s": 19060,
"text": "--plugin − the plugin that we want to install."
},
{
"code": null,
"e": 19199,
"s": 19107,
"text": "If you set valid parameters, the command prompt window should display the following output."
},
{
"code": null,
"e": 19248,
"s": 19199,
"text": "You can use the uninstall method in similar way."
},
{
"code": null,
"e": 19392,
"s": 19248,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>plugman uninstall \n --platform android --project platforms\\android --plugin cordova-plugin-camera \n"
},
{
"code": null,
"e": 19454,
"s": 19392,
"text": "The command prompt console will display the following output."
},
{
"code": null,
"e": 19558,
"s": 19454,
"text": "Plugman offers some additional methods that can be used. The methods are listed in the following table."
},
{
"code": null,
"e": 19566,
"s": 19558,
"text": "install"
},
{
"code": null,
"e": 19603,
"s": 19566,
"text": "Used for installing Cordova plugins."
},
{
"code": null,
"e": 19613,
"s": 19603,
"text": "uninstall"
},
{
"code": null,
"e": 19652,
"s": 19613,
"text": "Used for uninstalling Cordova plugins."
},
{
"code": null,
"e": 19658,
"s": 19652,
"text": "fetch"
},
{
"code": null,
"e": 19712,
"s": 19658,
"text": "Used for copying Cordova plugin to specific location."
},
{
"code": null,
"e": 19720,
"s": 19712,
"text": "prepare"
},
{
"code": null,
"e": 19784,
"s": 19720,
"text": "Used for updating configuration file to help JS module support."
},
{
"code": null,
"e": 19792,
"s": 19784,
"text": "adduser"
},
{
"code": null,
"e": 19838,
"s": 19792,
"text": "Used for adding user account to the registry."
},
{
"code": null,
"e": 19846,
"s": 19838,
"text": "publish"
},
{
"code": null,
"e": 19890,
"s": 19846,
"text": "Used for publishing plugin to the registry."
},
{
"code": null,
"e": 19900,
"s": 19890,
"text": "unpublish"
},
{
"code": null,
"e": 19948,
"s": 19900,
"text": "Used for unpublishing plugin from the registry."
},
{
"code": null,
"e": 19955,
"s": 19948,
"text": "search"
},
{
"code": null,
"e": 20003,
"s": 19955,
"text": "Used for searching the plugins in the registry."
},
{
"code": null,
"e": 20010,
"s": 20003,
"text": "config"
},
{
"code": null,
"e": 20052,
"s": 20010,
"text": "Used for registry settings configuration."
},
{
"code": null,
"e": 20059,
"s": 20052,
"text": "create"
},
{
"code": null,
"e": 20092,
"s": 20059,
"text": "Used for creating custom plugin."
},
{
"code": null,
"e": 20101,
"s": 20092,
"text": "platform"
},
{
"code": null,
"e": 20170,
"s": 20101,
"text": "Used for adding or removing platform from the custom created plugin."
},
{
"code": null,
"e": 20432,
"s": 20170,
"text": "If you are stuck, you can always use the plugman -help command. The version can be checked by using plugman -v. To search for the plugin, you can use plugman search and finally you can change the plugin registry by using the plugman config set registry command."
},
{
"code": null,
"e": 20580,
"s": 20432,
"text": "Since Cordova is used for cross platform development, in our subsequent chapters we will use Cordova CLI instead of Plugman for installing plugins."
},
{
"code": null,
"e": 20719,
"s": 20580,
"text": "This Cordova plugin is used for monitoring device's battery status. The plugin will monitor every change that happens to device's battery."
},
{
"code": null,
"e": 20813,
"s": 20719,
"text": "To install this plugin, we need to open the command prompt window and run the following code."
},
{
"code": null,
"e": 20904,
"s": 20813,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-pluginbattery-status \n"
},
{
"code": null,
"e": 21029,
"s": 20904,
"text": "When you open the index.js file, you will find the onDeviceReady function. This is where the event listener should be added."
},
{
"code": null,
"e": 21097,
"s": 21029,
"text": "window.addEventListener(\"batterystatus\", onBatteryStatus, false); \n"
},
{
"code": null,
"e": 21186,
"s": 21097,
"text": "We will create the onBatteryStatus callback function at the bottom of the index.js file."
},
{
"code": null,
"e": 21308,
"s": 21186,
"text": "function onBatteryStatus(info) { \n alert(\"BATTERY STATUS: Level: \" + info.level + \" isPlugged: \" + info.isPlugged); \n}"
},
{
"code": null,
"e": 21401,
"s": 21308,
"text": "When we run the app, an alert will be triggered. At the moment, the battery is 100% charged."
},
{
"code": null,
"e": 21522,
"s": 21401,
"text": "When the status is changed, a new alert will be displayed. The battery status shows that the battery is now charged 99%."
},
{
"code": null,
"e": 21632,
"s": 21522,
"text": "If we plug in the device to the charger, the new alert will show that the isPlugged value is changed to true."
},
{
"code": null,
"e": 21775,
"s": 21632,
"text": "This plugin offers two additional events besides the batterystatus event. These events can be used in the same way as the batterystatus event."
},
{
"code": null,
"e": 21786,
"s": 21775,
"text": "batterylow"
},
{
"code": null,
"e": 21905,
"s": 21786,
"text": "The event is triggered when the battery charge percentage reaches low value. This value varies with different devices."
},
{
"code": null,
"e": 21921,
"s": 21905,
"text": "batterycritical"
},
{
"code": null,
"e": 22045,
"s": 21921,
"text": "The event is triggered when the battery charge percentage reaches critical value. This value varies with different devices."
},
{
"code": null,
"e": 22122,
"s": 22045,
"text": "This plugin is used for taking photos or using files from the image gallery."
},
{
"code": null,
"e": 22198,
"s": 22122,
"text": "Run the following code in the command prompt window to install this plugin."
},
{
"code": null,
"e": 22280,
"s": 22198,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugincamera\n"
},
{
"code": null,
"e": 22459,
"s": 22280,
"text": "Now, we will create the button for calling the camera and img where the image will be displayed once taken. This will be added to index.html inside the div class = \"app\" element."
},
{
"code": null,
"e": 22541,
"s": 22459,
"text": "<button id = \"cameraTakePicture\">TAKE PICTURE</button>\n<img id = \"myImage\"></img>"
},
{
"code": null,
"e": 22662,
"s": 22541,
"text": "The event listener is added inside the onDeviceReady function to ensure that Cordova is loaded before we start using it."
},
{
"code": null,
"e": 22759,
"s": 22662,
"text": "document.getElementById(\"cameraTakePicture\").addEventListener \n (\"click\", cameraTakePicture); "
},
{
"code": null,
"e": 23193,
"s": 22759,
"text": "We will create the cameraTakePicture function that is passed as a callback to our event listener. It will be fired when the button is tapped. Inside this function, we will call the navigator.camera global object provided by the plugin API. If taking picture is successful, the data will be sent to the onSuccess callback function, if not, the alert with error message will be shown. We will place this code at the bottom of index.js."
},
{
"code": null,
"e": 23611,
"s": 23193,
"text": "function cameraTakePicture() { \n navigator.camera.getPicture(onSuccess, onFail, { \n quality: 50, \n destinationType: Camera.DestinationType.DATA_URL \n }); \n \n function onSuccess(imageData) { \n var image = document.getElementById('myImage'); \n image.src = \"data:image/jpeg;base64,\" + imageData; \n } \n \n function onFail(message) { \n alert('Failed because: ' + message); \n } \n}"
},
{
"code": null,
"e": 23686,
"s": 23611,
"text": "When we run the app and press the button, native camera will be triggered."
},
{
"code": null,
"e": 23749,
"s": 23686,
"text": "When we take and save picture, it will be displayed on screen."
},
{
"code": null,
"e": 23955,
"s": 23749,
"text": "The same procedure can be used for getting image from the local file system. The only difference is the function created in the last step. You can see that the sourceType optional parameter has been added."
},
{
"code": null,
"e": 24037,
"s": 23955,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugincamera\n"
},
{
"code": null,
"e": 24090,
"s": 24037,
"text": "<button id = \"cameraGetPicture\">GET PICTURE</button>"
},
{
"code": null,
"e": 24181,
"s": 24090,
"text": "document.getElementById(\"cameraGetPicture\").addEventListener(\"click\", cameraGetPicture); \n"
},
{
"code": null,
"e": 24599,
"s": 24181,
"text": "function cameraGetPicture() {\n navigator.camera.getPicture(onSuccess, onFail, { quality: 50,\n destinationType: Camera.DestinationType.DATA_URL,\n sourceType: Camera.PictureSourceType.PHOTOLIBRARY\n });\n\n function onSuccess(imageURL) {\n var image = document.getElementById('myImage');\n image.src = imageURL;\n }\n\n function onFail(message) {\n alert('Failed because: ' + message);\n }\n\n}"
},
{
"code": null,
"e": 24732,
"s": 24599,
"text": "When we press the second button, the file system will open instead of the camera so we can choose the image that is to be displayed."
},
{
"code": null,
"e": 24798,
"s": 24732,
"text": "This plugin offers lots of optional parameters for customization."
},
{
"code": null,
"e": 24806,
"s": 24798,
"text": "quality"
},
{
"code": null,
"e": 24865,
"s": 24806,
"text": "Quality of the image in the range of 0-100. Default is 50."
},
{
"code": null,
"e": 24881,
"s": 24865,
"text": "destinationType"
},
{
"code": null,
"e": 24926,
"s": 24881,
"text": "DATA_URL or 0 Returns base64 encoded string."
},
{
"code": null,
"e": 24964,
"s": 24926,
"text": "FILE_URI or 1 Returns image file URI."
},
{
"code": null,
"e": 25006,
"s": 24964,
"text": "NATIVE_URI or 2 Returns image native URI."
},
{
"code": null,
"e": 25017,
"s": 25006,
"text": "sourceType"
},
{
"code": null,
"e": 25056,
"s": 25017,
"text": "PHOTOLIBRARY or 0 Opens photo library."
},
{
"code": null,
"e": 25089,
"s": 25056,
"text": "CAMERA or 1 Opens native camera."
},
{
"code": null,
"e": 25135,
"s": 25089,
"text": "SAVEDPHOTOALBUM or 2 Opens saved photo album."
},
{
"code": null,
"e": 25145,
"s": 25135,
"text": "allowEdit"
},
{
"code": null,
"e": 25167,
"s": 25145,
"text": "Allows image editing."
},
{
"code": null,
"e": 25180,
"s": 25167,
"text": "encodingType"
},
{
"code": null,
"e": 25218,
"s": 25180,
"text": "JPEG or 0 Returns JPEG encoded image."
},
{
"code": null,
"e": 25254,
"s": 25218,
"text": "PNG or 1 Returns PNG encoded image."
},
{
"code": null,
"e": 25266,
"s": 25254,
"text": "targetWidth"
},
{
"code": null,
"e": 25297,
"s": 25266,
"text": "Image scaling width in pixels."
},
{
"code": null,
"e": 25310,
"s": 25297,
"text": "targetHeight"
},
{
"code": null,
"e": 25342,
"s": 25310,
"text": "Image scaling height in pixels."
},
{
"code": null,
"e": 25352,
"s": 25342,
"text": "mediaType"
},
{
"code": null,
"e": 25396,
"s": 25352,
"text": "PICTURE or 0 Allows only picture selection."
},
{
"code": null,
"e": 25436,
"s": 25396,
"text": "VIDEO or 1 Allows only video selection."
},
{
"code": null,
"e": 25483,
"s": 25436,
"text": "ALLMEDIA or 2 Allows all media type selection."
},
{
"code": null,
"e": 25502,
"s": 25483,
"text": "correctOrientation"
},
{
"code": null,
"e": 25548,
"s": 25502,
"text": "Used for correcting orientation of the image."
},
{
"code": null,
"e": 25565,
"s": 25548,
"text": "saveToPhotoAlbum"
},
{
"code": null,
"e": 25608,
"s": 25565,
"text": "Used to save the image to the photo album."
},
{
"code": null,
"e": 25623,
"s": 25608,
"text": "popoverOptions"
},
{
"code": null,
"e": 25665,
"s": 25623,
"text": "Used for setting popover location on IOS."
},
{
"code": null,
"e": 25681,
"s": 25665,
"text": "cameraDirection"
},
{
"code": null,
"e": 25706,
"s": 25681,
"text": "FRONT or 0 Front camera."
},
{
"code": null,
"e": 25729,
"s": 25706,
"text": "BACK or 1 Back camera."
},
{
"code": null,
"e": 25738,
"s": 25729,
"text": "ALLMEDIA"
},
{
"code": null,
"e": 25885,
"s": 25738,
"text": "This plugin is used for accessing the contacts database of the device. In this tutorial we will show you how to create, query and delete contacts."
},
{
"code": null,
"e": 25969,
"s": 25885,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugincontacts\n"
},
{
"code": null,
"e": 26095,
"s": 25969,
"text": "The button will be used for calling the createContact function. We will place it in the div class = \"app\" in index.html file."
},
{
"code": null,
"e": 26247,
"s": 26095,
"text": "<button id = \"createContact\">ADD CONTACT</button>\n<button id = \"findContact\">FIND CONTACT</button>\n<button id = \"deleteContact\">DELETE CONTACT</button>"
},
{
"code": null,
"e": 26330,
"s": 26247,
"text": "Open index.js and copy the following code snippet into the onDeviceReady function."
},
{
"code": null,
"e": 26575,
"s": 26330,
"text": "document.getElementById(\"createContact\").addEventListener(\"click\", createContact);\ndocument.getElementById(\"findContact\").addEventListener(\"click\", findContact);\ndocument.getElementById(\"deleteContact\").addEventListener(\"click\", deleteContact);"
},
{
"code": null,
"e": 26630,
"s": 26575,
"text": "Now, we do not have any contacts stored on the device."
},
{
"code": null,
"e": 26950,
"s": 26630,
"text": "Our first callback function will call the navigator.contacts.create method where we can specify the new contact data. This will create a contact and assign it to the myContact variable but it will not be stored on the device. To store it, we need to call the save method and create success and error callback functions."
},
{
"code": null,
"e": 27267,
"s": 26950,
"text": "function createContact() {\n var myContact = navigator.contacts.create({\"displayName\": \"Test User\"});\n myContact.save(contactSuccess, contactError);\n \n function contactSuccess() {\n alert(\"Contact is saved!\");\n }\n\t\n function contactError(message) {\n alert('Failed because: ' + message);\n }\n\t\n}"
},
{
"code": null,
"e": 27360,
"s": 27267,
"text": "When we click the ADD CONTACT button, new contact will be stored to the device contact list."
},
{
"code": null,
"e": 27706,
"s": 27360,
"text": "Our second callback function will query all contacts. We will use the navigator.contacts.find method. The options object has filter parameter which is used to specify the search filter. multiple = true is used since we want to return all contacts from device. The field key to search contacts by displayName since we used it when saving contact."
},
{
"code": null,
"e": 27846,
"s": 27706,
"text": "After the options are set, we are using find method to query contacts. The alert message will be triggered for every contact that is found."
},
{
"code": null,
"e": 28345,
"s": 27846,
"text": "function findContacts() {\n var options = new ContactFindOptions();\n options.filter = \"\";\n options.multiple = true;\n fields = [\"displayName\"];\n navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);\n \n function contactfindSuccess(contacts) {\n for (var i = 0; i < contacts.length; i++) {\n alert(\"Display Name = \" + contacts[i].displayName);\n }\n }\n\t\n function contactfindError(message) {\n alert('Failed because: ' + message);\n }\n\t\n}"
},
{
"code": null,
"e": 28456,
"s": 28345,
"text": "When we press the FIND CONTACT button, one alert popup will be triggered since we have saved only one contact."
},
{
"code": null,
"e": 28802,
"s": 28456,
"text": "In this step, we will use the find method again but this time we will set different options. The options.filter is set to search that Test User which has to be deleted. After the contactfindSuccess callback function has returned the contact we want, we will delete it by using the remove method that requires its own success and error callbacks."
},
{
"code": null,
"e": 29476,
"s": 28802,
"text": "function deleteContact() {\n var options = new ContactFindOptions();\n options.filter = \"Test User\";\n options.multiple = false;\n fields = [\"displayName\"];\n navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);\n\n function contactfindSuccess(contacts) {\n var contact = contacts[0];\n contact.remove(contactRemoveSuccess, contactRemoveError);\n\n function contactRemoveSuccess(contact) {\n alert(\"Contact Deleted\");\n }\n\n function contactRemoveError(message) {\n alert('Failed because: ' + message);\n }\n }\n\n function contactfindError(message) {\n alert('Failed because: ' + message);\n }\n\t\n}"
},
{
"code": null,
"e": 29592,
"s": 29476,
"text": "Now, we have only one contact stored on the device. We will manually add one more to show you the deleting process."
},
{
"code": null,
"e": 29752,
"s": 29592,
"text": "We will now click the DELETE CONTACT button to delete the Test User. If we check the contact list again, we will see that the Test User does not exist anymore."
},
{
"code": null,
"e": 29821,
"s": 29752,
"text": "This plugin is used for getting information about the user’s device."
},
{
"code": null,
"e": 29905,
"s": 29821,
"text": "To install this plugin, we need to run the following snippet in the command prompt."
},
{
"code": null,
"e": 29988,
"s": 29905,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-device\n"
},
{
"code": null,
"e": 30176,
"s": 29988,
"text": "We will be using this plugin the same way we used the other Cordova plugins. Let us add a button in the index.html file. This button will be used for getting information about the device."
},
{
"code": null,
"e": 30229,
"s": 30176,
"text": "<button id = \"cordovaDevice\">CORDOVA DEVICE</button>"
},
{
"code": null,
"e": 30370,
"s": 30229,
"text": "Cordova plugins are available after the deviceready event so we will place the event listener inside the onDeviceReady function in index.js."
},
{
"code": null,
"e": 30454,
"s": 30370,
"text": "document.getElementById(\"cordovaDevice\").addEventListener(\"click\", cordovaDevice);\t"
},
{
"code": null,
"e": 30567,
"s": 30454,
"text": "The following function will show how to use all possibilities the plugin provides. We will place it in index.js."
},
{
"code": null,
"e": 30840,
"s": 30567,
"text": "function cordovaDevice() {\n alert(\"Cordova version: \" + device.cordova + \"\\n\" +\n \"Device model: \" + device.model + \"\\n\" +\n \"Device platform: \" + device.platform + \"\\n\" +\n \"Device UUID: \" + device.uuid + \"\\n\" +\n \"Device version: \" + device.version);\n}"
},
{
"code": null,
"e": 30974,
"s": 30840,
"text": "When we click the CORDOVA DEVICE button, the alert will display the Cordova version, device model, platform, UUID and device version."
},
{
"code": null,
"e": 31088,
"s": 30974,
"text": "The Accelerometer plugin is also called the device-motion. It is used to track device motion in three dimensions."
},
{
"code": null,
"e": 31192,
"s": 31088,
"text": "We will install this plugin by using cordova-CLI. Type the following code in the command prompt window."
},
{
"code": null,
"e": 31283,
"s": 31192,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-device-motion \n"
},
{
"code": null,
"e": 31454,
"s": 31283,
"text": "In this step, we will add two buttons in the index.html file. One will be used for getting the current acceleration and the other will watch for the acceleration changes."
},
{
"code": null,
"e": 31572,
"s": 31454,
"text": "<button id = \"getAcceleration\">GET ACCELERATION</button>\n<button id = \"watchAcceleration\">WATCH ACCELERATION</button>"
},
{
"code": null,
"e": 31662,
"s": 31572,
"text": "Let us now add event listeners for our buttons to onDeviceReady function inside index.js."
},
{
"code": null,
"e": 31844,
"s": 31662,
"text": "document.getElementById(\"getAcceleration\").addEventListener(\"click\", getAcceleration);\ndocument.getElementById(\"watchAcceleration\").addEventListener(\n \"click\", watchAcceleration);"
},
{
"code": null,
"e": 32301,
"s": 31844,
"text": "Now, we will create two functions. The first function will be used to get the current acceleration and the second function will watch the acceleration and the information about the acceleration will be triggered every three seconds. We will also add the clearWatch function wrapped by the setTimeout function to stop watching acceleration after the specified time frame. The frequency parameter is used to trigger the callback function every three seconds."
},
{
"code": null,
"e": 33460,
"s": 32301,
"text": "function getAcceleration() {\n navigator.accelerometer.getCurrentAcceleration(\n accelerometerSuccess, accelerometerError);\n\n function accelerometerSuccess(acceleration) {\n alert('Acceleration X: ' + acceleration.x + '\\n' +\n 'Acceleration Y: ' + acceleration.y + '\\n' +\n 'Acceleration Z: ' + acceleration.z + '\\n' +\n 'Timestamp: ' + acceleration.timestamp + '\\n');\n };\n\n function accelerometerError() {\n alert('onError!');\n };\n}\n\nfunction watchAcceleration() {\n var accelerometerOptions = {\n frequency: 3000\n }\n var watchID = navigator.accelerometer.watchAcceleration(\n accelerometerSuccess, accelerometerError, accelerometerOptions);\n\n function accelerometerSuccess(acceleration) {\n alert('Acceleration X: ' + acceleration.x + '\\n' +\n 'Acceleration Y: ' + acceleration.y + '\\n' +\n 'Acceleration Z: ' + acceleration.z + '\\n' +\n 'Timestamp: ' + acceleration.timestamp + '\\n');\n\n setTimeout(function() {\n navigator.accelerometer.clearWatch(watchID);\n }, 10000);\n };\n\n function accelerometerError() {\n alert('onError!');\n };\n\t\n}"
},
{
"code": null,
"e": 33787,
"s": 33460,
"text": "Now if we press the GET ACCELERATION button, we will get the current acceleration value. If we press the WATCH ACCELERATION button, the alert will be triggered every three seconds. After third alert is shown the clearWatch function will be called and we will not get any more alerts since we set timeout to 10000 milliseconds."
},
{
"code": null,
"e": 33866,
"s": 33787,
"text": "Compass is used to show direction relative to geographic north cardinal point."
},
{
"code": null,
"e": 33920,
"s": 33866,
"text": "Open the command prompt window and run the following."
},
{
"code": null,
"e": 34018,
"s": 33920,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin \n add cordova-plugindevice-orientation\n"
},
{
"code": null,
"e": 34114,
"s": 34018,
"text": "This plugin is similar to the acceleration plugin. Let us now create two buttons in index.html."
},
{
"code": null,
"e": 34228,
"s": 34114,
"text": "<button id = \"getOrientation\">GET ORIENTATION</button>\n<button id = \"watchOrientation\">WATCH ORIENTATION</button>"
},
{
"code": null,
"e": 34308,
"s": 34228,
"text": "Now, we will add event listeners inside the onDeviceReady function in index.js."
},
{
"code": null,
"e": 34482,
"s": 34308,
"text": "document.getElementById(\"getOrientation\").addEventListener(\"click\", getOrientation);\ndocument.getElementById(\"watchOrientation\").addEventListener(\"click\", watchOrientation);"
},
{
"code": null,
"e": 34739,
"s": 34482,
"text": "We will create two functions; the first function will generate the current acceleration and the other will check on the orientation changes. You can see that we are using the frequency option again to keep a watch on changes that occur every three seconds."
},
{
"code": null,
"e": 35486,
"s": 34739,
"text": "function getOrientation() {\n navigator.compass.getCurrentHeading(compassSuccess, compassError);\n\n function compassSuccess(heading) {\n alert('Heading: ' + heading.magneticHeading);\n };\n\n function compassError(error) {\n alert('CompassError: ' + error.code);\n };\n}\n\nfunction watchOrientation(){\n var compassOptions = {\n frequency: 3000\n }\n var watchID = navigator.compass.watchHeading(compassSuccess, \n compassError, compassOptions);\n\n function compassSuccess(heading) {\n alert('Heading: ' + heading.magneticHeading);\n\n setTimeout(function() {\n navigator.compass.clearWatch(watchID);\n }, 10000);\n };\n\n function compassError(error) {\n alert('CompassError: ' + error.code);\n };\n}"
},
{
"code": null,
"e": 35756,
"s": 35486,
"text": "Since the compass plugin is almost the same as the acceleration plugin, we will show you an error code this time. Some devices do not have the magnetic sensor that is needed for the compass to work. If your device doesn't have it, the following error will be displayed."
},
{
"code": null,
"e": 35832,
"s": 35756,
"text": "The Cordova Dialogs plugin will call the platform native dialog UI element."
},
{
"code": null,
"e": 35912,
"s": 35832,
"text": "Type the following command in the command prompt window to install this plugin."
},
{
"code": null,
"e": 35996,
"s": 35912,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-dialogs\n"
},
{
"code": null,
"e": 36075,
"s": 35996,
"text": "Let us now open index.html and add four buttons, one for every type of dialog."
},
{
"code": null,
"e": 36247,
"s": 36075,
"text": "<button id = \"dialogAlert\">ALERT</button>\n<button id = \"dialogConfirm\">CONFIRM</button>\n<button id = \"dialogPrompt\">PROMPT</button>\n<button id = \"dialogBeep\">BEEP</button>"
},
{
"code": null,
"e": 36418,
"s": 36247,
"text": "Now we will add the event listeners inside the onDeviceReady function in index.js. The listeners will call the callback function once the corresponding button is clicked."
},
{
"code": null,
"e": 36739,
"s": 36418,
"text": "document.getElementById(\"dialogAlert\").addEventListener(\"click\", dialogAlert);\ndocument.getElementById(\"dialogConfirm\").addEventListener(\"click\", dialogConfirm);\ndocument.getElementById(\"dialogPrompt\").addEventListener(\"click\", dialogPrompt);\ndocument.getElementById(\"dialogBeep\").addEventListener(\"click\", dialogBeep);\t"
},
{
"code": null,
"e": 36877,
"s": 36739,
"text": "Since we added four event listeners, we will now create the callback functions for all of them in index.js. The first one is dialogAlert."
},
{
"code": null,
"e": 37160,
"s": 36877,
"text": "function dialogAlert() {\n var message = \"I am Alert Dialog!\";\n var title = \"ALERT\";\n var buttonName = \"Alert Button\";\n navigator.notification.alert(message, alertCallback, title, buttonName);\n \n function alertCallback() {\n console.log(\"Alert is Dismissed!\");\n }\n}"
},
{
"code": null,
"e": 37228,
"s": 37160,
"text": "If we click the ALERT button, we will get see the alert dialog box."
},
{
"code": null,
"e": 37316,
"s": 37228,
"text": "When we click the dialog button, the following output will be displayed on the console."
},
{
"code": null,
"e": 37385,
"s": 37316,
"text": "The second function we need to create is the dialogConfirm function."
},
{
"code": null,
"e": 37708,
"s": 37385,
"text": "function dialogConfirm() {\n var message = \"Am I Confirm Dialog?\";\n var title = \"CONFIRM\";\n var buttonLabels = \"YES,NO\";\n navigator.notification.confirm(message, confirmCallback, title, buttonLabels);\n\n function confirmCallback(buttonIndex) {\n console.log(\"You clicked \" + buttonIndex + \" button!\");\n }\n\t\n}"
},
{
"code": null,
"e": 37772,
"s": 37708,
"text": "When the CONFIRM button is pressed, the new dialog will pop up."
},
{
"code": null,
"e": 37880,
"s": 37772,
"text": "We will click the YES button to answer the question. The following output will be displayed on the console."
},
{
"code": null,
"e": 37995,
"s": 37880,
"text": "The third function is the dialogPrompt function. This allows the users to type text into the dialog input element."
},
{
"code": null,
"e": 38416,
"s": 37995,
"text": "function dialogPrompt() {\n var message = \"Am I Prompt Dialog?\";\n var title = \"PROMPT\";\n var buttonLabels = [\"YES\",\"NO\"];\n var defaultText = \"Default\"\n navigator.notification.prompt(message, promptCallback, \n title, buttonLabels, defaultText);\n\n function promptCallback(result) {\n console.log(\"You clicked \" + result.buttonIndex + \" button! \\n\" + \n \"You entered \" + result.input1);\n }\n\t\n}"
},
{
"code": null,
"e": 38492,
"s": 38416,
"text": "The PROMPT button will trigger a dialog box as in the following screenshot."
},
{
"code": null,
"e": 38626,
"s": 38492,
"text": "In this dialog box, we have an option to type the text. We will log this text in the console, together with a button that is clicked."
},
{
"code": null,
"e": 38793,
"s": 38626,
"text": "The last one is the dialogBeep function. This is used for calling the audio beep notification. The times parameter will set the number of repeats for the beep signal."
},
{
"code": null,
"e": 38876,
"s": 38793,
"text": "function dialogBeep() {\n var times = 2;\n navigator.notification.beep(times);\n}"
},
{
"code": null,
"e": 38985,
"s": 38876,
"text": "When we click the BEEP button, we will hear the notification sound twice, since the times value is set to 2."
},
{
"code": null,
"e": 39067,
"s": 38985,
"text": "This plugin is used for manipulating the native file system on the user's device."
},
{
"code": null,
"e": 39147,
"s": 39067,
"text": "We need to run the following code in the command prompt to install this plugin."
},
{
"code": null,
"e": 39228,
"s": 39147,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-file\n"
},
{
"code": null,
"e": 39454,
"s": 39228,
"text": "In this example, we will show you how to create file, write to file, read it and delete it. For this reason, we will create four buttons in index.html. We will also add textarea wherein, the content of our file will be shown."
},
{
"code": null,
"e": 39674,
"s": 39454,
"text": "<button id = \"createFile\">CREATE FILE</button>\n<button id = \"writeFile\">WRITE FILE</button>\n<button id = \"readFile\">READ FILE</button>\n<button id = \"removeFile\">DELETE FILE</button>\n<textarea id = \"textarea\"></textarea>"
},
{
"code": null,
"e": 39813,
"s": 39674,
"text": "We will add event listeners in index.js inside the onDeviceReady function to ensure that everything has started before the plugin is used."
},
{
"code": null,
"e": 40115,
"s": 39813,
"text": "document.getElementById(\"createFile\").addEventListener(\"click\", createFile);\ndocument.getElementById(\"writeFile\").addEventListener(\"click\", writeFile);\ndocument.getElementById(\"readFile\").addEventListener(\"click\", readFile);\ndocument.getElementById(\"removeFile\").addEventListener(\"click\", removeFile);"
},
{
"code": null,
"e": 40382,
"s": 40115,
"text": "The file will be created in the apps root folder on the device. To be able to access the root folder you need to provide superuser access to your folders. In our case, the path to root folder is \\data\\data\\com.example.hello\\cache. At the moment this folder is empty."
},
{
"code": null,
"e": 40655,
"s": 40382,
"text": "Let us now add a function that will create the log.txt file. We will write this code in index.js and send a request to the file system. This method uses WINDOW.TEMPORARY or WINDOW.PERSISTENT. The size that will be required for storage is valued in bytes (5MB in our case)."
},
{
"code": null,
"e": 41089,
"s": 40655,
"text": "function createFile() {\n var type = window.TEMPORARY;\n var size = 5*1024*1024;\n window.requestFileSystem(type, size, successCallback, errorCallback)\n\n function successCallback(fs) {\n fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {\n alert('File creation successfull!')\n }, errorCallback);\n }\n\n function errorCallback(error) {\n alert(\"ERROR: \" + error.code)\n }\n\t\n}"
},
{
"code": null,
"e": 41195,
"s": 41089,
"text": "Now we can press the CREATE FILE button and the alert will confirm that we successfully created the file."
},
{
"code": null,
"e": 41276,
"s": 41195,
"text": "Now, we can check our apps root folder again and we can find our new file there."
},
{
"code": null,
"e": 41484,
"s": 41276,
"text": "In this step, we will write some text to our file. We will again send a request to the file system, and then create the file writer to be able to write Lorem Ipsum text that we assigned to the blob variable."
},
{
"code": null,
"e": 42271,
"s": 41484,
"text": "function writeFile() {\n var type = window.TEMPORARY;\n var size = 5*1024*1024;\n window.requestFileSystem(type, size, successCallback, errorCallback)\n\n function successCallback(fs) {\n fs.root.getFile('log.txt', {create: true}, function(fileEntry) {\n\n fileEntry.createWriter(function(fileWriter) {\n fileWriter.onwriteend = function(e) {\n alert('Write completed.');\n };\n\n fileWriter.onerror = function(e) {\n alert('Write failed: ' + e.toString());\n };\n\n var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});\n fileWriter.write(blob);\n }, errorCallback);\n }, errorCallback);\n }\n\n function errorCallback(error) {\n alert(\"ERROR: \" + error.code)\n }\n}"
},
{
"code": null,
"e": 42397,
"s": 42271,
"text": "After pressing the WRITE FILE button, the alert will inform us that the writing is successful as in the following screenshot."
},
{
"code": null,
"e": 42465,
"s": 42397,
"text": "Now we can open log.txt and see that Lorem Ipsum is written inside."
},
{
"code": null,
"e": 42719,
"s": 42465,
"text": "In this step, we will read the log.txt file and display it in the textarea element. We will send a request to the file system and get the file object, then we are creating reader. When the reader is loaded, we will assign the returned value to textarea."
},
{
"code": null,
"e": 43397,
"s": 42719,
"text": "function readFile() {\n var type = window.TEMPORARY;\n var size = 5*1024*1024;\n window.requestFileSystem(type, size, successCallback, errorCallback)\n\n function successCallback(fs) {\n fs.root.getFile('log.txt', {}, function(fileEntry) {\n\n fileEntry.file(function(file) {\n var reader = new FileReader();\n\n reader.onloadend = function(e) {\n var txtArea = document.getElementById('textarea');\n txtArea.value = this.result;\n };\n reader.readAsText(file);\n }, errorCallback);\n }, errorCallback);\n }\n\n function errorCallback(error) {\n alert(\"ERROR: \" + error.code)\n }\n}\t"
},
{
"code": null,
"e": 43489,
"s": 43397,
"text": "When we click the READ FILE button, the text from the file will be written inside textarea."
},
{
"code": null,
"e": 43552,
"s": 43489,
"text": "And finally we will create function for deleting log.txt file."
},
{
"code": null,
"e": 44028,
"s": 43552,
"text": "function removeFile() {\n var type = window.TEMPORARY;\n var size = 5*1024*1024;\n window.requestFileSystem(type, size, successCallback, errorCallback)\n\n function successCallback(fs) {\n fs.root.getFile('log.txt', {create: false}, function(fileEntry) {\n\n fileEntry.remove(function() {\n alert('File removed.');\n }, errorCallback);\n }, errorCallback);\n }\n\n function errorCallback(error) {\n alert(\"ERROR: \" + error.code)\n }\n}\t"
},
{
"code": null,
"e": 44180,
"s": 44028,
"text": "We can now press the DELETE FILE button to remove the file from the apps root folder. The alert will notify us that the delete operation is successful."
},
{
"code": null,
"e": 44244,
"s": 44180,
"text": "If we check the apps root folder, we will see that it is empty."
},
{
"code": null,
"e": 44301,
"s": 44244,
"text": "This plugin is used for uploading and downloading files."
},
{
"code": null,
"e": 44385,
"s": 44301,
"text": "We need to open command prompt and run the following command to install the plugin."
},
{
"code": null,
"e": 44475,
"s": 44385,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-file-transfer\n"
},
{
"code": null,
"e": 44582,
"s": 44475,
"text": "In this chapter, we will show you how to upload and download files. Let's create two buttons in index.html"
},
{
"code": null,
"e": 44670,
"s": 44582,
"text": "<button id = \"uploadFile\">UPLOAD</button>\n<button id = \"downloadFile\">DOWNLOAD</button>"
},
{
"code": null,
"e": 44800,
"s": 44670,
"text": "Event listeners will be created in index.js inside the onDeviceReady function. We are adding click events and callback functions."
},
{
"code": null,
"e": 44958,
"s": 44800,
"text": "document.getElementById(\"uploadFile\").addEventListener(\"click\", uploadFile);\ndocument.getElementById(\"downloadFile\").addEventListener(\"click\", downloadFile);"
},
{
"code": null,
"e": 45332,
"s": 44958,
"text": "This function will be used for downloading the files from server to device. We uploaded file to postimage.org to make things more simple. You will probably want to use your own server. The function is placed in index.js and will be triggered when the corresponding button is pressed. uri is the server download link and fileURI is the path to the DCIM folder on our device."
},
{
"code": null,
"e": 46022,
"s": 45332,
"text": "function downloadFile() {\n var fileTransfer = new FileTransfer();\n var uri = encodeURI(\"http://s14.postimg.org/i8qvaxyup/bitcoin1.jpg\");\n var fileURL = \"///storage/emulated/0/DCIM/myFile\";\n\n fileTransfer.download(\n uri, fileURL, function(entry) {\n console.log(\"download complete: \" + entry.toURL());\n },\n\t\t\n function(error) {\n console.log(\"download error source \" + error.source);\n console.log(\"download error target \" + error.target);\n console.log(\"download error code\" + error.code);\n },\n\t\t\n false, {\n headers: {\n \"Authorization\": \"Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==\"\n }\n }\n );\n}"
},
{
"code": null,
"e": 46199,
"s": 46022,
"text": "Once we press the DOWNLOAD button, the file will be downloaded from the postimg.org server to our mobile device. We can check the specified folder and see that myFile is there."
},
{
"code": null,
"e": 46240,
"s": 46199,
"text": "The console output will look like this −"
},
{
"code": null,
"e": 46495,
"s": 46240,
"text": "Now let's create a function that will take the file and upload it to the server. Again, we want to simplify this as much as possible, so we will use posttestserver.com online server for testing. The uri value will be linked for posting to posttestserver."
},
{
"code": null,
"e": 47364,
"s": 46495,
"text": "function uploadFile() {\n var fileURL = \"///storage/emulated/0/DCIM/myFile\"\n var uri = encodeURI(\"http://posttestserver.com/post.php\");\n var options = new FileUploadOptions();\n options.fileKey = \"file\";\n options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1);\n options.mimeType = \"text/plain\";\n \n var headers = {'headerParam':'headerValue'};\n options.headers = headers;\n var ft = new FileTransfer();\n ft.upload(fileURL, uri, onSuccess, onError, options);\n\n function onSuccess(r) {\n console.log(\"Code = \" + r.responseCode);\n console.log(\"Response = \" + r.response);\n console.log(\"Sent = \" + r.bytesSent);\n }\n\n function onError(error) {\n alert(\"An error has occurred: Code = \" + error.code);\n console.log(\"upload error source \" + error.source);\n console.log(\"upload error target \" + error.target);\n }\n\t\n}"
},
{
"code": null,
"e": 47505,
"s": 47364,
"text": "Now we can press the UPLOAD button to trigger this function. We will get a console output as confirmation that the uploading was successful."
},
{
"code": null,
"e": 47575,
"s": 47505,
"text": "We can also check the server to make sure that the file was uploaded."
},
{
"code": null,
"e": 47651,
"s": 47575,
"text": "Geolocation is used for getting info about device's latitude and longitude."
},
{
"code": null,
"e": 47733,
"s": 47651,
"text": "We can install this plugin by typing the following code to command prompt window."
},
{
"code": null,
"e": 47821,
"s": 47733,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-geolocation\n"
},
{
"code": null,
"e": 47977,
"s": 47821,
"text": "In this tutorial we will show you how to get current position and how to watch for changes. We first need to create buttons that will call these functions."
},
{
"code": null,
"e": 48083,
"s": 47977,
"text": "<button id = \"getPosition\">CURRENT POSITION</button>\n<button id = \"watchPosition\">WATCH POSITION</button>"
},
{
"code": null,
"e": 48217,
"s": 48083,
"text": "Now we want to add event listeners when the device is ready. We will add the code sample below to onDeviceReady function in index.js."
},
{
"code": null,
"e": 48380,
"s": 48217,
"text": "document.getElementById(\"getPosition\").addEventListener(\"click\", getPosition);\ndocument.getElementById(\"watchPosition\").addEventListener(\"click\", watchPosition);\t"
},
{
"code": null,
"e": 48529,
"s": 48380,
"text": "Two functions have to be created for two event listeners. One will be used for getting the current position and the other for watching the position."
},
{
"code": null,
"e": 50488,
"s": 48529,
"text": "function getPosition() {\n var options = {\n enableHighAccuracy: true,\n maximumAge: 3600000\n }\n var watchID = navigator.geolocation.getCurrentPosition(onSuccess, onError, options);\n\n function onSuccess(position) {\n alert('Latitude: ' + position.coords.latitude + '\\n' +\n 'Longitude: ' + position.coords.longitude + '\\n' +\n 'Altitude: ' + position.coords.altitude + '\\n' +\n 'Accuracy: ' + position.coords.accuracy + '\\n' +\n 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\\n' +\n 'Heading: ' + position.coords.heading + '\\n' +\n 'Speed: ' + position.coords.speed + '\\n' +\n 'Timestamp: ' + position.timestamp + '\\n');\n };\n\n function onError(error) {\n alert('code: ' + error.code + '\\n' + 'message: ' + error.message + '\\n');\n }\n}\n\nfunction watchPosition() {\n var options = {\n maximumAge: 3600000,\n timeout: 3000,\n enableHighAccuracy: true,\n }\n var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);\n\n function onSuccess(position) {\n alert('Latitude: ' + position.coords.latitude + '\\n' +\n 'Longitude: ' + position.coords.longitude + '\\n' +\n 'Altitude: ' + position.coords.altitude + '\\n' +\n 'Accuracy: ' + position.coords.accuracy + '\\n' +\n 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\\n' +\n 'Heading: ' + position.coords.heading + '\\n' +\n 'Speed: ' + position.coords.speed + '\\n' +\n 'Timestamp: ' + position.timestamp + '\\n');\n };\n\n function onError(error) {\n alert('code: ' + error.code + '\\n' +'message: ' + error.message + '\\n');\n }\n}"
},
{
"code": null,
"e": 50692,
"s": 50488,
"text": "In example above we are using two methods − getCurrentPosition and watchPosition. Both functions are using three parameters. Once we click CURRENT POSITION button, the alert will show geolocation values."
},
{
"code": null,
"e": 50842,
"s": 50692,
"text": "If we click WATCH POSITION button, the same alert will be triggered every three seconds. This way we can track movement changes of the user's device."
},
{
"code": null,
"e": 51194,
"s": 50842,
"text": "This plugin is using GPS. Sometimes it can't return the values on time and the request will return timeout error. This is why we specified enableHighAccuracy: true and maximumAge: 3600000. This means that if a request isn't completed on time, we will use the last known value instead. In our example, we are setting maximumAge to 3600000 milliseconds."
},
{
"code": null,
"e": 51303,
"s": 51194,
"text": "This plugin is used for getting information about users’ locale language, date and time zone, currency, etc."
},
{
"code": null,
"e": 51375,
"s": 51303,
"text": "Open command prompt and install the plugin by typing the following code"
},
{
"code": null,
"e": 51465,
"s": 51375,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-globalization\n"
},
{
"code": null,
"e": 51571,
"s": 51465,
"text": "We will add several buttons to index.html to be able to call different methods that we will create later."
},
{
"code": null,
"e": 51748,
"s": 51571,
"text": "<button id = \"getLanguage\">LANGUAGE</button>\n<button id = \"getLocaleName\">LOCALE NAME</button>\n<button id = \"getDate\">DATE</button>\n<button id = \"getCurrency\">CURRENCY</button>"
},
{
"code": null,
"e": 51898,
"s": 51748,
"text": "Event listeners will be added inside getDeviceReady function in index.js file to ensure that our app and Cordova are loaded before we start using it."
},
{
"code": null,
"e": 52210,
"s": 51898,
"text": "document.getElementById(\"getLanguage\").addEventListener(\"click\", getLanguage);\ndocument.getElementById(\"getLocaleName\").addEventListener(\"click\", getLocaleName);\ndocument.getElementById(\"getDate\").addEventListener(\"click\", getDate);\ndocument.getElementById(\"getCurrency\").addEventListener(\"click\", getCurrency);"
},
{
"code": null,
"e": 52436,
"s": 52210,
"text": "The first function that we are using returns BCP 47 language tag of the client's device. We will use getPreferredLanguage method. The function has two parameters onSuccess and onError. We are adding this function in index.js."
},
{
"code": null,
"e": 52691,
"s": 52436,
"text": "function getLanguage() {\n navigator.globalization.getPreferredLanguage(onSuccess, onError);\n\n function onSuccess(language) {\n alert('language: ' + language.value + '\\n');\n }\n\n function onError(){\n alert('Error getting language');\n }\n}"
},
{
"code": null,
"e": 52761,
"s": 52691,
"text": "Once we press the LANGUAGE button, the alert will be shown on screen."
},
{
"code": null,
"e": 52955,
"s": 52761,
"text": "This function returns BCP 47 tag for the client's local settings. This function is similar as the one we created before. The only difference is that we are using getLocaleName method this time."
},
{
"code": null,
"e": 53190,
"s": 52955,
"text": "function getLocaleName() {\n navigator.globalization.getLocaleName(onSuccess, onError);\n\n function onSuccess(locale) {\n alert('locale: ' + locale.value);\n }\n\n function onError(){\n alert('Error getting locale');\n }\n}"
},
{
"code": null,
"e": 53259,
"s": 53190,
"text": "When we click the LOCALE button, the alert will show our locale tag."
},
{
"code": null,
"e": 53421,
"s": 53259,
"text": "This function is used for returning date according to client's locale and timezone setting. date parameter is the current date and options parameter is optional."
},
{
"code": null,
"e": 53772,
"s": 53421,
"text": "function getDate() {\n var date = new Date();\n\n var options = {\n formatLength:'short',\n selector:'date and time'\n }\n navigator.globalization.dateToString(date, onSuccess, onError, options);\n\n function onSuccess(date) {\n alert('date: ' + date.value);\n }\n\n function onError(){\n alert('Error getting dateString');\n }\n}"
},
{
"code": null,
"e": 53842,
"s": 53772,
"text": "We can now run the app and press DATE button to see the current date."
},
{
"code": null,
"e": 54015,
"s": 53842,
"text": "The last function that we will show is returning currency values according to client's device settings and ISO 4217 currency code. You can see that the concept is the same."
},
{
"code": null,
"e": 54554,
"s": 54015,
"text": "function getCurrency() {\n var currencyCode = 'EUR';\n navigator.globalization.getCurrencyPattern(currencyCode, onSuccess, onError);\n\n function onSuccess(pattern) {\n alert('pattern: ' + pattern.pattern + '\\n' +\n 'code: ' + pattern.code + '\\n' +\n 'fraction: ' + pattern.fraction + '\\n' +\n 'rounding: ' + pattern.rounding + '\\n' +\n 'decimal: ' + pattern.decimal + '\\n' +\n 'grouping: ' + pattern.grouping);\n }\n\n function onError(){\n alert('Error getting pattern');\n }\n}"
},
{
"code": null,
"e": 54632,
"s": 54554,
"text": "The CURRENCY button will trigger alert that will show users currency pattern."
},
{
"code": null,
"e": 54708,
"s": 54632,
"text": "This plugin offers other methods. You can see all of it in the table below."
},
{
"code": null,
"e": 54772,
"s": 54708,
"text": "This plugin is used for opening web browser inside Cordova app."
},
{
"code": null,
"e": 54858,
"s": 54772,
"text": "We need to install this plugin in command prompt window before we are able to use it."
},
{
"code": null,
"e": 54947,
"s": 54858,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-inappbrowser\n"
},
{
"code": null,
"e": 55035,
"s": 54947,
"text": "We will add one button that will be used for opening inAppBrowser window in index.html."
},
{
"code": null,
"e": 55118,
"s": 55035,
"text": "Now let's add event listener for our button in onDeviceReady function in index.js."
},
{
"code": null,
"e": 55197,
"s": 55118,
"text": "document.getElementById(\"openBrowser\").addEventListener(\"click\", openBrowser);"
},
{
"code": null,
"e": 55360,
"s": 55197,
"text": "In this step we are creating function that will open browser inside our app. We are assigning it to the ref variable that we can use later to add event listeners."
},
{
"code": null,
"e": 56140,
"s": 55360,
"text": "function openBrowser() {\n var url = 'https://cordova.apache.org';\n var target = '_blank';\n var options = \"location = yes\"\n var ref = cordova.InAppBrowser.open(url, target, options);\n \n ref.addEventListener('loadstart', loadstartCallback);\n ref.addEventListener('loadstop', loadstopCallback);\n ref.addEventListener('loaderror', loaderrorCallback);\n ref.addEventListener('exit', exitCallback);\n\n function loadstartCallback(event) {\n console.log('Loading started: ' + event.url)\n }\n\n function loadstopCallback(event) {\n console.log('Loading finished: ' + event.url)\n }\n\n function loaderrorCallback(error) {\n console.log('Loading error: ' + error.message)\n }\n\n function exitCallback() {\n console.log('Browser is closed...')\n }\n}"
},
{
"code": null,
"e": 56212,
"s": 56140,
"text": "If we press BROWSER button, we will see the following output on screen."
},
{
"code": null,
"e": 56371,
"s": 56212,
"text": "Console will also listen to events. loadstart event will fire when URL is started loading and loadstop will fire when URL is loaded. We can see it in console."
},
{
"code": null,
"e": 56420,
"s": 56371,
"text": "Once we close the browser, exit event will fire."
},
{
"code": null,
"e": 56517,
"s": 56420,
"text": "There are other possible options for InAppBrowser window. We will explain it in the table below."
},
{
"code": null,
"e": 56526,
"s": 56517,
"text": "location"
},
{
"code": null,
"e": 56597,
"s": 56526,
"text": "Used to turn the browser location bar on or off. Values are yes or no."
},
{
"code": null,
"e": 56604,
"s": 56597,
"text": "hidden"
},
{
"code": null,
"e": 56661,
"s": 56604,
"text": "Used to hide or show inAppBrowser. Values are yes or no."
},
{
"code": null,
"e": 56672,
"s": 56661,
"text": "clearCache"
},
{
"code": null,
"e": 56730,
"s": 56672,
"text": "Used to clear browser cookie cache. Values are yes or no."
},
{
"code": null,
"e": 56748,
"s": 56730,
"text": "clearsessioncache"
},
{
"code": null,
"e": 56806,
"s": 56748,
"text": "Used to clear session cookie cache. Values are yes or no."
},
{
"code": null,
"e": 56811,
"s": 56806,
"text": "zoom"
},
{
"code": null,
"e": 56887,
"s": 56811,
"text": "Used to hide or show Android browser's zoom controls. Values are yes or no."
},
{
"code": null,
"e": 56900,
"s": 56887,
"text": "hardwareback"
},
{
"code": null,
"e": 57035,
"s": 56900,
"text": "yes to use the hardware back button to navigate back through the browser history. no to close the browser once back button is clicked."
},
{
"code": null,
"e": 57189,
"s": 57035,
"text": "We can use ref (reference) variable for some other functionalities. We will show you just quick examples of it. For removing event listeners we can use −"
},
{
"code": null,
"e": 57237,
"s": 57189,
"text": "ref.removeEventListener(eventname, callback); \n"
},
{
"code": null,
"e": 57275,
"s": 57237,
"text": "For closing InAppBrowser we can use −"
},
{
"code": null,
"e": 57289,
"s": 57275,
"text": "ref.close();\n"
},
{
"code": null,
"e": 57334,
"s": 57289,
"text": "If we opened hidden window, we can show it −"
},
{
"code": null,
"e": 57347,
"s": 57334,
"text": "ref.show();\n"
},
{
"code": null,
"e": 57406,
"s": 57347,
"text": "Even JavaScript code can be injected to the InAppBrowser −"
},
{
"code": null,
"e": 57481,
"s": 57406,
"text": "var details = \"javascript/file/url\"\nref.executeScript(details, callback);\n"
},
{
"code": null,
"e": 57530,
"s": 57481,
"text": "The same concept can be used for injecting CSS −"
},
{
"code": null,
"e": 57593,
"s": 57530,
"text": "var details = \"css/file/url\"\nref.inserCSS(details, callback);\n"
},
{
"code": null,
"e": 57678,
"s": 57593,
"text": "Cordova media plugin is used for recording and playing audio sounds in Cordova apps."
},
{
"code": null,
"e": 57764,
"s": 57678,
"text": "Media plugin can be installed by running the following code in command prompt window."
},
{
"code": null,
"e": 57846,
"s": 57764,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-media\n"
},
{
"code": null,
"e": 57949,
"s": 57846,
"text": "In this tutorial, we will create simple audio player. Let's create buttons that we need in index.html."
},
{
"code": null,
"e": 58158,
"s": 57949,
"text": "<button id = \"playAudio\">PLAY</button>\n<button id = \"pauseAudio\">PAUSE</button>\n<button id = \"stopAudio\">STOP</button>\n<button id = \"volumeUp\">VOLUME UP</button>\n<button id = \"volumeDown\">VOLUME DOWN</button>"
},
{
"code": null,
"e": 58256,
"s": 58158,
"text": "Now we need to add event listeners for our buttons inside onDeviceReady function inside index.js."
},
{
"code": null,
"e": 58633,
"s": 58256,
"text": "document.getElementById(\"playAudio\").addEventListener(\"click\", playAudio);\ndocument.getElementById(\"pauseAudio\").addEventListener(\"click\", pauseAudio);\ndocument.getElementById(\"stopAudio\").addEventListener(\"click\", stopAudio);\ndocument.getElementById(\"volumeUp\").addEventListener(\"click\", volumeUp);\ndocument.getElementById(\"volumeDown\").addEventListener(\"click\", volumeDown);"
},
{
"code": null,
"e": 58889,
"s": 58633,
"text": "The first function that we are going to add is playAudio. We are defining myMedia outside of the function because we want to use it in functions that are going to be added later (pause, stop, volumeUp and volumeDown). This code is placed in index.js file."
},
{
"code": null,
"e": 59266,
"s": 58889,
"text": "var myMedia = null;\nfunction playAudio() {\n var src = \"/android_asset/www/audio/piano.mp3\";\n\n if(myMedia === null) {\n myMedia = new Media(src, onSuccess, onError);\n\n function onSuccess() {\n console.log(\"playAudio Success\");\n }\n\n function onError(error) {\n console.log(\"playAudio Error: \" + error.code);\n }\n }\n myMedia.play();\n}"
},
{
"code": null,
"e": 59335,
"s": 59266,
"text": "We can click PLAY button to start the piano music from the src path."
},
{
"code": null,
"e": 59396,
"s": 59335,
"text": "The next functions that we need is pauseAudio and stopAudio."
},
{
"code": null,
"e": 59557,
"s": 59396,
"text": "function pauseAudio() {\n if(myMedia) {\n myMedia.pause();\n }\n}\n\nfunction stopAudio() {\n if(myMedia) {\n myMedia.stop(); \n }\n myMedia = null;\n}"
},
{
"code": null,
"e": 59633,
"s": 59557,
"text": "Now we can pause or stop the piano sound by clicking PAUSE or STOP buttons."
},
{
"code": null,
"e": 59769,
"s": 59633,
"text": "To set the volume, we can use setVolume method. This method takes parameter with values from 0 to 1. We will set starting value to 0.5."
},
{
"code": null,
"e": 60015,
"s": 59769,
"text": "var volumeValue = 0.5;\nfunction volumeUp() {\n if(myMedia && volumeValue < 1) {\n myMedia.setVolume(volumeValue += 0.1);\n }\n}\n\nfunction volumeDown() {\n if(myMedia && volumeValue > 0) {\n myMedia.setVolume(volumeValue -= 0.1);\n }\n}"
},
{
"code": null,
"e": 60093,
"s": 60015,
"text": "Once we press VOLUME UP or VOLUME DOWN we can change the volume value by 0.1."
},
{
"code": null,
"e": 60160,
"s": 60093,
"text": "The following table shows other methods that this plugin provides."
},
{
"code": null,
"e": 60179,
"s": 60160,
"text": "getCurrentPosition"
},
{
"code": null,
"e": 60217,
"s": 60179,
"text": "Returns current position of an audio."
},
{
"code": null,
"e": 60229,
"s": 60217,
"text": "getDuration"
},
{
"code": null,
"e": 60259,
"s": 60229,
"text": "Returns duration of an audio."
},
{
"code": null,
"e": 60264,
"s": 60259,
"text": "play"
},
{
"code": null,
"e": 60301,
"s": 60264,
"text": "Used for starting or resuming audio."
},
{
"code": null,
"e": 60307,
"s": 60301,
"text": "pause"
},
{
"code": null,
"e": 60331,
"s": 60307,
"text": "Used for pausing audio."
},
{
"code": null,
"e": 60339,
"s": 60331,
"text": "release"
},
{
"code": null,
"e": 60399,
"s": 60339,
"text": "Releases the underlying operating system's audio resources."
},
{
"code": null,
"e": 60406,
"s": 60399,
"text": "seekTo"
},
{
"code": null,
"e": 60446,
"s": 60406,
"text": "Used for changing position of an audio."
},
{
"code": null,
"e": 60456,
"s": 60446,
"text": "setVolume"
},
{
"code": null,
"e": 60491,
"s": 60456,
"text": "Used for setting volume for audio."
},
{
"code": null,
"e": 60503,
"s": 60491,
"text": "startRecord"
},
{
"code": null,
"e": 60534,
"s": 60503,
"text": "Start recording an audio file."
},
{
"code": null,
"e": 60545,
"s": 60534,
"text": "stopRecord"
},
{
"code": null,
"e": 60575,
"s": 60545,
"text": "Stop recording an audio file."
},
{
"code": null,
"e": 60580,
"s": 60575,
"text": "stop"
},
{
"code": null,
"e": 60608,
"s": 60580,
"text": "Stop playing an audio file."
},
{
"code": null,
"e": 60668,
"s": 60608,
"text": "This plugin is used for accessing device's capture options."
},
{
"code": null,
"e": 60749,
"s": 60668,
"text": "To install this plugin, we will open command prompt and run the following code −"
},
{
"code": null,
"e": 60839,
"s": 60749,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-media-capture\n"
},
{
"code": null,
"e": 60948,
"s": 60839,
"text": "Since we want to show you how to capture audio, image and video, we will create three buttons in index.html."
},
{
"code": null,
"e": 61077,
"s": 60948,
"text": "<button id = \"audioCapture\">AUDIO</button>\n<button id = \"imageCapture\">IMAGE</button>\n<button id = \"videoCapture\">VIDEO</button>"
},
{
"code": null,
"e": 61151,
"s": 61077,
"text": "The next step is adding event listeners inside onDeviceReady in index.js."
},
{
"code": null,
"e": 61394,
"s": 61151,
"text": "document.getElementById(\"audioCapture\").addEventListener(\"click\", audioCapture);\ndocument.getElementById(\"imageCapture\").addEventListener(\"click\", imageCapture);\ndocument.getElementById(\"videoCapture\").addEventListener(\"click\", videoCapture);"
},
{
"code": null,
"e": 61663,
"s": 61394,
"text": "The first callback function in index.js is audioCapture. To start sound recorder, we will use captureAudio method. We are using two options − limit will allow recording only one audio clip per single capture operation and duration is number of seconds of a sound clip."
},
{
"code": null,
"e": 62155,
"s": 61663,
"text": "function audioCapture() {\n var options = {\n limit: 1,\n duration: 10\n };\n navigator.device.capture.captureAudio(onSuccess, onError, options);\n\n function onSuccess(mediaFiles) {\n var i, path, len;\n for (i = 0, len = mediaFiles.length; i < len; i += 1) {\n path = mediaFiles[i].fullPath;\n console.log(mediaFiles);\n }\n }\n\n function onError(error) {\n navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');\n }\n}"
},
{
"code": null,
"e": 62209,
"s": 62155,
"text": "When we press AUDIO button, sound recorder will open."
},
{
"code": null,
"e": 62274,
"s": 62209,
"text": "Console will show returned array of objects that users captured."
},
{
"code": null,
"e": 62413,
"s": 62274,
"text": "The function for capturing image will be the same as the last one. The only difference is that we are using captureImage method this time."
},
{
"code": null,
"e": 62885,
"s": 62413,
"text": "function imageCapture() {\n var options = {\n limit: 1\n };\n navigator.device.capture.captureImage(onSuccess, onError, options);\n\n function onSuccess(mediaFiles) {\n var i, path, len;\n for (i = 0, len = mediaFiles.length; i < len; i += 1) {\n path = mediaFiles[i].fullPath;\n console.log(mediaFiles);\n }\n }\n\n function onError(error) {\n navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');\n }\n}"
},
{
"code": null,
"e": 62936,
"s": 62885,
"text": "Now we can click IMAGE button to start the camera."
},
{
"code": null,
"e": 63008,
"s": 62936,
"text": "When we take picture, the console will log the array with image object."
},
{
"code": null,
"e": 63102,
"s": 63008,
"text": "Let's repeat the same concept for capturing video. We will use videoCapture method this time."
},
{
"code": null,
"e": 63594,
"s": 63102,
"text": "function videoCapture() {\n var options = {\n limit: 1,\n duration: 10\n };\n navigator.device.capture.captureVideo(onSuccess, onError, options);\n\n function onSuccess(mediaFiles) {\n var i, path, len;\n for (i = 0, len = mediaFiles.length; i < len; i += 1) {\n path = mediaFiles[i].fullPath;\n console.log(mediaFiles);\n }\n }\n\n function onError(error) {\n navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');\n }\n}"
},
{
"code": null,
"e": 63670,
"s": 63594,
"text": "If we press VIDEO button, the camera will open and we can record the video."
},
{
"code": null,
"e": 63772,
"s": 63670,
"text": "Once the video is saved, the console will return array once more. This time with video object inside."
},
{
"code": null,
"e": 63829,
"s": 63772,
"text": "This plugin provides information about device's network."
},
{
"code": null,
"e": 63910,
"s": 63829,
"text": "To install this plugin, we will open command prompt and run the following code −"
},
{
"code": null,
"e": 64010,
"s": 63910,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin \n add cordova-plugin-network-information\n"
},
{
"code": null,
"e": 64098,
"s": 64010,
"text": "Let's create one button in index.html that will be used for getting info about network."
},
{
"code": null,
"e": 64139,
"s": 64098,
"text": "<button id = \"networkInfo\">INFO</button>"
},
{
"code": null,
"e": 64339,
"s": 64139,
"text": "We will add three event listeners inside onDeviceReady function in index.js. One will listen for clicks on the button we created before and the other two will listen for changes in connection status."
},
{
"code": null,
"e": 64528,
"s": 64339,
"text": "document.getElementById(\"networkInfo\").addEventListener(\"click\", networkInfo);\ndocument.addEventListener(\"offline\", onOffline, false);\ndocument.addEventListener(\"online\", onOnline, false);"
},
{
"code": null,
"e": 64816,
"s": 64528,
"text": "networkInfo function will return info about current network connection once button is clicked. We are calling type method. The other functions are onOffline and onOnline. These functions are listening to the connection changes and any change will trigger the corresponding alert message."
},
{
"code": null,
"e": 65530,
"s": 64816,
"text": "function networkInfo() {\n var networkState = navigator.connection.type;\n var states = {};\n states[Connection.UNKNOWN] = 'Unknown connection';\n states[Connection.ETHERNET] = 'Ethernet connection';\n states[Connection.WIFI] = 'WiFi connection';\n states[Connection.CELL_2G] = 'Cell 2G connection';\n states[Connection.CELL_3G] = 'Cell 3G connection';\n states[Connection.CELL_4G] = 'Cell 4G connection';\n states[Connection.CELL] = 'Cell generic connection';\n states[Connection.NONE] = 'No network connection';\n alert('Connection type: ' + states[networkState]);\n}\n\nfunction onOffline() {\n alert('You are now offline!');\n}\n\nfunction onOnline() {\n alert('You are now online!');\n}"
},
{
"code": null,
"e": 65616,
"s": 65530,
"text": "When we start the app connected to the network, onOnline function will trigger alert."
},
{
"code": null,
"e": 65679,
"s": 65616,
"text": "If we press INFO button the alert will show our network state."
},
{
"code": null,
"e": 65749,
"s": 65679,
"text": "If we disconnect from the network, onOffline function will be called."
},
{
"code": null,
"e": 65819,
"s": 65749,
"text": "This plugin is used to display a splash screen on application launch."
},
{
"code": null,
"e": 65913,
"s": 65819,
"text": "Splash screen plugin can be installed in command prompt window by running the following code."
},
{
"code": null,
"e": 66002,
"s": 65913,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-splashscreen\n"
},
{
"code": null,
"e": 66165,
"s": 66002,
"text": "Adding splash screen is different from adding the other Cordova plugins. We need to open config.xml and add the following code snippets inside the widget element."
},
{
"code": null,
"e": 66527,
"s": 66165,
"text": "First snippet is SplashScreen. It has value property which is the name of the images in platform/android/res/drawable- folders. Cordova offers default screen.png images that we are using in this example, but you will probably want to add your own images. Important thing is to add images for portrait and landscape view and also to cover different screen sizes."
},
{
"code": null,
"e": 66581,
"s": 66527,
"text": "<preference name = \"SplashScreen\" value = \"screen\" />"
},
{
"code": null,
"e": 66709,
"s": 66581,
"text": "Second snippet we need to add is SplashScreenDelay. We are setting value to 3000 to hide the splash screen after three seconds."
},
{
"code": null,
"e": 66766,
"s": 66709,
"text": "<preference name = \"SplashScreenDelay\" value = \"3000\" />"
},
{
"code": null,
"e": 66916,
"s": 66766,
"text": "The last preference is optional. If value is set to true, the image will not be stretched to fit screen. If it is set to false, it will be stretched."
},
{
"code": null,
"e": 66981,
"s": 66916,
"text": "<preference name = \"SplashMaintainAspectRatio\" value = \"true\" />"
},
{
"code": null,
"e": 67037,
"s": 66981,
"text": "Now when we run the app, we will see the splash screen."
},
{
"code": null,
"e": 67109,
"s": 67037,
"text": "This plugin is used for connecting to device's vibration functionality."
},
{
"code": null,
"e": 67193,
"s": 67109,
"text": "We can install this plugin in command prompt window by running the following code −"
},
{
"code": null,
"e": 67279,
"s": 67193,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-vibration\n"
},
{
"code": null,
"e": 67391,
"s": 67279,
"text": "Once the plugin is installed we can add buttons in index.html that will be used later to trigger the vibration."
},
{
"code": null,
"e": 67484,
"s": 67391,
"text": "<button id = \"vibration\">VIBRATION</button>\n<button id = \"vibrationPattern\">PATTERN</button>"
},
{
"code": null,
"e": 67558,
"s": 67484,
"text": "Now we are going to add event listeners inside onDeviceReady in index.js."
},
{
"code": null,
"e": 67722,
"s": 67558,
"text": "document.getElementById(\"vibration\").addEventListener(\"click\", vibration);\ndocument.getElementById(\"vibrationPattern\").addEventListener(\"click\", vibrationPattern);"
},
{
"code": null,
"e": 67785,
"s": 67722,
"text": "This plugin is very easy to use. We will create two functions."
},
{
"code": null,
"e": 67965,
"s": 67785,
"text": "function vibration() {\n var time = 3000;\n navigator.vibrate(time);\n}\n\nfunction vibrationPattern() {\n var pattern = [1000, 1000, 1000, 1000];\n navigator.vibrate(pattern);\n}"
},
{
"code": null,
"e": 68146,
"s": 67965,
"text": "The first function is taking time parameter. This parameter is used for setting the duration of the vibration. Device will vibrate for three seconds once we press VIBRATION button."
},
{
"code": null,
"e": 68305,
"s": 68146,
"text": "The second function is using pattern parameter. This array will ask device to vibrate for one second, then wait for one second, then repeat the process again."
},
{
"code": null,
"e": 68570,
"s": 68305,
"text": "This plugin allows us to implement whitelist policy for app's navigation. When we create a new Cordova project, the whitelist plugin is installed and implemented by default. You can open the config.xml file to see allow-intent default settings provided by Cordova."
},
{
"code": null,
"e": 68727,
"s": 68570,
"text": "In the simple example below we are allowing links to some external URL. This code is placed in config.xml. Navigation to file:// URLs is allowed by default."
},
{
"code": null,
"e": 68778,
"s": 68727,
"text": "<allow-navigation href = \"http://example.com/*\" />"
},
{
"code": null,
"e": 68994,
"s": 68778,
"text": "The asterix sign, *, is used to allow navigation to multiple values. In the above example, we are allowing navigation to all sub-domains of the example.com. The same can be applied to protocol or prefix to the host."
},
{
"code": null,
"e": 69044,
"s": 68994,
"text": "<allow-navigation href = \"*://*.example.com/*\" />"
},
{
"code": null,
"e": 69243,
"s": 69044,
"text": "There is also the allow-intent element which is used to specify which URLs are allowed to open the system. You can see in the config.xml that Cordova already allowed most of the needed links for us."
},
{
"code": null,
"e": 69496,
"s": 69243,
"text": "When you look inside config.xml file, there is <access origin=\"*\" /> element. This element allows all network requests to our app via Cordova hooks. If you want to allow only specific requests, you can delete it from the config.xml and set it yourself."
},
{
"code": null,
"e": 69548,
"s": 69496,
"text": "The same principle is used as in previous examples."
},
{
"code": null,
"e": 69589,
"s": 69548,
"text": "<access origin = \"http://example.com\" />"
},
{
"code": null,
"e": 69651,
"s": 69589,
"text": "This will allow all network requests from http://example.com."
},
{
"code": null,
"e": 69743,
"s": 69651,
"text": "You can see the current security policy for your app inside the head element in index.html."
},
{
"code": null,
"e": 69924,
"s": 69743,
"text": "<meta http-equiv = \"Content-Security-Policy\" content = \"default-src \n 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src \n 'self' 'unsafe-inline'; media-src *\">"
},
{
"code": null,
"e": 70044,
"s": 69924,
"text": "This is default configuration. If you want to allow everything from the same origin and example.com, then you can use −"
},
{
"code": null,
"e": 70129,
"s": 70044,
"text": "<meta http-equiv = \"Content-Security-Policy\" content = \"default-src 'self' foo.com\">"
},
{
"code": null,
"e": 70212,
"s": 70129,
"text": "You can also allow everything, but restrict CSS and JavaScript to the same origin."
},
{
"code": null,
"e": 70375,
"s": 70212,
"text": "<meta http-equiv = \"Content-Security-Policy\" content = \"default-src *; \n style-src 'self' 'unsafe-inline'; script-src 'self' \n 'unsafe-inline' 'unsafe-eval'\">"
},
{
"code": null,
"e": 70532,
"s": 70375,
"text": "Since this is a beginners’ tutorial, we are recommending the default Cordova options. Once you get familiar with Cordova, you can try some different values."
},
{
"code": null,
"e": 70708,
"s": 70532,
"text": "Cordova is used for creating hybrid mobile apps, so you need to consider this before you choose it for your project. Below are the best practices for Cordova apps development."
},
{
"code": null,
"e": 71105,
"s": 70708,
"text": "This is the recommended design for all Cordova apps. SPA is using client-side router and navigation loaded on the single page (usually index.html). The routing is handled via AJAX. If you have followed our tutorials, you probably noticed that almost every Cordova plugin needs to wait until the device is ready before it can be used. SPA design will improve loading speed and overall performance."
},
{
"code": null,
"e": 71428,
"s": 71105,
"text": "Since Cordova is used for mobile world it is natural to use touchstart and touchend events instead of click events. The click events have 300ms delay, so the clicks don’t feel native. On the other hand, touch events aren't supported on every platform. You should take this into consideration before you decide what to use."
},
{
"code": null,
"e": 71570,
"s": 71428,
"text": "You should always use hardware accelerated CSS Transitions instead of JavaScript animations since they will perform better on mobile devices."
},
{
"code": null,
"e": 71818,
"s": 71570,
"text": "Use storage caching as much as possible. Mobile network connections are usually bad, so you should minimize network calls inside your app. You should also handle offline status of the app, since there will be times when user's devices are offline."
},
{
"code": null,
"e": 72115,
"s": 71818,
"text": "Most of the time the first slow part inside your app will be scrolling lists. There are couple of ways to improve scrolling performance of the app. Our recommendation is to use native scrolling. When there are lots of items in the list, you should load them partially. Use loaders when necessary."
},
{
"code": null,
"e": 72259,
"s": 72115,
"text": "Images can also slow the mobile app. You should use CSS image sprites whenever possible. Try to fit the images perfectly instead of scaling it."
},
{
"code": null,
"e": 72347,
"s": 72259,
"text": "You should avoid shadows and gradients, since they slow the rendering time of the page."
},
{
"code": null,
"e": 72445,
"s": 72347,
"text": "Browser's DOM is slow, so you should try to minimize DOM manipulation and number of DOM elements."
},
{
"code": null,
"e": 72654,
"s": 72445,
"text": "Ensure that you test your app on as many devices and operating system versions as possible. If app works flawlessly on one device, it doesn't necessary mean that it will work on some other device or platform."
},
{
"code": null,
"e": 72687,
"s": 72654,
"text": "\n 45 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 72707,
"s": 72687,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 72740,
"s": 72707,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 72753,
"s": 72740,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 72760,
"s": 72753,
"text": " Print"
},
{
"code": null,
"e": 72771,
"s": 72760,
"text": " Add Notes"
}
]
|
Git - Managing Branches | Branch operation allows creating another line of development. We can use this operation to fork off the development process into two different directions. For example, we released a product for 6.0 version and we might want to create a branch so that the development of 7.0 features can be kept separate from 6.0 bug fixes.
Tom creates a new branch using the git branch <branch name> command. We can create a new branch from an existing one. We can use a specific commit or tag as the starting point. If any specific commit ID is not provided, then the branch will be created with HEAD as its starting point.
[jerry@CentOS src]$ git branch new_branch
[jerry@CentOS src]$ git branch
* master
new_branch
A new branch is created; Tom used the git branch command to list the available branches. Git shows an asterisk mark before currently checked out branch.
The pictorial representation of create branch operation is shown below −
Jerry uses the git checkout command to switch between branches.
[jerry@CentOS src]$ git checkout new_branch
Switched to branch 'new_branch'
[jerry@CentOS src]$ git branch
master
* new_branch
In the above example, we have used two commands to create and switch branches, respectively. Git provides –b option with the checkout command; this operation creates a new branch and immediately switches to the new branch.
[jerry@CentOS src]$ git checkout -b test_branch
Switched to a new branch 'test_branch'
[jerry@CentOS src]$ git branch
master
new_branch
* test_branch
A branch can be deleted by providing –D option with git branch command. But before deleting the existing branch, switch to the other branch.
Jerry is currently on test_branch and he wants to remove that branch. So he switches branch and deletes branch as shown below.
[jerry@CentOS src]$ git branch
master
new_branch
* test_branch
[jerry@CentOS src]$ git checkout master
Switched to branch 'master'
[jerry@CentOS src]$ git branch -D test_branch
Deleted branch test_branch (was 5776472).
Now, Git will show only two branches.
[jerry@CentOS src]$ git branch
* master
new_branch
Jerry decides to add support for wide characters in his string operations project. He has already created a new branch, but the branch name is not appropriate. So he changes the branch name by using –m option followed by the old branch name and the new branch name.
[jerry@CentOS src]$ git branch
* master
new_branch
[jerry@CentOS src]$ git branch -m new_branch wchar_support
Now, the git branch command will show the new branch name.
[jerry@CentOS src]$ git branch
* master
wchar_support
Jerry implements a function to return the string length of wide character string. New the code will appear as follows −
[jerry@CentOS src]$ git branch
master
* wchar_support
[jerry@CentOS src]$ pwd
/home/jerry/jerry_repo/project/src
[jerry@CentOS src]$ git diff
The above command produces the following result −
t a/src/string_operations.c b/src/string_operations.c
index 8ab7f42..8fb4b00 100644
--- a/src/string_operations.c
+++ b/src/string_operations.c
@@ -1,4 +1,14 @@
#include <stdio.h>
+#include <wchar.h>
+
+size_t w_strlen(const wchar_t *s)
+
{
+
const wchar_t *p = s;
+
+
while (*p)
+ ++p;
+ return (p - s);
+
}
After testing, he commits and pushes his changes to the new branch.
[jerry@CentOS src]$ git status -s
M string_operations.c
?? string_operations
[jerry@CentOS src]$ git add string_operations.c
[jerry@CentOS src]$ git commit -m 'Added w_strlen function to return string lenght of wchar_t
string'
[wchar_support 64192f9] Added w_strlen function to return string lenght of wchar_t string
1 files changed, 10 insertions(+), 0 deletions(-)
Note that Jerry is pushing these changes to the new branch, which is why he used the branch name wchar_support instead of master branch.
[jerry@CentOS src]$ git push origin wchar_support <−−− Observer branch_name
The above command will produce the following result.
Counting objects: 7, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 507 bytes, done.
Total 4 (delta 1), reused 0 (delta 0)
To [email protected]:project.git
* [new branch]
wchar_support -> wchar_support
After committing the changes, the new branch will appear as follows −
Tom is curious about what Jerry is doing in his private branch and he checks the log from the wchar_support branch.
[tom@CentOS src]$ pwd
/home/tom/top_repo/project/src
[tom@CentOS src]$ git log origin/wchar_support -2
The above command will produce the following result.
commit 64192f91d7cc2bcdf3bf946dd33ece63b74184a3
Author: Jerry Mouse <[email protected]>
Date: Wed Sep 11 16:10:06 2013 +0530
Added w_strlen function to return string lenght of wchar_t string
commit 577647211ed44fe2ae479427a0668a4f12ed71a1
Author: Tom Cat <[email protected]>
Date: Wed Sep 11 10:21:20 2013 +0530
Removed executable binary
By viewing commit messages, Tom realizes that Jerry implemented the strlen function for wide character and he wants the same functionality in the master branch. Instead of re-implementing, he decides to take Jerry’s code by merging his branch with the master branch.
[tom@CentOS project]$ git branch
* master
[tom@CentOS project]$ pwd
/home/tom/top_repo/project
[tom@CentOS project]$ git merge origin/wchar_support
Updating 5776472..64192f9
Fast-forward
src/string_operations.c | 10 ++++++++++
1 files changed, 10 insertions(+), 0 deletions(-)
After the merge operation, the master branch will appear as follows −
Now, the branch wchar_support has been merged with the master branch. We can verify it by viewing the commit message or by viewing the modifications done into the string_operation.c file.
[tom@CentOS project]$ cd src/
[tom@CentOS src]$ git log -1
commit 64192f91d7cc2bcdf3bf946dd33ece63b74184a3
Author: Jerry Mouse
Date: Wed Sep 11 16:10:06 2013 +0530
Added w_strlen function to return string lenght of wchar_t string
[tom@CentOS src]$ head -12 string_operations.c
The above command will produce the following result.
#include <stdio.h>
#include <wchar.h>
size_t w_strlen(const wchar_t *s)
{
const wchar_t *p = s;
while (*p)
++p;
return (p - s);
}
After testing, he pushes his code changes to the master branch.
[tom@CentOS src]$ git push origin master
Total 0 (delta 0), reused 0 (delta 0)
To [email protected]:project.git
5776472..64192f9 master −> master
The Git rebase command is a branch merge command, but the difference is that it modifies the order of commits.
The Git merge command tries to put the commits from other branches on top of the HEAD of the current local branch. For example, your local branch has commits A−>B−>C−>D and the merge branch has commits A−>B−>X−>Y, then git merge will convert the current local branch to something like A−>B−>C−>D−>X−>Y
The Git rebase command tries to find out the common ancestor between the current local branch and the merge branch. It then pushes the commits to the local branch by modifying the order of commits in the current local branch. For example, if your local branch has commits A−>B−>C−>D and the merge branch has commits A−>B−>X−>Y, then Git rebase will convert the current local branch to something like A−>B−>X−>Y−>C−>D.
When multiple developers work on a single remote repository, you cannot modify the order of the commits in the remote repository. In this situation, you can use rebase operation to put your local commits on top of the remote repository commits and you can push these changes.
251 Lectures
35.5 hours
Gowthami Swarna
23 Lectures
2 hours
Asif Hussain
15 Lectures
1.5 hours
Abhilash Nelson
125 Lectures
9 hours
John Shea
13 Lectures
2.5 hours
Raghu Pandey
13 Lectures
3 hours
Sebastian Sulinski
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2369,
"s": 2045,
"text": "Branch operation allows creating another line of development. We can use this operation to fork off the development process into two different directions. For example, we released a product for 6.0 version and we might want to create a branch so that the development of 7.0 features can be kept separate from 6.0 bug fixes."
},
{
"code": null,
"e": 2654,
"s": 2369,
"text": "Tom creates a new branch using the git branch <branch name> command. We can create a new branch from an existing one. We can use a specific commit or tag as the starting point. If any specific commit ID is not provided, then the branch will be created with HEAD as its starting point."
},
{
"code": null,
"e": 2749,
"s": 2654,
"text": "[jerry@CentOS src]$ git branch new_branch\n\n[jerry@CentOS src]$ git branch\n* master\nnew_branch\n"
},
{
"code": null,
"e": 2902,
"s": 2749,
"text": "A new branch is created; Tom used the git branch command to list the available branches. Git shows an asterisk mark before currently checked out branch."
},
{
"code": null,
"e": 2975,
"s": 2902,
"text": "The pictorial representation of create branch operation is shown below −"
},
{
"code": null,
"e": 3039,
"s": 2975,
"text": "Jerry uses the git checkout command to switch between branches."
},
{
"code": null,
"e": 3167,
"s": 3039,
"text": "[jerry@CentOS src]$ git checkout new_branch\nSwitched to branch 'new_branch'\n[jerry@CentOS src]$ git branch\nmaster\n* new_branch\n"
},
{
"code": null,
"e": 3390,
"s": 3167,
"text": "In the above example, we have used two commands to create and switch branches, respectively. Git provides –b option with the checkout command; this operation creates a new branch and immediately switches to the new branch."
},
{
"code": null,
"e": 3542,
"s": 3390,
"text": "[jerry@CentOS src]$ git checkout -b test_branch\nSwitched to a new branch 'test_branch'\n\n[jerry@CentOS src]$ git branch\nmaster\nnew_branch\n* test_branch\n"
},
{
"code": null,
"e": 3683,
"s": 3542,
"text": "A branch can be deleted by providing –D option with git branch command. But before deleting the existing branch, switch to the other branch."
},
{
"code": null,
"e": 3810,
"s": 3683,
"text": "Jerry is currently on test_branch and he wants to remove that branch. So he switches branch and deletes branch as shown below."
},
{
"code": null,
"e": 4032,
"s": 3810,
"text": "[jerry@CentOS src]$ git branch\nmaster\nnew_branch\n* test_branch\n\n[jerry@CentOS src]$ git checkout master\nSwitched to branch 'master'\n\n[jerry@CentOS src]$ git branch -D test_branch\nDeleted branch test_branch (was 5776472).\n"
},
{
"code": null,
"e": 4070,
"s": 4032,
"text": "Now, Git will show only two branches."
},
{
"code": null,
"e": 4122,
"s": 4070,
"text": "[jerry@CentOS src]$ git branch\n* master\nnew_branch\n"
},
{
"code": null,
"e": 4388,
"s": 4122,
"text": "Jerry decides to add support for wide characters in his string operations project. He has already created a new branch, but the branch name is not appropriate. So he changes the branch name by using –m option followed by the old branch name and the new branch name."
},
{
"code": null,
"e": 4500,
"s": 4388,
"text": "[jerry@CentOS src]$ git branch\n* master\nnew_branch\n\n[jerry@CentOS src]$ git branch -m new_branch wchar_support\n"
},
{
"code": null,
"e": 4559,
"s": 4500,
"text": "Now, the git branch command will show the new branch name."
},
{
"code": null,
"e": 4614,
"s": 4559,
"text": "[jerry@CentOS src]$ git branch\n* master\nwchar_support\n"
},
{
"code": null,
"e": 4734,
"s": 4614,
"text": "Jerry implements a function to return the string length of wide character string. New the code will appear as follows −"
},
{
"code": null,
"e": 4879,
"s": 4734,
"text": "[jerry@CentOS src]$ git branch\nmaster\n* wchar_support\n\n[jerry@CentOS src]$ pwd\n/home/jerry/jerry_repo/project/src\n\n[jerry@CentOS src]$ git diff\n"
},
{
"code": null,
"e": 4929,
"s": 4879,
"text": "The above command produces the following result −"
},
{
"code": null,
"e": 5263,
"s": 4929,
"text": "t a/src/string_operations.c b/src/string_operations.c\nindex 8ab7f42..8fb4b00 100644\n--- a/src/string_operations.c\n+++ b/src/string_operations.c\n@@ -1,4 +1,14 @@\n#include <stdio.h>\n+#include <wchar.h>\n+\n+size_t w_strlen(const wchar_t *s)\n+\n{\n +\n const wchar_t *p = s;\n +\n +\n while (*p)\n + ++p;\n + return (p - s);\n +\n}\n"
},
{
"code": null,
"e": 5331,
"s": 5263,
"text": "After testing, he commits and pushes his changes to the new branch."
},
{
"code": null,
"e": 5702,
"s": 5331,
"text": "[jerry@CentOS src]$ git status -s\nM string_operations.c\n?? string_operations\n\n[jerry@CentOS src]$ git add string_operations.c\n\n[jerry@CentOS src]$ git commit -m 'Added w_strlen function to return string lenght of wchar_t\nstring'\n\n[wchar_support 64192f9] Added w_strlen function to return string lenght of wchar_t string\n1 files changed, 10 insertions(+), 0 deletions(-)\n"
},
{
"code": null,
"e": 5839,
"s": 5702,
"text": "Note that Jerry is pushing these changes to the new branch, which is why he used the branch name wchar_support instead of master branch."
},
{
"code": null,
"e": 5918,
"s": 5839,
"text": "[jerry@CentOS src]$ git push origin wchar_support <−−− Observer branch_name\n"
},
{
"code": null,
"e": 5971,
"s": 5918,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 6206,
"s": 5971,
"text": "Counting objects: 7, done.\nCompressing objects: 100% (4/4), done.\nWriting objects: 100% (4/4), 507 bytes, done.\nTotal 4 (delta 1), reused 0 (delta 0)\nTo [email protected]:project.git\n* [new branch]\nwchar_support -> wchar_support\n"
},
{
"code": null,
"e": 6276,
"s": 6206,
"text": "After committing the changes, the new branch will appear as follows −"
},
{
"code": null,
"e": 6392,
"s": 6276,
"text": "Tom is curious about what Jerry is doing in his private branch and he checks the log from the wchar_support branch."
},
{
"code": null,
"e": 6496,
"s": 6392,
"text": "[tom@CentOS src]$ pwd\n/home/tom/top_repo/project/src\n\n[tom@CentOS src]$ git log origin/wchar_support -2"
},
{
"code": null,
"e": 6549,
"s": 6496,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 6904,
"s": 6549,
"text": "commit 64192f91d7cc2bcdf3bf946dd33ece63b74184a3\nAuthor: Jerry Mouse <[email protected]>\nDate: Wed Sep 11 16:10:06 2013 +0530\n\nAdded w_strlen function to return string lenght of wchar_t string\n\n\ncommit 577647211ed44fe2ae479427a0668a4f12ed71a1\nAuthor: Tom Cat <[email protected]>\nDate: Wed Sep 11 10:21:20 2013 +0530\n\nRemoved executable binary\n"
},
{
"code": null,
"e": 7171,
"s": 6904,
"text": "By viewing commit messages, Tom realizes that Jerry implemented the strlen function for wide character and he wants the same functionality in the master branch. Instead of re-implementing, he decides to take Jerry’s code by merging his branch with the master branch."
},
{
"code": null,
"e": 7451,
"s": 7171,
"text": "[tom@CentOS project]$ git branch\n* master\n\n[tom@CentOS project]$ pwd\n/home/tom/top_repo/project\n\n[tom@CentOS project]$ git merge origin/wchar_support\nUpdating 5776472..64192f9\nFast-forward\nsrc/string_operations.c | 10 ++++++++++\n1 files changed, 10 insertions(+), 0 deletions(-)\n"
},
{
"code": null,
"e": 7521,
"s": 7451,
"text": "After the merge operation, the master branch will appear as follows −"
},
{
"code": null,
"e": 7709,
"s": 7521,
"text": "Now, the branch wchar_support has been merged with the master branch. We can verify it by viewing the commit message or by viewing the modifications done into the string_operation.c file."
},
{
"code": null,
"e": 7991,
"s": 7709,
"text": "[tom@CentOS project]$ cd src/\n\n[tom@CentOS src]$ git log -1\n\ncommit 64192f91d7cc2bcdf3bf946dd33ece63b74184a3\nAuthor: Jerry Mouse \nDate: Wed Sep 11 16:10:06 2013 +0530\n\nAdded w_strlen function to return string lenght of wchar_t string\n\n[tom@CentOS src]$ head -12 string_operations.c"
},
{
"code": null,
"e": 8044,
"s": 7991,
"text": "The above command will produce the following result."
},
{
"code": null,
"e": 8192,
"s": 8044,
"text": "#include <stdio.h>\n#include <wchar.h>\nsize_t w_strlen(const wchar_t *s)\n{\n const wchar_t *p = s;\n\n while (*p)\n ++p;\n\n return (p - s);\n}\n"
},
{
"code": null,
"e": 8256,
"s": 8192,
"text": "After testing, he pushes his code changes to the master branch."
},
{
"code": null,
"e": 8407,
"s": 8256,
"text": "[tom@CentOS src]$ git push origin master\nTotal 0 (delta 0), reused 0 (delta 0)\nTo [email protected]:project.git\n5776472..64192f9 master −> master"
},
{
"code": null,
"e": 8518,
"s": 8407,
"text": "The Git rebase command is a branch merge command, but the difference is that it modifies the order of commits."
},
{
"code": null,
"e": 8820,
"s": 8518,
"text": "The Git merge command tries to put the commits from other branches on top of the HEAD of the current local branch. For example, your local branch has commits A−>B−>C−>D and the merge branch has commits A−>B−>X−>Y, then git merge will convert the current local branch to something like A−>B−>C−>D−>X−>Y"
},
{
"code": null,
"e": 9238,
"s": 8820,
"text": "The Git rebase command tries to find out the common ancestor between the current local branch and the merge branch. It then pushes the commits to the local branch by modifying the order of commits in the current local branch. For example, if your local branch has commits A−>B−>C−>D and the merge branch has commits A−>B−>X−>Y, then Git rebase will convert the current local branch to something like A−>B−>X−>Y−>C−>D."
},
{
"code": null,
"e": 9514,
"s": 9238,
"text": "When multiple developers work on a single remote repository, you cannot modify the order of the commits in the remote repository. In this situation, you can use rebase operation to put your local commits on top of the remote repository commits and you can push these changes."
},
{
"code": null,
"e": 9551,
"s": 9514,
"text": "\n 251 Lectures \n 35.5 hours \n"
},
{
"code": null,
"e": 9568,
"s": 9551,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 9601,
"s": 9568,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9615,
"s": 9601,
"text": " Asif Hussain"
},
{
"code": null,
"e": 9650,
"s": 9615,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9667,
"s": 9650,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9701,
"s": 9667,
"text": "\n 125 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9712,
"s": 9701,
"text": " John Shea"
},
{
"code": null,
"e": 9747,
"s": 9712,
"text": "\n 13 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9761,
"s": 9747,
"text": " Raghu Pandey"
},
{
"code": null,
"e": 9794,
"s": 9761,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9814,
"s": 9794,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 9821,
"s": 9814,
"text": " Print"
},
{
"code": null,
"e": 9832,
"s": 9821,
"text": " Add Notes"
}
]
|
Unlock M-Step in Expectation Maximization from GMM | Towards Data Science | I like the kind of math that can be explained to me like I’m five years old.
My take on explaining, like I’m five years old, the math behind a key component of Gaussian Mixture Models (GMM) known as Expectation-Maximization (EM) and how to translate the concepts to Python. The focus this story is on the M of EM, or M-Step.
Note: This is not a comprehensive explanation about the end-to-end GMM algorithm. For a deeper dive, check out this article from Towards Data Science, another one on GMM, documenation from sci-kit learn, or Wikipedia.
Source: Based on my notes from studying machine learning; the source materials are derived from and credited to this university class.
There is a series of steps in GMM that are often referred to as Expectation Maximization, or “EM” in short. To explain how to understand the EM math, first consider a mental model of what you might be dealing with.
There are samples, represented by points on a graph.
The points form a few distinct blobs.
Each blob has a center and each point is some distance away from each blob’s center.
Given a GMM model the data, the goal is to generally label other samples by their points based on the closest center.
Some points are nearly equally far from one or more centers, as a result, we want to label points based on some kind of probability.
To learn how to learn about machine learning algorithms, you need some Greek in your life. No, not college fraternity “Greek Life” — I am talking about the meaning of Greek symbols in algorithms. Although it may be tempting to gloss over the basics, establishing a simple grasp of the individual Greek letters can help you understand important concepts in algorithms.
Algorithms can be intimidating and downright confusing. For example, at first glance, a high concentration of Greek symbols is sometimes strong enough to make a person blackout. However, instead of passing out, consider taking in the Greek, one symbol at a time.
Not to be left out, we also have some English letters that carry meaning during EM for GMM. Usually, English letters surround Greek letters like little pilot fish swimming around big sharks. Like little fish, English letters serve an important purpose and provide a guide for how to interpret the algorithm.
Now that we’ve isolated each component of the equation, let’s combine them into some common mathy phrases that are important to conversing in the language of EM by examining the M-Step.
Clusters, Gaussians, The Letter J or K and sometimes C: This all generally the same thing — if we have 3 clusters, then you might hear “for every Gaussian”, “for every j”, “for every Gaussian j”, or “for every K components” — these are all different ways to talk about the same 3 clusters. In terms of data, we could plot an array of (x,y) samples/points and see how they form clusters.
# a 2D array of samples [features and targets] # the last column, targets [0,1,2], represent three clusters# the first two columns are the points that make up our features# each feature is just a set of points (x,y) in 2D space# each row is a sample and cluster label[[-7.72642091 -8.39495682 2. ] [ 5.45339605 0.74230537 1. ] [-2.97867201 9.55684617 0. ] [ 6.04267315 0.57131862 1. ] ...]
Soft Assignments, Probability, Responsibility: The big idea with clustering is that we want to find a number for each sample that tells us which cluster the sample belongs to. In GMM, for every sample we evaluate, we might return values that represent the “responsibility of each Gaussian j”, the “soft assignment” of each, or “the probability” of each.
These phases are all generally about the same thing but with a key distinction between responsibility and probability.
# an array of assignment data about the 2D array of samples# each column represents a cluster# each row represents data about each sample# in each row, we have the probability that a sample belongs to one of three clusters - it adds up to 1 (as it should)# but the sum of each column is a big number number (not 1)print(assignments)# sample output: an array of assignment data[[1.00000000e+000 2.82033618e-118 1.13001412e-070] [9.21706438e-074 1.00000000e+000 3.98146031e-029] [4.40884339e-099 5.66602768e-053 1.00000000e+000]...]print(np.sum(assignments[0])# sample output: the sum across each row is 11print(np.sum(assignments[:, 0])# sample output: the sum in each col is a big number that varies# Little Gamma: the really small numbers in each column# Big Gamma: the sum of each column, or 33.0 in this sample33.0
Big Gamma, Little Gamma, J, N, x, and i: The core set of tasks in EM is to optimize three sets of parameters for every cluster, or “for every j, optimize the w (w), the mew (μ), and the variance (σ).” In other words, what is the cluster’s weight (w), the cluster’s center point (μ), and cluster’s variance(σ)?
For weight (w), we have Big Gamma divided by the total number of features. From earlier, we know that Big Gamma for every cluster j, is just the result of adding every sample’s assignment value for a given cluster (this is the number that does not add up to 1). Figure 3.
For mew (μ), instead of adding up all the Little Gammas into a single Big Gamma as we did earlier, do matrix multiplication of the Little Gammas by the features x for each cluster j and each sample i. Figure 4.
Remember, the mew is just the center point of each cluster — if we have 3 clusters and our samples are all x, y coordinates, then the mew is going to be an array of 3 x, y coordinates, one for each cluster.
# for figure 4 - mew (mu)# same array of assignment data as before# each column is a cluster of little gammasprint(assignments)[[1.00000000e+000 2.82033618e-118 1.13001412e-070] [9.21706438e-074 1.00000000e+000 3.98146031e-029] [4.40884339e-099 5.66602768e-053 1.00000000e+000]...]# the little gammas of cluster 0 is just column 0[[1.00000000e+000 ] [9.21706438e-074 ] [4.40884339e-099 ]...]# same array of sample data as before# the first two columns are the x,y coordinates# the last column is the cluster label of the sampleprint(features)[[-7.72642091 -8.39495682 2. ] [ 5.45339605 0.74230537 1. ] [-2.97867201 9.55684617 0. ] [ 6.04267315 0.57131862 1. ] ...]# for features, we just need its points[[-7.72642091 -8.39495682 ] [ 5.45339605 0.74230537 ] [-2.97867201 9.55684617 ] [ 6.04267315 0.57131862 ] ...]# if using numpy (np) for matrix multiplication # for cluster 0 ...big_gamma = np.sum(assignments[:, 0]mew = np.matmul(assignments[:, 0], features) / big_gamma# returns an array of mew[[-2.66780392 8.93576069] [-6.95170962 -6.67621669] [ 4.49951001 1.93892013]]
For variance (σ), consider that by now, we have points and center points — with variance, we are basically evaluating the distance from each sample’s points (x for every i) to each cluster’s center point (mew for every i). In the language of EM, some might say “x_i minus mew_i squared over Big Gamma j.”
# for figure 5 - variance# a sampling of variance for cluster 0 of n clusters# given arrays for features and assignments...x_i = featuresbig_gamma = np.sum(assignments[:, 0]mew = np.matmul(assignments[:, 0], features) / big_gammanumerator = np.matmul(assignments[:, 0], (x_i - mew) ** 2)variance = numerator / big_gamma# returns an array of variance[[0.6422345 1.06006186] [0.65254746 0.9274831 ] [0.95031461 0.92519751]]
The preceding steps are all about the M-Step in EM or Maximization — everything about weights, mew, and variance are all about optimization; however, what about the initial assignments array? How do we get an array of probabilities for each sample — this is the E-Step in EM or Expectation.
Although not covered in detail in this story, I can leave you with a good reference to Wikipedia and the following intuition.
In E-Step, we try to guess the assignments of each point with Bayes’ Rule — this produces the array of values that indicate responsibility or probability of each point to a Gaussian. At first the guessed values in assignments (which are the posteriors) are far off, but after cycling through E-Step and M-Step, the guesses will get better and closer to the objective ground truth.
The GMM algorithm repeats both M-Step and E-Step until convergence. The convergence, for instance, might be a maximum number of iterations or when the differences between each round of guessing gets really small. The result, hopefully, is a label of soft assignments for each sample in the data.
In this article, I present a beginner’s understanding to navigating part of the Expectation Maximization phase of the Gaussian Mixture Model algorithm known as M-Step. Although the math seems too hot to handle at the surface, we can manage the complexity by understanding its individual parts. For instance, a few key understandings as simple as pronouncing the Greek symbols and applying their operations with NumPy are important to grasping the overarching concepts.
Thanks for reading, hope these explanations help you learn and understand GMM. Let me know if I can make any improvements or cover new topics. | [
{
"code": null,
"e": 249,
"s": 172,
"text": "I like the kind of math that can be explained to me like I’m five years old."
},
{
"code": null,
"e": 497,
"s": 249,
"text": "My take on explaining, like I’m five years old, the math behind a key component of Gaussian Mixture Models (GMM) known as Expectation-Maximization (EM) and how to translate the concepts to Python. The focus this story is on the M of EM, or M-Step."
},
{
"code": null,
"e": 715,
"s": 497,
"text": "Note: This is not a comprehensive explanation about the end-to-end GMM algorithm. For a deeper dive, check out this article from Towards Data Science, another one on GMM, documenation from sci-kit learn, or Wikipedia."
},
{
"code": null,
"e": 850,
"s": 715,
"text": "Source: Based on my notes from studying machine learning; the source materials are derived from and credited to this university class."
},
{
"code": null,
"e": 1065,
"s": 850,
"text": "There is a series of steps in GMM that are often referred to as Expectation Maximization, or “EM” in short. To explain how to understand the EM math, first consider a mental model of what you might be dealing with."
},
{
"code": null,
"e": 1118,
"s": 1065,
"text": "There are samples, represented by points on a graph."
},
{
"code": null,
"e": 1156,
"s": 1118,
"text": "The points form a few distinct blobs."
},
{
"code": null,
"e": 1241,
"s": 1156,
"text": "Each blob has a center and each point is some distance away from each blob’s center."
},
{
"code": null,
"e": 1359,
"s": 1241,
"text": "Given a GMM model the data, the goal is to generally label other samples by their points based on the closest center."
},
{
"code": null,
"e": 1492,
"s": 1359,
"text": "Some points are nearly equally far from one or more centers, as a result, we want to label points based on some kind of probability."
},
{
"code": null,
"e": 1860,
"s": 1492,
"text": "To learn how to learn about machine learning algorithms, you need some Greek in your life. No, not college fraternity “Greek Life” — I am talking about the meaning of Greek symbols in algorithms. Although it may be tempting to gloss over the basics, establishing a simple grasp of the individual Greek letters can help you understand important concepts in algorithms."
},
{
"code": null,
"e": 2123,
"s": 1860,
"text": "Algorithms can be intimidating and downright confusing. For example, at first glance, a high concentration of Greek symbols is sometimes strong enough to make a person blackout. However, instead of passing out, consider taking in the Greek, one symbol at a time."
},
{
"code": null,
"e": 2431,
"s": 2123,
"text": "Not to be left out, we also have some English letters that carry meaning during EM for GMM. Usually, English letters surround Greek letters like little pilot fish swimming around big sharks. Like little fish, English letters serve an important purpose and provide a guide for how to interpret the algorithm."
},
{
"code": null,
"e": 2617,
"s": 2431,
"text": "Now that we’ve isolated each component of the equation, let’s combine them into some common mathy phrases that are important to conversing in the language of EM by examining the M-Step."
},
{
"code": null,
"e": 3004,
"s": 2617,
"text": "Clusters, Gaussians, The Letter J or K and sometimes C: This all generally the same thing — if we have 3 clusters, then you might hear “for every Gaussian”, “for every j”, “for every Gaussian j”, or “for every K components” — these are all different ways to talk about the same 3 clusters. In terms of data, we could plot an array of (x,y) samples/points and see how they form clusters."
},
{
"code": null,
"e": 3401,
"s": 3004,
"text": "# a 2D array of samples [features and targets] # the last column, targets [0,1,2], represent three clusters# the first two columns are the points that make up our features# each feature is just a set of points (x,y) in 2D space# each row is a sample and cluster label[[-7.72642091 -8.39495682 2. ] [ 5.45339605 0.74230537 1. ] [-2.97867201 9.55684617 0. ] [ 6.04267315 0.57131862 1. ] ...]"
},
{
"code": null,
"e": 3755,
"s": 3401,
"text": "Soft Assignments, Probability, Responsibility: The big idea with clustering is that we want to find a number for each sample that tells us which cluster the sample belongs to. In GMM, for every sample we evaluate, we might return values that represent the “responsibility of each Gaussian j”, the “soft assignment” of each, or “the probability” of each."
},
{
"code": null,
"e": 3874,
"s": 3755,
"text": "These phases are all generally about the same thing but with a key distinction between responsibility and probability."
},
{
"code": null,
"e": 4692,
"s": 3874,
"text": "# an array of assignment data about the 2D array of samples# each column represents a cluster# each row represents data about each sample# in each row, we have the probability that a sample belongs to one of three clusters - it adds up to 1 (as it should)# but the sum of each column is a big number number (not 1)print(assignments)# sample output: an array of assignment data[[1.00000000e+000 2.82033618e-118 1.13001412e-070] [9.21706438e-074 1.00000000e+000 3.98146031e-029] [4.40884339e-099 5.66602768e-053 1.00000000e+000]...]print(np.sum(assignments[0])# sample output: the sum across each row is 11print(np.sum(assignments[:, 0])# sample output: the sum in each col is a big number that varies# Little Gamma: the really small numbers in each column# Big Gamma: the sum of each column, or 33.0 in this sample33.0"
},
{
"code": null,
"e": 5002,
"s": 4692,
"text": "Big Gamma, Little Gamma, J, N, x, and i: The core set of tasks in EM is to optimize three sets of parameters for every cluster, or “for every j, optimize the w (w), the mew (μ), and the variance (σ).” In other words, what is the cluster’s weight (w), the cluster’s center point (μ), and cluster’s variance(σ)?"
},
{
"code": null,
"e": 5274,
"s": 5002,
"text": "For weight (w), we have Big Gamma divided by the total number of features. From earlier, we know that Big Gamma for every cluster j, is just the result of adding every sample’s assignment value for a given cluster (this is the number that does not add up to 1). Figure 3."
},
{
"code": null,
"e": 5485,
"s": 5274,
"text": "For mew (μ), instead of adding up all the Little Gammas into a single Big Gamma as we did earlier, do matrix multiplication of the Little Gammas by the features x for each cluster j and each sample i. Figure 4."
},
{
"code": null,
"e": 5692,
"s": 5485,
"text": "Remember, the mew is just the center point of each cluster — if we have 3 clusters and our samples are all x, y coordinates, then the mew is going to be an array of 3 x, y coordinates, one for each cluster."
},
{
"code": null,
"e": 6783,
"s": 5692,
"text": "# for figure 4 - mew (mu)# same array of assignment data as before# each column is a cluster of little gammasprint(assignments)[[1.00000000e+000 2.82033618e-118 1.13001412e-070] [9.21706438e-074 1.00000000e+000 3.98146031e-029] [4.40884339e-099 5.66602768e-053 1.00000000e+000]...]# the little gammas of cluster 0 is just column 0[[1.00000000e+000 ] [9.21706438e-074 ] [4.40884339e-099 ]...]# same array of sample data as before# the first two columns are the x,y coordinates# the last column is the cluster label of the sampleprint(features)[[-7.72642091 -8.39495682 2. ] [ 5.45339605 0.74230537 1. ] [-2.97867201 9.55684617 0. ] [ 6.04267315 0.57131862 1. ] ...]# for features, we just need its points[[-7.72642091 -8.39495682 ] [ 5.45339605 0.74230537 ] [-2.97867201 9.55684617 ] [ 6.04267315 0.57131862 ] ...]# if using numpy (np) for matrix multiplication # for cluster 0 ...big_gamma = np.sum(assignments[:, 0]mew = np.matmul(assignments[:, 0], features) / big_gamma# returns an array of mew[[-2.66780392 8.93576069] [-6.95170962 -6.67621669] [ 4.49951001 1.93892013]]"
},
{
"code": null,
"e": 7088,
"s": 6783,
"text": "For variance (σ), consider that by now, we have points and center points — with variance, we are basically evaluating the distance from each sample’s points (x for every i) to each cluster’s center point (mew for every i). In the language of EM, some might say “x_i minus mew_i squared over Big Gamma j.”"
},
{
"code": null,
"e": 7511,
"s": 7088,
"text": "# for figure 5 - variance# a sampling of variance for cluster 0 of n clusters# given arrays for features and assignments...x_i = featuresbig_gamma = np.sum(assignments[:, 0]mew = np.matmul(assignments[:, 0], features) / big_gammanumerator = np.matmul(assignments[:, 0], (x_i - mew) ** 2)variance = numerator / big_gamma# returns an array of variance[[0.6422345 1.06006186] [0.65254746 0.9274831 ] [0.95031461 0.92519751]]"
},
{
"code": null,
"e": 7802,
"s": 7511,
"text": "The preceding steps are all about the M-Step in EM or Maximization — everything about weights, mew, and variance are all about optimization; however, what about the initial assignments array? How do we get an array of probabilities for each sample — this is the E-Step in EM or Expectation."
},
{
"code": null,
"e": 7928,
"s": 7802,
"text": "Although not covered in detail in this story, I can leave you with a good reference to Wikipedia and the following intuition."
},
{
"code": null,
"e": 8309,
"s": 7928,
"text": "In E-Step, we try to guess the assignments of each point with Bayes’ Rule — this produces the array of values that indicate responsibility or probability of each point to a Gaussian. At first the guessed values in assignments (which are the posteriors) are far off, but after cycling through E-Step and M-Step, the guesses will get better and closer to the objective ground truth."
},
{
"code": null,
"e": 8605,
"s": 8309,
"text": "The GMM algorithm repeats both M-Step and E-Step until convergence. The convergence, for instance, might be a maximum number of iterations or when the differences between each round of guessing gets really small. The result, hopefully, is a label of soft assignments for each sample in the data."
},
{
"code": null,
"e": 9074,
"s": 8605,
"text": "In this article, I present a beginner’s understanding to navigating part of the Expectation Maximization phase of the Gaussian Mixture Model algorithm known as M-Step. Although the math seems too hot to handle at the surface, we can manage the complexity by understanding its individual parts. For instance, a few key understandings as simple as pronouncing the Greek symbols and applying their operations with NumPy are important to grasping the overarching concepts."
}
]
|
Stack in C++ STL - GeeksforGeeks | 31 Aug, 2021
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. Stack uses an encapsulated object of either vector or deque (by default) or list (sequential container class) as its underlying container, providing a specific set of member functions to access its elements.
Stack Syntax:-
For creating a stack, we must include the <stack> header file in our code. We then use this syntax to define the std::stack:
Type – is the Type of element contained in the std::stack. It can be any valid C++ type or even a user-defined type.
Container – is the Type of underlying container object.
Member Types:-
value_type- The first template parameter, T. It denotes the element types.
container_type- The second template parameter, Container. It denotes the underlying container type.
size_type- Unsigned integral type. The functions associated with stack are: empty() – Returns whether the stack is empty – Time Complexity : O(1) size() – Returns the size of the stack – Time Complexity : O(1) top() – Returns a reference to the top most element of the stack – Time Complexity : O(1) push(g) – Adds the element ‘g’ at the top of the stack – Time Complexity : O(1) pop() – Deletes the top most element of the stack – Time Complexity : O(1)
C++
#include <iostream>#include <stack>using namespace std;int main() { stack<int> stack; stack.push(21); stack.push(22); stack.push(24); stack.push(25); stack.pop(); stack.pop(); while (!stack.empty()) { cout << ' ' << stack.top(); stack.pop(); }}
22 21
Code Explanation:
Include the iostream header file or <bits/stdc++.h> in our code to use its functions.Include the stack header file in our code to use its functions if already included <bits/stdc++.h> then no need of stack header file because it has already inbuilt function in it.Include the std namespace in our code to use its classes without calling it.Call the main() function. The program logic should be added within this function.Create a stack to store integer values.Use the push() function to insert the value 21 into the stack.Use the push() function to insert the value 22 into the stack.Use the push() function to insert the value 24 into the stack.Use the push() function to insert the value 25 into the stack.Use the pop() function to remove the top element from the stack, that is, 25. The top element now becomes 24.Use the pop() function to remove the top element from the stack, that is, 24. The top element now becomes 22.Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator.Printing the current contents of the stack on the console.Call the pop() function on the stack.End of the body of the while loop.End of the main() function body.
Include the iostream header file or <bits/stdc++.h> in our code to use its functions.
Include the stack header file in our code to use its functions if already included <bits/stdc++.h> then no need of stack header file because it has already inbuilt function in it.
Include the std namespace in our code to use its classes without calling it.
Call the main() function. The program logic should be added within this function.
Create a stack to store integer values.
Use the push() function to insert the value 21 into the stack.
Use the push() function to insert the value 22 into the stack.
Use the push() function to insert the value 24 into the stack.
Use the push() function to insert the value 25 into the stack.
Use the pop() function to remove the top element from the stack, that is, 25. The top element now becomes 24.
Use the pop() function to remove the top element from the stack, that is, 24. The top element now becomes 22.
Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator.
Printing the current contents of the stack on the console.
Call the pop() function on the stack.
End of the body of the while loop.
End of the main() function body.
List of functions of Stack:
stack::top() in C++ STL
stack::empty() and stack::size() in C++ STL
stack::push() and stack::pop() in C++ STL
stack::swap() in C++ STL
stack::emplace() in C++ STL
Recent Articles on C++ Stack
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
naveenkumar173
hit
chiranshu3444
cpp-containers-library
cpp-stack
cpp-stack-functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL
Virtual Function in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Templates in C++ with Examples
Constructors in C++ | [
{
"code": null,
"e": 37778,
"s": 37750,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 38165,
"s": 37778,
"text": "Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. Stack uses an encapsulated object of either vector or deque (by default) or list (sequential container class) as its underlying container, providing a specific set of member functions to access its elements."
},
{
"code": null,
"e": 38180,
"s": 38165,
"text": "Stack Syntax:-"
},
{
"code": null,
"e": 38306,
"s": 38180,
"text": "For creating a stack, we must include the <stack> header file in our code. We then use this syntax to define the std::stack:"
},
{
"code": null,
"e": 38423,
"s": 38306,
"text": "Type – is the Type of element contained in the std::stack. It can be any valid C++ type or even a user-defined type."
},
{
"code": null,
"e": 38479,
"s": 38423,
"text": "Container – is the Type of underlying container object."
},
{
"code": null,
"e": 38494,
"s": 38479,
"text": "Member Types:-"
},
{
"code": null,
"e": 38569,
"s": 38494,
"text": "value_type- The first template parameter, T. It denotes the element types."
},
{
"code": null,
"e": 38669,
"s": 38569,
"text": "container_type- The second template parameter, Container. It denotes the underlying container type."
},
{
"code": null,
"e": 39126,
"s": 38669,
"text": "size_type- Unsigned integral type. The functions associated with stack are: empty() – Returns whether the stack is empty – Time Complexity : O(1) size() – Returns the size of the stack – Time Complexity : O(1) top() – Returns a reference to the top most element of the stack – Time Complexity : O(1) push(g) – Adds the element ‘g’ at the top of the stack – Time Complexity : O(1) pop() – Deletes the top most element of the stack – Time Complexity : O(1) "
},
{
"code": null,
"e": 39130,
"s": 39126,
"text": "C++"
},
{
"code": "#include <iostream>#include <stack>using namespace std;int main() { stack<int> stack; stack.push(21); stack.push(22); stack.push(24); stack.push(25); stack.pop(); stack.pop(); while (!stack.empty()) { cout << ' ' << stack.top(); stack.pop(); }}",
"e": 39427,
"s": 39130,
"text": null
},
{
"code": null,
"e": 39434,
"s": 39427,
"text": " 22 21"
},
{
"code": null,
"e": 39452,
"s": 39434,
"text": "Code Explanation:"
},
{
"code": null,
"e": 40645,
"s": 39452,
"text": "Include the iostream header file or <bits/stdc++.h> in our code to use its functions.Include the stack header file in our code to use its functions if already included <bits/stdc++.h> then no need of stack header file because it has already inbuilt function in it.Include the std namespace in our code to use its classes without calling it.Call the main() function. The program logic should be added within this function.Create a stack to store integer values.Use the push() function to insert the value 21 into the stack.Use the push() function to insert the value 22 into the stack.Use the push() function to insert the value 24 into the stack.Use the push() function to insert the value 25 into the stack.Use the pop() function to remove the top element from the stack, that is, 25. The top element now becomes 24.Use the pop() function to remove the top element from the stack, that is, 24. The top element now becomes 22.Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator.Printing the current contents of the stack on the console.Call the pop() function on the stack.End of the body of the while loop.End of the main() function body."
},
{
"code": null,
"e": 40731,
"s": 40645,
"text": "Include the iostream header file or <bits/stdc++.h> in our code to use its functions."
},
{
"code": null,
"e": 40911,
"s": 40731,
"text": "Include the stack header file in our code to use its functions if already included <bits/stdc++.h> then no need of stack header file because it has already inbuilt function in it."
},
{
"code": null,
"e": 40988,
"s": 40911,
"text": "Include the std namespace in our code to use its classes without calling it."
},
{
"code": null,
"e": 41070,
"s": 40988,
"text": "Call the main() function. The program logic should be added within this function."
},
{
"code": null,
"e": 41110,
"s": 41070,
"text": "Create a stack to store integer values."
},
{
"code": null,
"e": 41173,
"s": 41110,
"text": "Use the push() function to insert the value 21 into the stack."
},
{
"code": null,
"e": 41236,
"s": 41173,
"text": "Use the push() function to insert the value 22 into the stack."
},
{
"code": null,
"e": 41299,
"s": 41236,
"text": "Use the push() function to insert the value 24 into the stack."
},
{
"code": null,
"e": 41362,
"s": 41299,
"text": "Use the push() function to insert the value 25 into the stack."
},
{
"code": null,
"e": 41472,
"s": 41362,
"text": "Use the pop() function to remove the top element from the stack, that is, 25. The top element now becomes 24."
},
{
"code": null,
"e": 41582,
"s": 41472,
"text": "Use the pop() function to remove the top element from the stack, that is, 24. The top element now becomes 22."
},
{
"code": null,
"e": 41688,
"s": 41582,
"text": "Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator."
},
{
"code": null,
"e": 41747,
"s": 41688,
"text": "Printing the current contents of the stack on the console."
},
{
"code": null,
"e": 41785,
"s": 41747,
"text": "Call the pop() function on the stack."
},
{
"code": null,
"e": 41820,
"s": 41785,
"text": "End of the body of the while loop."
},
{
"code": null,
"e": 41853,
"s": 41820,
"text": "End of the main() function body."
},
{
"code": null,
"e": 41882,
"s": 41853,
"text": "List of functions of Stack: "
},
{
"code": null,
"e": 41906,
"s": 41882,
"text": "stack::top() in C++ STL"
},
{
"code": null,
"e": 41950,
"s": 41906,
"text": "stack::empty() and stack::size() in C++ STL"
},
{
"code": null,
"e": 41992,
"s": 41950,
"text": "stack::push() and stack::pop() in C++ STL"
},
{
"code": null,
"e": 42017,
"s": 41992,
"text": "stack::swap() in C++ STL"
},
{
"code": null,
"e": 42045,
"s": 42017,
"text": "stack::emplace() in C++ STL"
},
{
"code": null,
"e": 42074,
"s": 42045,
"text": "Recent Articles on C++ Stack"
},
{
"code": null,
"e": 42198,
"s": 42074,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 42213,
"s": 42198,
"text": "naveenkumar173"
},
{
"code": null,
"e": 42217,
"s": 42213,
"text": "hit"
},
{
"code": null,
"e": 42231,
"s": 42217,
"text": "chiranshu3444"
},
{
"code": null,
"e": 42254,
"s": 42231,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 42264,
"s": 42254,
"text": "cpp-stack"
},
{
"code": null,
"e": 42284,
"s": 42264,
"text": "cpp-stack-functions"
},
{
"code": null,
"e": 42288,
"s": 42284,
"text": "STL"
},
{
"code": null,
"e": 42292,
"s": 42288,
"text": "C++"
},
{
"code": null,
"e": 42296,
"s": 42292,
"text": "STL"
},
{
"code": null,
"e": 42300,
"s": 42296,
"text": "CPP"
},
{
"code": null,
"e": 42398,
"s": 42300,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42416,
"s": 42398,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 42435,
"s": 42416,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 42481,
"s": 42435,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 42524,
"s": 42481,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 42547,
"s": 42524,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 42571,
"s": 42547,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 42595,
"s": 42571,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 42622,
"s": 42595,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 42653,
"s": 42622,
"text": "Templates in C++ with Examples"
}
]
|
Maximum and Minimum Of Array Elements | Practice | GeeksforGeeks | Given an array A[ ], find maximum and minimum elements from the array.
Input:
The first line of input contains an integer T, denoting the number of testcases. The description of T testcases follows. The first line of each testcase contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
For each testcase in a new line, print the maximum and minimum element in a single line with space in between.
Constraints:
1 ≤ T ≤ 30
1 ≤ N ≤ 100
0 ≤A[i]<100
Example:
Input:
2
4
5 4 2 1
1
8
Output:
5 1
8 8
Explanation:
Testcase 1:
Maximum element is: 5
Minimum element is: 1
0
codingbeast00122 weeks ago
#include<iostream>#include<limits.h>using namespace std;
int max_element(int a[], int size){ int maxi=INT_MIN; for(int i=0;i<size;i++) { maxi=max(maxi,a[i]); } return maxi; }
int min_element(int b[], int size){ int mini=INT_MAX; for(int i=0;i<size;i++) { mini=min(mini,b[i]); } return mini;}
int main(){//codeint T;cin>>T;while(T--){ int N; cin>>N; int A[N]; for(int i=0;i<N;i++) { cin>>A[i]; } cout<<max_element(A,N)<<" "<<min_element(A,N)<<endl; }
return 0;}
0
krishnakshirsagar413 months ago
#try this difficult one so much to learn in this code not only min max #function
n = int(input())
for i in range(n): l = int(input()) lst1 = list(map(int, input().split())) lst1.sort(reverse=True) ans1=[] ans1.append(lst1[0]) lst1.sort() ans1.append(lst1[0]) print(*ans1)
-1
abhinavsinghbiz3 months ago
C Code,Run Time=0.0
#include <stdio.h>
int max(int arr[],int N){ int max=arr[0]; for(int i=1;i<N;i++){ if(arr[i]>max){ max=arr[i]; } } return max;}
int min(int arr[],int N){ int min=arr[0]; for(int i=1;i<N;i++){ if(arr[i]<min){ min=arr[i]; } } return min;}
int main() { int T; scanf("%d",&T);for(int i=0;i<T;i++){ int N; scanf("%d",&N); int arr[N]; for(int j=0;j<N;j++){ scanf("%d",&arr[j]); } printf("%d ",max(arr,N)); printf("%d\n",min(arr,N)); }return 0;}
0
mohanlovish70803 months ago
#please help me out... i don't know that why my code fails every time i run...
t = int(input())
for i in range(t):
n = int(input())
arr = input()
arr_l = arr.split(" ")
mx = max(arr_l)
mn = min(arr_l)
print(mx, end = " ")
print(mn)
0
rutwikgosavi3 months ago
t = int(input())
for i in range(t):
n = int(input())
lst = list(map(int, input().split()))
print(max(lst), min(lst))
0
rutwikgosavi
This comment was deleted.
0
rryadav142001
This comment was deleted.
0
bickyjha0553 months ago
#include "bits/stdc++.h"using namespace std;
int min(int arr[], int n){ int min_value = INT_MAX; for(int i = 0; i<n; i++){ if(arr[i] < min_value){ min_value = arr[i]; // store the min value } } return min_value;}int max(int arr[], int n){ int max_value = INT_MIN; for(int i = 0; i<n; i++){ if(arr[i] > max_value){ max_value = arr[i]; // store the max value } } return max_value;}
int main() { int t; cin >>t; while(t--){ int n; cin>>n; int arr[n]; for(int i = 0; i<n; i++){ cin >> arr[i]; } //Direct using STL Function int Max = INT_MIN; int Min = INT_MAX; for(int i =0; i< n; i++){ Max = max(Max, arr[i]); Min = min(Min, arr[i]); } // using create your one funtion // int Max = max(arr,n); // int Min = min(arr,n); cout << Max << " " << Min <<endl; }return 0;}
0
ujjwal013 months ago
#include <iostream>
#include<climits>
#include<algorithm>
using namespace std;
int main() {
//code
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int max=INT_MIN;
int min=INT_MAX;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
max=std::max(max,a[i]);
min=std::min(min,a[i]);
}
cout<<max<<" "<<min<<endl;
}
return 0;
}
+1
adibose93 months ago
#SIMPLE AND UNDERSTANDABLE PYTHON CODE
#UPVOTING WOULD BE HIGHLY APPRICIABLE
t=int(input()) #input for test casel=list() #created and empty list to store multiple arraysfor i in range(t): #loop so that for every test case, we can input an array n=int(input()) #size of array lst=list(map(int, input().split())) #creating array l.append(lst) #adding array to the list for arr in l: #looping through the arrays inside the list print(max(arr),min(arr)) #printing out the max and min values
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 297,
"s": 226,
"text": "Given an array A[ ], find maximum and minimum elements from the array."
},
{
"code": null,
"e": 617,
"s": 297,
"text": "Input:\nThe first line of input contains an integer T, denoting the number of testcases. The description of T testcases follows. The first line of each testcase contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array."
},
{
"code": null,
"e": 736,
"s": 617,
"text": "Output:\nFor each testcase in a new line, print the maximum and minimum element in a single line with space in between."
},
{
"code": null,
"e": 784,
"s": 736,
"text": "Constraints:\n1 ≤ T ≤ 30\n1 ≤ N ≤ 100\n0 ≤A[i]<100"
},
{
"code": null,
"e": 816,
"s": 784,
"text": "Example:\nInput:\n2\n4\n5 4 2 1\n1\n8"
},
{
"code": null,
"e": 832,
"s": 816,
"text": "Output:\n5 1\n8 8"
},
{
"code": null,
"e": 902,
"s": 832,
"text": "Explanation:\nTestcase 1:\nMaximum element is: 5 \nMinimum element is: 1"
},
{
"code": null,
"e": 904,
"s": 902,
"text": "0"
},
{
"code": null,
"e": 931,
"s": 904,
"text": "codingbeast00122 weeks ago"
},
{
"code": null,
"e": 988,
"s": 931,
"text": "#include<iostream>#include<limits.h>using namespace std;"
},
{
"code": null,
"e": 1130,
"s": 988,
"text": "int max_element(int a[], int size){ int maxi=INT_MIN; for(int i=0;i<size;i++) { maxi=max(maxi,a[i]); } return maxi; }"
},
{
"code": null,
"e": 1265,
"s": 1130,
"text": "int min_element(int b[], int size){ int mini=INT_MAX; for(int i=0;i<size;i++) { mini=min(mini,b[i]); } return mini;}"
},
{
"code": null,
"e": 1456,
"s": 1267,
"text": "int main(){//codeint T;cin>>T;while(T--){ int N; cin>>N; int A[N]; for(int i=0;i<N;i++) { cin>>A[i]; } cout<<max_element(A,N)<<\" \"<<min_element(A,N)<<endl; } "
},
{
"code": null,
"e": 1470,
"s": 1456,
"text": " return 0;}"
},
{
"code": null,
"e": 1472,
"s": 1470,
"text": "0"
},
{
"code": null,
"e": 1504,
"s": 1472,
"text": "krishnakshirsagar413 months ago"
},
{
"code": null,
"e": 1585,
"s": 1504,
"text": "#try this difficult one so much to learn in this code not only min max #function"
},
{
"code": null,
"e": 1602,
"s": 1585,
"text": "n = int(input())"
},
{
"code": null,
"e": 1792,
"s": 1602,
"text": "for i in range(n): l = int(input()) lst1 = list(map(int, input().split())) lst1.sort(reverse=True) ans1=[] ans1.append(lst1[0]) lst1.sort() ans1.append(lst1[0]) print(*ans1)"
},
{
"code": null,
"e": 1795,
"s": 1792,
"text": "-1"
},
{
"code": null,
"e": 1823,
"s": 1795,
"text": "abhinavsinghbiz3 months ago"
},
{
"code": null,
"e": 1843,
"s": 1823,
"text": "C Code,Run Time=0.0"
},
{
"code": null,
"e": 1862,
"s": 1843,
"text": "#include <stdio.h>"
},
{
"code": null,
"e": 2001,
"s": 1862,
"text": "int max(int arr[],int N){ int max=arr[0]; for(int i=1;i<N;i++){ if(arr[i]>max){ max=arr[i]; } } return max;}"
},
{
"code": null,
"e": 2140,
"s": 2001,
"text": "int min(int arr[],int N){ int min=arr[0]; for(int i=1;i<N;i++){ if(arr[i]<min){ min=arr[i]; } } return min;}"
},
{
"code": null,
"e": 2377,
"s": 2140,
"text": "int main() { int T; scanf(\"%d\",&T);for(int i=0;i<T;i++){ int N; scanf(\"%d\",&N); int arr[N]; for(int j=0;j<N;j++){ scanf(\"%d\",&arr[j]); } printf(\"%d \",max(arr,N)); printf(\"%d\\n\",min(arr,N)); }return 0;}"
},
{
"code": null,
"e": 2379,
"s": 2377,
"text": "0"
},
{
"code": null,
"e": 2407,
"s": 2379,
"text": "mohanlovish70803 months ago"
},
{
"code": null,
"e": 2486,
"s": 2407,
"text": "#please help me out... i don't know that why my code fails every time i run..."
},
{
"code": null,
"e": 2677,
"s": 2486,
"text": "t = int(input())\nfor i in range(t):\n n = int(input())\n arr = input()\n arr_l = arr.split(\" \")\n \n mx = max(arr_l)\n mn = min(arr_l)\n \n print(mx, end = \" \")\n print(mn)"
},
{
"code": null,
"e": 2679,
"s": 2677,
"text": "0"
},
{
"code": null,
"e": 2704,
"s": 2679,
"text": "rutwikgosavi3 months ago"
},
{
"code": null,
"e": 2833,
"s": 2704,
"text": "t = int(input())\nfor i in range(t):\n n = int(input())\n lst = list(map(int, input().split()))\n print(max(lst), min(lst))"
},
{
"code": null,
"e": 2835,
"s": 2833,
"text": "0"
},
{
"code": null,
"e": 2848,
"s": 2835,
"text": "rutwikgosavi"
},
{
"code": null,
"e": 2874,
"s": 2848,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2876,
"s": 2874,
"text": "0"
},
{
"code": null,
"e": 2890,
"s": 2876,
"text": "rryadav142001"
},
{
"code": null,
"e": 2916,
"s": 2890,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2918,
"s": 2916,
"text": "0"
},
{
"code": null,
"e": 2942,
"s": 2918,
"text": "bickyjha0553 months ago"
},
{
"code": null,
"e": 2987,
"s": 2942,
"text": "#include \"bits/stdc++.h\"using namespace std;"
},
{
"code": null,
"e": 3402,
"s": 2987,
"text": "int min(int arr[], int n){ int min_value = INT_MAX; for(int i = 0; i<n; i++){ if(arr[i] < min_value){ min_value = arr[i]; // store the min value } } return min_value;}int max(int arr[], int n){ int max_value = INT_MIN; for(int i = 0; i<n; i++){ if(arr[i] > max_value){ max_value = arr[i]; // store the max value } } return max_value;}"
},
{
"code": null,
"e": 3873,
"s": 3402,
"text": "int main() { int t; cin >>t; while(t--){ int n; cin>>n; int arr[n]; for(int i = 0; i<n; i++){ cin >> arr[i]; } //Direct using STL Function int Max = INT_MIN; int Min = INT_MAX; for(int i =0; i< n; i++){ Max = max(Max, arr[i]); Min = min(Min, arr[i]); } // using create your one funtion // int Max = max(arr,n); // int Min = min(arr,n); cout << Max << \" \" << Min <<endl; }return 0;}"
},
{
"code": null,
"e": 3875,
"s": 3873,
"text": "0"
},
{
"code": null,
"e": 3896,
"s": 3875,
"text": "ujjwal013 months ago"
},
{
"code": null,
"e": 4271,
"s": 3896,
"text": "#include <iostream>\n#include<climits>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n\t//code\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t int n;\n\t cin>>n;\n\t int max=INT_MIN;\n\t int min=INT_MAX;\n\t int a[n];\n\t for(int i=0;i<n;i++){\n\t cin>>a[i];\n\t max=std::max(max,a[i]);\n\t min=std::min(min,a[i]);\n\t }\n\t cout<<max<<\" \"<<min<<endl;\n\t}\n\treturn 0;\n}"
},
{
"code": null,
"e": 4274,
"s": 4271,
"text": "+1"
},
{
"code": null,
"e": 4295,
"s": 4274,
"text": "adibose93 months ago"
},
{
"code": null,
"e": 4334,
"s": 4295,
"text": "#SIMPLE AND UNDERSTANDABLE PYTHON CODE"
},
{
"code": null,
"e": 4372,
"s": 4334,
"text": "#UPVOTING WOULD BE HIGHLY APPRICIABLE"
},
{
"code": null,
"e": 4798,
"s": 4374,
"text": "t=int(input()) #input for test casel=list() #created and empty list to store multiple arraysfor i in range(t): #loop so that for every test case, we can input an array n=int(input()) #size of array lst=list(map(int, input().split())) #creating array l.append(lst) #adding array to the list for arr in l: #looping through the arrays inside the list print(max(arr),min(arr)) #printing out the max and min values"
},
{
"code": null,
"e": 4944,
"s": 4798,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4980,
"s": 4944,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4990,
"s": 4980,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5000,
"s": 4990,
"text": "\nContest\n"
},
{
"code": null,
"e": 5063,
"s": 5000,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5211,
"s": 5063,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5419,
"s": 5211,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5525,
"s": 5419,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
KnockoutJS - Computed Observables | Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change.
Computed Observables can be chained.
this.varName = ko.computed(function(){
...
... // function code
...
},this);
Let us look at the following example which demonstrates the use of Computed Observables.
<!DOCTYPE html>
<head >
<title>KnockoutJS Computed Observables</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
</head>
<body>
<p>Enter first number: <input data-bind = "value: a" /></p>
<p>Enter second number: <input data-bind = "value: b"/></p>
<p>Average := <span data-bind="text: totalAvg"></span></p>
<script>
function MyViewModel() {
this.a = ko.observable(10);
this.b = ko.observable(40);
this.totalAvg = ko.computed(function() {
if(typeof(this.a()) !== "number" || typeof(this.b()) !== "number") {
this.a(Number(this.a())); //convert string to Number
this.b(Number(this.b())); //convert string to Number
}
total = (this.a() + this.b())/2 ;
return total;
},this);
}
ko.applyBindings(new MyViewModel());
</script>
</body>
</html>
In the following lines, first two are for accepting input values. Third line prints the average of these two numbers.
<p>Enter first number: <input data-bind = "value: a" /></p>
<p>Enter second number: <input data-bind = "value: b"/></p>
<p>Average := <span data-bind = "text: totalAvg"></span></p>
In the following lines, type of Observables a and b is number when they are initialized for the first time inside ViewModel. However, in KO every input accepted from UI is by default in the String format. So they need to be converted to Number so as to perform arithmetic operation on them.
this.totalAvg = ko.computed(function() {
if(typeof(this.a()) !== "number" || typeof(this.b()) !== "number") {
this.a(Number(this.a())); //convert string to Number
this.b(Number(this.b())); //convert string to Number
}
total = (this.a() + this.b())/2 ;
return total;
},this);
In the following line, the calculated average is displayed in the UI. Note that data-bind type of totalAvg is just text.
<p>Average := <span data-bind = "text: totalAvg"></span></p>
Let's carry out the following steps to see how the above code works −
Save the above code in computed-observable.htm file.
Save the above code in computed-observable.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Enter any 2 numbers in the text boxes and observe that the average is calculated.
Enter any 2 numbers in the text boxes and observe that the average is calculated.
Enter first number:
Enter second number:
Average := 25
Note that in the above example, the second parameter is provided as this to Computed function. It is not possible to refer to Observables a() and b() without providing this.
To overcome this, self variable is used which holds the reference of this. Doing so, there is no need to track this throughout the code. Instead, self can be used.
Following ViewModel code is rewritten for the above example using self.
function MyViewModel(){
self = this;
self.a = ko.observable(10);
self.b = ko.observable(40);
this.totalAvg = ko.computed(function() {
if(typeof(self.a()) !== "number" || typeof(self.b()) !== "number") {
self.a(Number(self.a())); //convert string to Number
self.b(Number(self.b())); //convert string to Number
}
total = (self.a() + self.b())/2 ;
return total;
});
}
A Computed Observable should be declared as Pure Computed Observable if that Observable is simply calculating and returning the value and not directly modifying the other objects or state. Pure Computed Observables helps Knockout to manage reevaluation and memory usage efficiently.
When a Computed Observable is returning primitive data type value (String, Boolean, Null, and Number) then its subscribers are notified if and only if the actual value change takes place. It means if an Observable has received the value same as the previous value, then its subscribers are not notified.
You can make Computed Observables always explicitly notify the observers, even though the new value is the same as the old by using the notify syntax as follows.
myViewModel.property = ko.pureComputed(function() {
return ...; // code logic goes here
}).extend({ notify: 'always' });
Too many expensive updates can result in performance issues. You can limit the number of notifications to be received from Observable using rateLimit attribute as follows.
// make sure there are updates no more than once per 100-millisecond period
myViewModel.property.extend({ rateLimit: 100 });
In certain situations, it might be necessary to find out if a property is a Computed Observable. Following functions can be used to identify the types of Observables.
ko.isComputed
Returns true if the property is Computed Observable.
ko.isObservable
Returns true if the property is Observable, Observable array, or Computed Observable.
ko.isWritableObservable
Returns true if Observable, Observable array, or Writable Computed Observable. (This is also called as ko.isWriteableObservable)
Computed Observable is derived from one or multiple other Observables, so it is read only. However, it is possible that one can make Computed Observable writable. For this you need to provide callback function that works on written values.
These writable Computed Observables work just like regular Observables. In addition, they require custom logic to be built for interfering read and write actions.
One can assign values to many Observables or Computed Observable properties using the chaining syntax as follows.
myViewModel.fullName('Tom Smith').age(45)
Following example demonstrates the use of Writable Computable Observable.
<!DOCTYPE html>
<head >
<title>KnockoutJS Writable Computed Observable</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
</head>
<body>
<p>Enter your birth Date: <input type = "date" data-bind = "value: rawDate" ></p>
<p><span data-bind = "text: yourAge"></span></p>
<script>
function MyViewModel() {
this.yourAge = ko.observable();
today = new Date();
rawDate = ko.observable();
this.rawDate = ko.pureComputed ({
read: function() {
return this.yourAge;
},
write: function(value) {
var b = Date.parse(value); // convert birth date into milliseconds
var t = Date.parse(today); // convert todays date into milliseconds
diff = t - b; // take difference
var y = Math.floor(diff/31449600000); // difference is converted
// into years. 31449600000
//milliseconds form a year.
var m = Math.floor((diff % 31449600000)/604800000/4.3); // calculating
// months.
// 604800000
// milliseconds
// form a week.
this.yourAge("You are " + y + " year(s) " + m +" months old.");
},
owner: this
});
}
ko.applyBindings(new MyViewModel());
</script>
</body>
</html>
In the above code, rawDate is pureComputed property accepted from UI. yourAge Observable is derived from rawDate.
Dates in JavaScript are manipulated in milliseconds. Hence, both the dates (today date and birth date) are converted into milliseconds and then the difference between them is converted back in years and months.
Let's carry out the following steps to see how the above code works −
Save the above code in writable_computed_observable.htm file.
Save the above code in writable_computed_observable.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Enter any birth date and observe that the age is calculated.
Enter any birth date and observe that the age is calculated.
Enter your birth Date:
38 Lectures
2 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2017,
"s": 1852,
"text": "Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change."
},
{
"code": null,
"e": 2054,
"s": 2017,
"text": "Computed Observables can be chained."
},
{
"code": null,
"e": 2142,
"s": 2054,
"text": "this.varName = ko.computed(function(){\n ...\n ... // function code\n ...\n},this);\n"
},
{
"code": null,
"e": 2231,
"s": 2142,
"text": "Let us look at the following example which demonstrates the use of Computed Observables."
},
{
"code": null,
"e": 3247,
"s": 2231,
"text": "<!DOCTYPE html>\n <head >\n <title>KnockoutJS Computed Observables</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"></script>\n </head>\n\n <body>\n <p>Enter first number: <input data-bind = \"value: a\" /></p>\n <p>Enter second number: <input data-bind = \"value: b\"/></p>\n <p>Average := <span data-bind=\"text: totalAvg\"></span></p>\n\n <script>\n function MyViewModel() {\n this.a = ko.observable(10);\n this.b = ko.observable(40);\n\n this.totalAvg = ko.computed(function() {\n\n if(typeof(this.a()) !== \"number\" || typeof(this.b()) !== \"number\") {\n this.a(Number(this.a())); //convert string to Number\n this.b(Number(this.b())); //convert string to Number\n }\n\n total = (this.a() + this.b())/2 ;\n return total;\n },this);\n }\n\n ko.applyBindings(new MyViewModel());\n </script>\n\n </body>\n</html>"
},
{
"code": null,
"e": 3365,
"s": 3247,
"text": "In the following lines, first two are for accepting input values. Third line prints the average of these two numbers."
},
{
"code": null,
"e": 3546,
"s": 3365,
"text": "<p>Enter first number: <input data-bind = \"value: a\" /></p>\n<p>Enter second number: <input data-bind = \"value: b\"/></p>\n<p>Average := <span data-bind = \"text: totalAvg\"></span></p>"
},
{
"code": null,
"e": 3837,
"s": 3546,
"text": "In the following lines, type of Observables a and b is number when they are initialized for the first time inside ViewModel. However, in KO every input accepted from UI is by default in the String format. So they need to be converted to Number so as to perform arithmetic operation on them."
},
{
"code": null,
"e": 4148,
"s": 3837,
"text": "this.totalAvg = ko.computed(function() {\n \n if(typeof(this.a()) !== \"number\" || typeof(this.b()) !== \"number\") {\n this.a(Number(this.a())); //convert string to Number\n this.b(Number(this.b())); //convert string to Number\n }\n \n total = (this.a() + this.b())/2 ;\n return total;\n},this);"
},
{
"code": null,
"e": 4269,
"s": 4148,
"text": "In the following line, the calculated average is displayed in the UI. Note that data-bind type of totalAvg is just text."
},
{
"code": null,
"e": 4330,
"s": 4269,
"text": "<p>Average := <span data-bind = \"text: totalAvg\"></span></p>"
},
{
"code": null,
"e": 4400,
"s": 4330,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 4453,
"s": 4400,
"text": "Save the above code in computed-observable.htm file."
},
{
"code": null,
"e": 4506,
"s": 4453,
"text": "Save the above code in computed-observable.htm file."
},
{
"code": null,
"e": 4540,
"s": 4506,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 4574,
"s": 4540,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 4656,
"s": 4574,
"text": "Enter any 2 numbers in the text boxes and observe that the average is calculated."
},
{
"code": null,
"e": 4738,
"s": 4656,
"text": "Enter any 2 numbers in the text boxes and observe that the average is calculated."
},
{
"code": null,
"e": 4759,
"s": 4738,
"text": "Enter first number: "
},
{
"code": null,
"e": 4781,
"s": 4759,
"text": "Enter second number: "
},
{
"code": null,
"e": 4795,
"s": 4781,
"text": "Average := 25"
},
{
"code": null,
"e": 4969,
"s": 4795,
"text": "Note that in the above example, the second parameter is provided as this to Computed function. It is not possible to refer to Observables a() and b() without providing this."
},
{
"code": null,
"e": 5133,
"s": 4969,
"text": "To overcome this, self variable is used which holds the reference of this. Doing so, there is no need to track this throughout the code. Instead, self can be used."
},
{
"code": null,
"e": 5205,
"s": 5133,
"text": "Following ViewModel code is rewritten for the above example using self."
},
{
"code": null,
"e": 5646,
"s": 5205,
"text": "function MyViewModel(){\n self = this;\n self.a = ko.observable(10);\n self.b = ko.observable(40);\n\n this.totalAvg = ko.computed(function() {\n \n if(typeof(self.a()) !== \"number\" || typeof(self.b()) !== \"number\") {\n self.a(Number(self.a())); //convert string to Number\n self.b(Number(self.b())); //convert string to Number\n }\n \n total = (self.a() + self.b())/2 ;\n return total;\n });\n}"
},
{
"code": null,
"e": 5929,
"s": 5646,
"text": "A Computed Observable should be declared as Pure Computed Observable if that Observable is simply calculating and returning the value and not directly modifying the other objects or state. Pure Computed Observables helps Knockout to manage reevaluation and memory usage efficiently."
},
{
"code": null,
"e": 6233,
"s": 5929,
"text": "When a Computed Observable is returning primitive data type value (String, Boolean, Null, and Number) then its subscribers are notified if and only if the actual value change takes place. It means if an Observable has received the value same as the previous value, then its subscribers are not notified."
},
{
"code": null,
"e": 6395,
"s": 6233,
"text": "You can make Computed Observables always explicitly notify the observers, even though the new value is the same as the old by using the notify syntax as follows."
},
{
"code": null,
"e": 6523,
"s": 6395,
"text": "myViewModel.property = ko.pureComputed(function() {\n return ...; // code logic goes here\n}).extend({ notify: 'always' });\n"
},
{
"code": null,
"e": 6695,
"s": 6523,
"text": "Too many expensive updates can result in performance issues. You can limit the number of notifications to be received from Observable using rateLimit attribute as follows."
},
{
"code": null,
"e": 6820,
"s": 6695,
"text": "// make sure there are updates no more than once per 100-millisecond period\nmyViewModel.property.extend({ rateLimit: 100 });"
},
{
"code": null,
"e": 6987,
"s": 6820,
"text": "In certain situations, it might be necessary to find out if a property is a Computed Observable. Following functions can be used to identify the types of Observables."
},
{
"code": null,
"e": 7001,
"s": 6987,
"text": "ko.isComputed"
},
{
"code": null,
"e": 7054,
"s": 7001,
"text": "Returns true if the property is Computed Observable."
},
{
"code": null,
"e": 7070,
"s": 7054,
"text": "ko.isObservable"
},
{
"code": null,
"e": 7156,
"s": 7070,
"text": "Returns true if the property is Observable, Observable array, or Computed Observable."
},
{
"code": null,
"e": 7180,
"s": 7156,
"text": "ko.isWritableObservable"
},
{
"code": null,
"e": 7309,
"s": 7180,
"text": "Returns true if Observable, Observable array, or Writable Computed Observable. (This is also called as ko.isWriteableObservable)"
},
{
"code": null,
"e": 7549,
"s": 7309,
"text": "Computed Observable is derived from one or multiple other Observables, so it is read only. However, it is possible that one can make Computed Observable writable. For this you need to provide callback function that works on written values."
},
{
"code": null,
"e": 7712,
"s": 7549,
"text": "These writable Computed Observables work just like regular Observables. In addition, they require custom logic to be built for interfering read and write actions."
},
{
"code": null,
"e": 7826,
"s": 7712,
"text": "One can assign values to many Observables or Computed Observable properties using the chaining syntax as follows."
},
{
"code": null,
"e": 7869,
"s": 7826,
"text": "myViewModel.fullName('Tom Smith').age(45)\n"
},
{
"code": null,
"e": 7943,
"s": 7869,
"text": "Following example demonstrates the use of Writable Computable Observable."
},
{
"code": null,
"e": 9823,
"s": 7943,
"text": "<!DOCTYPE html>\n <head >\n <title>KnockoutJS Writable Computed Observable</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"></script>\n </head>\n\n <body>\n <p>Enter your birth Date: <input type = \"date\" data-bind = \"value: rawDate\" ></p>\n <p><span data-bind = \"text: yourAge\"></span></p>\n\n <script>\n function MyViewModel() {\n this.yourAge = ko.observable();\n today = new Date();\n rawDate = ko.observable();\n\n this.rawDate = ko.pureComputed ({\n\n read: function() {\n return this.yourAge;\n },\n\n write: function(value) {\n var b = Date.parse(value); // convert birth date into milliseconds\n var t = Date.parse(today); // convert todays date into milliseconds\n diff = t - b; // take difference\n var y = Math.floor(diff/31449600000); // difference is converted\n // into years. 31449600000\n //milliseconds form a year.\n\n var m = Math.floor((diff % 31449600000)/604800000/4.3); // calculating\n // months.\n // 604800000\n // milliseconds\n // form a week.\n\n this.yourAge(\"You are \" + y + \" year(s) \" + m +\" months old.\");\n },\n owner: this\n });\n }\n\n ko.applyBindings(new MyViewModel());\n </script>\n\n </body>\n</html>"
},
{
"code": null,
"e": 9937,
"s": 9823,
"text": "In the above code, rawDate is pureComputed property accepted from UI. yourAge Observable is derived from rawDate."
},
{
"code": null,
"e": 10148,
"s": 9937,
"text": "Dates in JavaScript are manipulated in milliseconds. Hence, both the dates (today date and birth date) are converted into milliseconds and then the difference between them is converted back in years and months."
},
{
"code": null,
"e": 10218,
"s": 10148,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 10280,
"s": 10218,
"text": "Save the above code in writable_computed_observable.htm file."
},
{
"code": null,
"e": 10342,
"s": 10280,
"text": "Save the above code in writable_computed_observable.htm file."
},
{
"code": null,
"e": 10376,
"s": 10342,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 10410,
"s": 10376,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 10471,
"s": 10410,
"text": "Enter any birth date and observe that the age is calculated."
},
{
"code": null,
"e": 10532,
"s": 10471,
"text": "Enter any birth date and observe that the age is calculated."
},
{
"code": null,
"e": 10557,
"s": 10532,
"text": "Enter your birth Date: "
},
{
"code": null,
"e": 10592,
"s": 10559,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10612,
"s": 10592,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 10619,
"s": 10612,
"text": " Print"
},
{
"code": null,
"e": 10630,
"s": 10619,
"text": " Add Notes"
}
]
|
Can I get the count of repeated values in a column with MySQL? | Yes, you can use ORDER BY DESC with GROUP BY. Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> PostMessage varchar(100)
-> );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(PostMessage) values('Hi');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(PostMessage) values('Hello');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(PostMessage) values('Hi');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(PostMessage) values('Awesome');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(PostMessage) values('Hello');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(PostMessage) values('Hi');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(PostMessage) values('Awesome');
Query OK, 1 row affected (0.33 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------------+
| Id | PostMessage |
+----+-------------+
| 1 | Hi |
| 2 | Hello |
| 3 | Hi |
| 4 | Awesome |
| 5 | Hello |
| 6 | Hi |
| 7 | Awesome |
+----+-------------+
7 rows in set (0.00 sec)
Following is the query to get the highest amount of a value in a MySQL database −
mysql> select PostMessage,count(Id) from DemoTable group by PostMessage
-> order by count(Id) DESC;
This will produce the following output −
+-------------+-----------+
| PostMessage | count(Id) |
+-------------+-----------+
| Hi | 3 |
| Hello | 2 |
| Awesome | 2 |
+-------------+-----------+
3 rows in set (0.00 sec)
If you want only highest, you can use the following query −
mysql> select PostMessage,count(Id) from DemoTable group by PostMessage having count(Id) > 2;
This will produce the following output −
+-------------+-----------+
| PostMessage | count(Id) |
+-------------+-----------+
| Hi | 3 |
+-------------+-----------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "Yes, you can use ORDER BY DESC with GROUP BY. Let us first create a table −"
},
{
"code": null,
"e": 1303,
"s": 1138,
"text": "mysql> create table DemoTable\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> PostMessage varchar(100)\n -> );\nQuery OK, 0 rows affected (0.69 sec)"
},
{
"code": null,
"e": 1359,
"s": 1303,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2025,
"s": 1359,
"text": "mysql> insert into DemoTable(PostMessage) values('Hi');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable(PostMessage) values('Hello');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DemoTable(PostMessage) values('Hi');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DemoTable(PostMessage) values('Awesome');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into DemoTable(PostMessage) values('Hello');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable(PostMessage) values('Hi');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into DemoTable(PostMessage) values('Awesome');\nQuery OK, 1 row affected (0.33 sec)"
},
{
"code": null,
"e": 2085,
"s": 2025,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2116,
"s": 2085,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2157,
"s": 2116,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2413,
"s": 2157,
"text": "+----+-------------+\n| Id | PostMessage |\n+----+-------------+\n| 1 | Hi |\n| 2 | Hello |\n| 3 | Hi |\n| 4 | Awesome |\n| 5 | Hello |\n| 6 | Hi |\n| 7 | Awesome |\n+----+-------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2495,
"s": 2413,
"text": "Following is the query to get the highest amount of a value in a MySQL database −"
},
{
"code": null,
"e": 2599,
"s": 2495,
"text": "mysql> select PostMessage,count(Id) from DemoTable group by PostMessage\n -> order by count(Id) DESC;"
},
{
"code": null,
"e": 2640,
"s": 2599,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2861,
"s": 2640,
"text": "+-------------+-----------+\n| PostMessage | count(Id) |\n+-------------+-----------+\n| Hi | 3 |\n| Hello | 2 |\n| Awesome | 2 |\n+-------------+-----------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2921,
"s": 2861,
"text": "If you want only highest, you can use the following query −"
},
{
"code": null,
"e": 3016,
"s": 2921,
"text": "mysql> select PostMessage,count(Id) from DemoTable group by PostMessage having count(Id) > 2;"
},
{
"code": null,
"e": 3057,
"s": 3016,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3221,
"s": 3057,
"text": "+-------------+-----------+\n| PostMessage | count(Id) |\n+-------------+-----------+\n| Hi | 3 |\n+-------------+-----------+\n1 row in set (0.00 sec)"
}
]
|
Selenium - Locators | Locating elements in Selenium WebDriver is performed with the help of findElement() and findElements() methods provided by WebDriver and WebElement class.
findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria.
findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria.
findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list.
findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list.
The following table lists all the Java syntax for locating elements in Selenium WebDriver.
Now let us understand the practical usage of each of the locator methods with the help of https://www.calculator.net
Here an object is accessed with the help of IDs. In this case, it is the ID of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity).
driver.findElement(By.id("cdensity")).sendKeys("10");
Here an object is accessed with the help of names. In this case, it is the name of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity).
driver.findElement(By.name("cdensity")).sendKeys("10");
Here an object is accessed with the help of Class Names. In this case, it is the Class name of the WebElement. The Value can be accessed with the help of the gettext method.
List<WebElement> byclass = driver.findElements(By.className("smalltext smtb"));
The DOM Tag Name of an element can be used to locate that particular element in the WebDriver. It is very easy to handle tables with the help of this method. Take a look at the following code.
WebElement table = driver.findElement(By.id("calctable"));
List<WebElement> row = table.findElements(By.tagName("tr"));
int rowcount = row.size();
This method helps to locate a link element with matching visible text.
driver.findElements(By.linkText("Volume")).click();
This methods helps locate a link element with partial matching visible text.
driver.findElement(By.partialLinkText("Volume")).click();
The CSS is used as a method to identify the webobject, however NOT all browsers support CSS identification.
WebElement loginButton = driver.findElement(By.cssSelector("input.login"));
XPath stands for XML path language. It is a query language for selecting nodes from an XML document. XPath is based on the tree representation of XML documents and provides the ability to navigate around the tree by selecting nodes using a variety of criteria.
driver.findElement(By.xpath(".//*[@id = 'content']/table[1]/tbody/tr/td/table/tbody/tr[2]/td[1]/input")).sendkeys("100");
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": 2030,
"s": 1875,
"text": "Locating elements in Selenium WebDriver is performed with the help of findElement() and findElements() methods provided by WebDriver and WebElement class."
},
{
"code": null,
"e": 2204,
"s": 2030,
"text": "findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria."
},
{
"code": null,
"e": 2378,
"s": 2204,
"text": "findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria."
},
{
"code": null,
"e": 2505,
"s": 2378,
"text": "findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list."
},
{
"code": null,
"e": 2632,
"s": 2505,
"text": "findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list."
},
{
"code": null,
"e": 2723,
"s": 2632,
"text": "The following table lists all the Java syntax for locating elements in Selenium WebDriver."
},
{
"code": null,
"e": 2840,
"s": 2723,
"text": "Now let us understand the practical usage of each of the locator methods with the help of https://www.calculator.net"
},
{
"code": null,
"e": 3027,
"s": 2840,
"text": "Here an object is accessed with the help of IDs. In this case, it is the ID of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity)."
},
{
"code": null,
"e": 3081,
"s": 3027,
"text": "driver.findElement(By.id(\"cdensity\")).sendKeys(\"10\");"
},
{
"code": null,
"e": 3272,
"s": 3081,
"text": "Here an object is accessed with the help of names. In this case, it is the name of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity)."
},
{
"code": null,
"e": 3328,
"s": 3272,
"text": "driver.findElement(By.name(\"cdensity\")).sendKeys(\"10\");"
},
{
"code": null,
"e": 3502,
"s": 3328,
"text": "Here an object is accessed with the help of Class Names. In this case, it is the Class name of the WebElement. The Value can be accessed with the help of the gettext method."
},
{
"code": null,
"e": 3582,
"s": 3502,
"text": "List<WebElement> byclass = driver.findElements(By.className(\"smalltext smtb\"));"
},
{
"code": null,
"e": 3775,
"s": 3582,
"text": "The DOM Tag Name of an element can be used to locate that particular element in the WebDriver. It is very easy to handle tables with the help of this method. Take a look at the following code."
},
{
"code": null,
"e": 3922,
"s": 3775,
"text": "WebElement table = driver.findElement(By.id(\"calctable\"));\nList<WebElement> row = table.findElements(By.tagName(\"tr\"));\nint rowcount = row.size();"
},
{
"code": null,
"e": 3993,
"s": 3922,
"text": "This method helps to locate a link element with matching visible text."
},
{
"code": null,
"e": 4045,
"s": 3993,
"text": "driver.findElements(By.linkText(\"Volume\")).click();"
},
{
"code": null,
"e": 4122,
"s": 4045,
"text": "This methods helps locate a link element with partial matching visible text."
},
{
"code": null,
"e": 4180,
"s": 4122,
"text": "driver.findElement(By.partialLinkText(\"Volume\")).click();"
},
{
"code": null,
"e": 4288,
"s": 4180,
"text": "The CSS is used as a method to identify the webobject, however NOT all browsers support CSS identification."
},
{
"code": null,
"e": 4364,
"s": 4288,
"text": "WebElement loginButton = driver.findElement(By.cssSelector(\"input.login\"));"
},
{
"code": null,
"e": 4625,
"s": 4364,
"text": "XPath stands for XML path language. It is a query language for selecting nodes from an XML document. XPath is based on the tree representation of XML documents and provides the ability to navigate around the tree by selecting nodes using a variety of criteria."
},
{
"code": null,
"e": 4747,
"s": 4625,
"text": "driver.findElement(By.xpath(\".//*[@id = 'content']/table[1]/tbody/tr/td/table/tbody/tr[2]/td[1]/input\")).sendkeys(\"100\");"
},
{
"code": null,
"e": 4782,
"s": 4747,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4794,
"s": 4782,
"text": " Aditya Dua"
},
{
"code": null,
"e": 4830,
"s": 4794,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 4844,
"s": 4830,
"text": " Arun Motoori"
},
{
"code": null,
"e": 4881,
"s": 4844,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 4903,
"s": 4881,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4936,
"s": 4903,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4950,
"s": 4936,
"text": " Arun Motoori"
},
{
"code": null,
"e": 4985,
"s": 4950,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 4999,
"s": 4985,
"text": " Arun Motoori"
},
{
"code": null,
"e": 5036,
"s": 4999,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 5050,
"s": 5036,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5057,
"s": 5050,
"text": " Print"
},
{
"code": null,
"e": 5068,
"s": 5057,
"text": " Add Notes"
}
]
|
N Queen Problem | This problem is to find an arrangement of N queens on a chess board, such that no queen can attack any other queens on the board.
The chess queens can attack in any direction as horizontal, vertical, horizontal and diagonal way.
A binary matrix is used to display the positions of N Queens, where no queens can attack other queens.
Input:
The size of a chess board. Generally, it is 8. as (8 x 8 is the size of a normal chess board.)
Output:
The matrix that represents in which row and column the N Queens can be placed.
If the solution does not exist, it will return false.
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
In this output, the value 1 indicates the correct place for the queens.
The 0 denotes the blank spaces on the chess board.
isValid(board, row, col)
Output − True when placing a queen in row and place position is a valid or not.
Begin
if there is a queen at the left of current col, then
return false
if there is a queen at the left upper diagonal, then
return false
if there is a queen at the left lower diagonal, then
return false;
return true //otherwise it is valid place
End
solveNQueen(board, col)
Input − The chess board, the col where the queen is trying to be placed.
Output − The position matrix where queens are placed.
Begin
if all columns are filled, then
return true
for each row of the board, do
if isValid(board, i, col), then
set queen at place (i, col) in the board
if solveNQueen(board, col+1) = true, then
return true
otherwise remove queen from place (i, col) from board.
done
return false
End
#include<iostream>
using namespace std;
#define N 8
void printBoard(int board[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << board[i][j] << " ";
cout << endl;
}
}
bool isValid(int board[N][N], int row, int col) {
for (int i = 0; i < col; i++) //check whether there is queen in the left or not
if (board[row][i])
return false;
for (int i=row, j=col; i>=0 && j>=0; i--, j--)
if (board[i][j]) //check whether there is queen in the left upper diagonal or not
return false;
for (int i=row, j=col; j>=0 && i<N; i++, j--)
if (board[i][j]) //check whether there is queen in the left lower diagonal or not
return false;
return true;
}
bool solveNQueen(int board[N][N], int col) {
if (col >= N) //when N queens are placed successfully
return true;
for (int i = 0; i < N; i++) { //for each row, check placing of queen is possible or not
if (isValid(board, i, col) ) {
board[i][col] = 1; //if validate, place the queen at place (i, col)
if ( solveNQueen(board, col + 1)) //Go for the other columns recursively
return true;
board[i][col] = 0; //When no place is vacant remove that queen
}
}
return false; //when no possible order is found
}
bool checkSolution() {
int board[N][N];
for(int i = 0; i<N; i++)
for(int j = 0; j<N; j++)
board[i][j] = 0; //set all elements to 0
if ( solveNQueen(board, 0) == false ) { //starting from 0th column
cout << "Solution does not exist";
return false;
}
printBoard(board);
return true;
}
int main() {
checkSolution();
}
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0 | [
{
"code": null,
"e": 1192,
"s": 1062,
"text": "This problem is to find an arrangement of N queens on a chess board, such that no queen can attack any other queens on the board."
},
{
"code": null,
"e": 1291,
"s": 1192,
"text": "The chess queens can attack in any direction as horizontal, vertical, horizontal and diagonal way."
},
{
"code": null,
"e": 1394,
"s": 1291,
"text": "A binary matrix is used to display the positions of N Queens, where no queens can attack other queens."
},
{
"code": null,
"e": 1890,
"s": 1394,
"text": "Input:\nThe size of a chess board. Generally, it is 8. as (8 x 8 is the size of a normal chess board.)\nOutput:\nThe matrix that represents in which row and column the N Queens can be placed.\nIf the solution does not exist, it will return false.\n\n1 0 0 0 0 0 0 0\n0 0 0 0 0 0 1 0\n0 0 0 0 1 0 0 0\n0 0 0 0 0 0 0 1\n0 1 0 0 0 0 0 0\n0 0 0 1 0 0 0 0\n0 0 0 0 0 1 0 0\n0 0 1 0 0 0 0 0\n\nIn this output, the value 1 indicates the correct place for the queens.\nThe 0 denotes the blank spaces on the chess board."
},
{
"code": null,
"e": 1915,
"s": 1890,
"text": "isValid(board, row, col)"
},
{
"code": null,
"e": 1995,
"s": 1915,
"text": "Output − True when placing a queen in row and place position is a valid or not."
},
{
"code": null,
"e": 2276,
"s": 1995,
"text": "Begin\n if there is a queen at the left of current col, then\n return false\n if there is a queen at the left upper diagonal, then\n return false\n if there is a queen at the left lower diagonal, then\n return false;\n return true //otherwise it is valid place\nEnd"
},
{
"code": null,
"e": 2300,
"s": 2276,
"text": "solveNQueen(board, col)"
},
{
"code": null,
"e": 2373,
"s": 2300,
"text": "Input − The chess board, the col where the queen is trying to be placed."
},
{
"code": null,
"e": 2428,
"s": 2373,
"text": "Output − The position matrix where queens are placed."
},
{
"code": null,
"e": 2775,
"s": 2428,
"text": "Begin\n if all columns are filled, then\n return true\n for each row of the board, do\n if isValid(board, i, col), then\n set queen at place (i, col) in the board\n if solveNQueen(board, col+1) = true, then\n return true\n otherwise remove queen from place (i, col) from board.\n done\n return false\nEnd"
},
{
"code": null,
"e": 4546,
"s": 2775,
"text": "#include<iostream>\nusing namespace std;\n#define N 8\n\nvoid printBoard(int board[N][N]) {\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++)\n cout << board[i][j] << \" \";\n cout << endl;\n }\n}\n\nbool isValid(int board[N][N], int row, int col) {\n for (int i = 0; i < col; i++) //check whether there is queen in the left or not\n if (board[row][i])\n return false;\n for (int i=row, j=col; i>=0 && j>=0; i--, j--)\n if (board[i][j]) //check whether there is queen in the left upper diagonal or not\n return false;\n for (int i=row, j=col; j>=0 && i<N; i++, j--)\n if (board[i][j]) //check whether there is queen in the left lower diagonal or not\n return false;\n return true;\n}\n\nbool solveNQueen(int board[N][N], int col) {\n if (col >= N) //when N queens are placed successfully\n return true;\n for (int i = 0; i < N; i++) { //for each row, check placing of queen is possible or not\n if (isValid(board, i, col) ) {\n board[i][col] = 1; //if validate, place the queen at place (i, col)\n if ( solveNQueen(board, col + 1)) //Go for the other columns recursively\n return true;\n \n board[i][col] = 0; //When no place is vacant remove that queen\n }\n }\n return false; //when no possible order is found\n}\n\nbool checkSolution() {\n int board[N][N];\n for(int i = 0; i<N; i++)\n for(int j = 0; j<N; j++)\n board[i][j] = 0; //set all elements to 0\n \n if ( solveNQueen(board, 0) == false ) { //starting from 0th column\n cout << \"Solution does not exist\";\n return false;\n }\n printBoard(board);\n return true;\n}\n\nint main() {\n checkSolution();\n}"
},
{
"code": null,
"e": 4674,
"s": 4546,
"text": "1 0 0 0 0 0 0 0\n0 0 0 0 0 0 1 0\n0 0 0 0 1 0 0 0\n0 0 0 0 0 0 0 1\n0 1 0 0 0 0 0 0\n0 0 0 1 0 0 0 0\n0 0 0 0 0 1 0 0\n0 0 1 0 0 0 0 0"
}
]
|
Display databases in MongoDB | To display number of databases in MongoDB, you need to create atleast one document in a database.
Let’s say, you have created a database, but did not added any document in it. Then in the list of databases that particular database won’t be visible.
Following is the query to create a database −
> use app;
switched to db app
Following is the query to display all databases −
> show dbs;
This will produce the following output. The new database “app” won’t be visible since we haven’t added atleast one document in it −
admin 0.002GB
business 0.000GB
config 0.000GB
local 0.000GB
main 0.000GB
my 0.001GB
sample 0.003GB
sampleDemo 0.000GB
studentSearch 0.000GB
test 0.022GB
university 0.000GB
web 0.001GB
webcustomertracker 0.000GB
Let us first create a collection with documents in the “app” database −
> db.demo.insert({"StudentName":"Chris"});
WriteResult({ "nInserted" : 1 })
Following is the query to display all documents from a collection with the help of find() method −
> db.demo.find();
This will produce the following output −
{ "_id" : ObjectId("5e07250e25ddae1f53b62204"), "StudentName" : "Chris" }
Here is the query to display all the databases in MongoDB −
> show dbs;
This will produce the following output. Now the “app” database will be visible in the list of databases −
admin 0.002GB
app 0.000GB
business 0.000GB
config 0.000GB
local 0.000GB
main 0.000GB
my 0.001GB
sample 0.003GB
sampleDemo 0.000GB
studentSearch 0.000GB
test 0.022GB
university 0.000GB
web 0.001GB
webcustomertracker 0.000GB | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "To display number of databases in MongoDB, you need to create atleast one document in a database."
},
{
"code": null,
"e": 1311,
"s": 1160,
"text": "Let’s say, you have created a database, but did not added any document in it. Then in the list of databases that particular database won’t be visible."
},
{
"code": null,
"e": 1357,
"s": 1311,
"text": "Following is the query to create a database −"
},
{
"code": null,
"e": 1387,
"s": 1357,
"text": "> use app;\nswitched to db app"
},
{
"code": null,
"e": 1437,
"s": 1387,
"text": "Following is the query to display all databases −"
},
{
"code": null,
"e": 1449,
"s": 1437,
"text": "> show dbs;"
},
{
"code": null,
"e": 1581,
"s": 1449,
"text": "This will produce the following output. The new database “app” won’t be visible since we haven’t added atleast one document in it −"
},
{
"code": null,
"e": 1904,
"s": 1581,
"text": "admin 0.002GB\nbusiness 0.000GB\nconfig 0.000GB\nlocal 0.000GB\nmain 0.000GB\nmy 0.001GB\nsample 0.003GB\nsampleDemo 0.000GB\nstudentSearch 0.000GB\ntest 0.022GB\nuniversity 0.000GB\nweb 0.001GB\nwebcustomertracker 0.000GB"
},
{
"code": null,
"e": 1976,
"s": 1904,
"text": "Let us first create a collection with documents in the “app” database −"
},
{
"code": null,
"e": 2052,
"s": 1976,
"text": "> db.demo.insert({\"StudentName\":\"Chris\"});\nWriteResult({ \"nInserted\" : 1 })"
},
{
"code": null,
"e": 2151,
"s": 2052,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2169,
"s": 2151,
"text": "> db.demo.find();"
},
{
"code": null,
"e": 2210,
"s": 2169,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2284,
"s": 2210,
"text": "{ \"_id\" : ObjectId(\"5e07250e25ddae1f53b62204\"), \"StudentName\" : \"Chris\" }"
},
{
"code": null,
"e": 2344,
"s": 2284,
"text": "Here is the query to display all the databases in MongoDB −"
},
{
"code": null,
"e": 2356,
"s": 2344,
"text": "> show dbs;"
},
{
"code": null,
"e": 2462,
"s": 2356,
"text": "This will produce the following output. Now the “app” database will be visible in the list of databases −"
},
{
"code": null,
"e": 2881,
"s": 2462,
"text": "admin 0.002GB\napp 0.000GB\nbusiness 0.000GB\nconfig 0.000GB\nlocal 0.000GB\nmain 0.000GB\nmy 0.001GB\nsample 0.003GB\nsampleDemo 0.000GB\nstudentSearch 0.000GB\ntest 0.022GB\nuniversity 0.000GB\nweb 0.001GB\nwebcustomertracker 0.000GB"
}
]
|
How to validate email address in JavaScript? | To validate email address in JavaScript, check the condition for “@” and “.” i.e. for [email protected] . Let’s try the following code to validate email
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var emailID;
function validateEmail(emailID) {
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
document.write("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
document.write(validateEmail("[email protected]"));
</script>
</body>
</html> | [
{
"code": null,
"e": 1211,
"s": 1062,
"text": "To validate email address in JavaScript, check the condition for “@” and “.” i.e. for [email protected] . Let’s try the following code to validate email"
},
{
"code": null,
"e": 1221,
"s": 1211,
"text": "Live Demo"
},
{
"code": null,
"e": 1762,
"s": 1221,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var emailID;\n function validateEmail(emailID) {\n atpos = emailID.indexOf(\"@\");\n dotpos = emailID.lastIndexOf(\".\");\n if (atpos < 1 || ( dotpos - atpos < 2 )) {\n document.write(\"Please enter correct email ID\")\n document.myForm.EMail.focus() ;\n return false;\n }\n return( true );\n }\n document.write(validateEmail(\"[email protected]\"));\n </script>\n </body>\n</html>"
}
]
|
Find the Second Largest Element in a Linked List - GeeksforGeeks | 29 Jun, 2021
Given a Linked list of integer data. The task is to write a program that efficiently finds the second largest element present in the Linked List.Examples:
Input : List = 12 -> 35 -> 1 -> 10 -> 34 -> 1
Output : The second largest element is 34.
Input : List = 10 -> 5 -> 10
Output : The second largest element is 5.
A Simple Solution will be to first sort the linked list in descending order and then print the second element from the sorted linked list. The time complexity of this solution is O(nlogn).A Better Solution is to traverse the Linked list twice. In the first traversal find the maximum element. In the second traversal find the greatest element less than the element obtained in first traversal. The time complexity of this solution is O(n).A more Efficient Solution can be to find the second largest element in a single traversal. Below is the complete algorithm for doing this:
1) Initialize two variables first and second to INT_MIN as,
first = second = INT_MIN
2) Start traversing the Linked List,
a) If the current element in Linked List say list[i] is greater
than first. Then update first and second as,
second = first
first = list[i]
b) If the current element is in between first and second,
then update second to store the value of current variable as
second = list[i]
3) Return the value stored in second node.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print second largest// value in a linked list#include <climits>#include <iostream> using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; // Function to add a node at the// beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Function to count size of listint listSize(struct Node* node){ int count = 0; while (node != NULL) { count++; node = node->next; } return count;} // Function to print the second// largest elementvoid print2largest(struct Node* head){ int i, first, second; int list_size = listSize(head); /* There should be atleast two elements */ if (list_size < 2) { cout << "Invalid Input"; return; } first = second = INT_MIN; struct Node* temp = head; while (temp != NULL) { if (temp->data > first) { second = first; first = temp->data; } // If current node's data is in between // first and second then update second else if (temp->data > second && temp->data != first) second = temp->data; temp = temp->next; } if (second == INT_MIN) cout << "There is no second largest element\n"; else cout << "The second largest element is " << second;} // Driver program to test above functionint main(){ struct Node* start = NULL; /* The constructed linked list is: 12 -> 35 -> 1 -> 10 -> 34 -> 1 */ push(&start, 1); push(&start, 34); push(&start, 10); push(&start, 1); push(&start, 35); push(&start, 12); print2largest(start); return 0;}
// Java program to print second largest// value in a linked listclass GFG{ // A linked list nodestatic class Node{ int data; Node next;}; // Function to add a node at the// beginning of Linked Liststatic Node push( Node head_ref, int new_data){ // allocate node / Node new_node = new Node(); // put in the data / new_node.data = new_data; // link the old list off the new node / new_node.next = (head_ref); // move the head to point to the new node / (head_ref) = new_node; return head_ref;} // Function to count size of liststatic int listSize( Node node){ int count = 0; while (node != null) { count++; node = node.next; } return count;} // Function to print the second// largest elementstatic void print2largest( Node head){ int i, first, second; int list_size = listSize(head); // There should be atleast two elements / if (list_size < 2) { System.out.print("Invalid Input"); return; } first = second = Integer.MIN_VALUE; Node temp = head; while (temp != null) { if (temp.data > first) { second = first; first = temp.data; } // If current node's data is in between // first and second then update second else if (temp.data > second && temp.data != first) second = temp.data; temp = temp.next; } if (second == Integer.MIN_VALUE) System.out.print( "There is no second largest element\n"); else System.out.print ("The second largest element is " + second);} // Driver program to test above functionpublic static void main(String args[]){ Node start = null; // The constructed linked list is: //12 . 35 . 1 . 10 . 34 . 1 start=push(start, 1); start=push(start, 34); start=push(start, 10); start=push(start, 1); start=push(start, 35); start=push(start, 12); print2largest(start);}} // This code is contributed by Arnab Kundu
# Python3 program to print second largest# value in a linked list # A linked list nodeclass Node : def __init__(self): self.data = 0 self.next = None # Function to add a node at the# beginning of Linked Listdef push( head_ref, new_data) : # allocate node / new_node = Node() # put in the data / new_node.data = new_data # link the old list off the new node / new_node.next = (head_ref) # move the head to point to the new node / (head_ref) = new_node return head_ref # Function to count size of listdef listSize( node): count = 0 while (node != None): count = count + 1 node = node.next return count # Function to print the second# largest elementdef print2largest( head): i = 0 first = 0 second = 0 list_size = listSize(head) # There should be atleast two elements / if (list_size < 2) : print("Invalid Input") return first = second = -323767 temp = head while (temp != None): if (temp.data > first) : second = first first = temp.data # If current node's data is in between # first and second then update second elif (temp.data > second and temp.data != first) : second = temp.data temp = temp.next if (second == -323767) : print( "There is no second largest element\n") else: print ("The second largest element is " , second) # Driver code start = None # The constructed linked list is:# 12 . 35 . 1 . 10 . 34 . 1start = push(start, 1)start = push(start, 34)start = push(start, 10)start = push(start, 1)start = push(start, 35)start = push(start, 12) print2largest(start) # This code is contributed by Arnab Kundu
// C# program to print second largest// value in a linked listusing System; class GFG{ // A linked list nodepublic class Node{ public int data; public Node next;}; // Function to add a node at the// beginning of Linked Liststatic Node push( Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = (head_ref); // move the head to point to the new node (head_ref) = new_node; return head_ref;} // Function to count size of liststatic int listSize( Node node){ int count = 0; while (node != null) { count++; node = node.next; } return count;} // Function to print the second// largest elementstatic void print2largest(Node head){ int first, second; int list_size = listSize(head); // There should be atleast two elements if (list_size < 2) { Console.Write("Invalid Input"); return; } first = second = int.MinValue; Node temp = head; while (temp != null) { if (temp.data > first) { second = first; first = temp.data; } // If current node's data is in between // first and second then update second else if (temp.data > second && temp.data != first) second = temp.data; temp = temp.next; } if (second == int.MinValue) Console.Write( "There is no second" + " largest element\n"); else Console.Write("The second largest " + "element is " + second);} // Driver Codepublic static void Main(String []args){ Node start = null; // The constructed linked list is: //12 . 35 . 1 . 10 . 34 . 1 start = push(start, 1); start = push(start, 34); start = push(start, 10); start = push(start, 1); start = push(start, 35); start = push(start, 12); print2largest(start);}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to print second largest // value in a linked list // A linked list node class Node { constructor() { this.data = 0; this.next = null; } } // Function to add a node at the // beginning of Linked List function push(head_ref, new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; return head_ref; } // Function to count size of list function listSize(node) { var count = 0; while (node != null) { count++; node = node.next; } return count; } // Function to print the second // largest element function print2largest(head) { var first, second; var list_size = listSize(head); // There should be atleast two elements if (list_size < 2) { document.write("Invalid Input"); return; } first = second = -2147483648; var temp = head; while (temp != null) { if (temp.data > first) { second = first; first = temp.data; } // If current node's data is in between // first and second then update second else if (temp.data > second && temp.data != first) second = temp.data; temp = temp.next; } if (second == -2147483648) document.write("There is no second" + " largest element<br>"); else document.write("The second largest " + "element is " + second); } // Driver Code var start = null; // The constructed linked list is: //12 . 35 . 1 . 10 . 34 . 1 start = push(start, 1); start = push(start, 34); start = push(start, 10); start = push(start, 1); start = push(start, 35); start = push(start, 12); print2largest(start); </script>
The second largest element is 34
andrew1234
29AjayKumar
Akanksha_Rai
rdtank
Sorting Quiz
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Delete a node in a Doubly Linked List
Given a linked list which is sorted, how will you insert in sorted way
Insert a node at a specific position in a linked list
Circular Linked List | Set 2 (Traversal)
Program to implement Singly Linked List in C++ using class
Swap nodes in a linked list without swapping data
Priority Queue using Linked List
Circular Singly Linked List | Insertion
Real-time application of Data Structures
Insertion Sort for Singly Linked List | [
{
"code": null,
"e": 24567,
"s": 24539,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 24724,
"s": 24567,
"text": "Given a Linked list of integer data. The task is to write a program that efficiently finds the second largest element present in the Linked List.Examples: "
},
{
"code": null,
"e": 24885,
"s": 24724,
"text": "Input : List = 12 -> 35 -> 1 -> 10 -> 34 -> 1\nOutput : The second largest element is 34.\n\nInput : List = 10 -> 5 -> 10\nOutput : The second largest element is 5."
},
{
"code": null,
"e": 25467,
"s": 24887,
"text": "A Simple Solution will be to first sort the linked list in descending order and then print the second element from the sorted linked list. The time complexity of this solution is O(nlogn).A Better Solution is to traverse the Linked list twice. In the first traversal find the maximum element. In the second traversal find the greatest element less than the element obtained in first traversal. The time complexity of this solution is O(n).A more Efficient Solution can be to find the second largest element in a single traversal. Below is the complete algorithm for doing this: "
},
{
"code": null,
"e": 25947,
"s": 25467,
"text": "1) Initialize two variables first and second to INT_MIN as,\n first = second = INT_MIN\n2) Start traversing the Linked List,\n a) If the current element in Linked List say list[i] is greater\n than first. Then update first and second as,\n second = first\n first = list[i]\n b) If the current element is in between first and second,\n then update second to store the value of current variable as\n second = list[i]\n3) Return the value stored in second node."
},
{
"code": null,
"e": 26000,
"s": 25947,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26004,
"s": 26000,
"text": "C++"
},
{
"code": null,
"e": 26009,
"s": 26004,
"text": "Java"
},
{
"code": null,
"e": 26017,
"s": 26009,
"text": "Python3"
},
{
"code": null,
"e": 26020,
"s": 26017,
"text": "C#"
},
{
"code": null,
"e": 26031,
"s": 26020,
"text": "Javascript"
},
{
"code": "// C++ program to print second largest// value in a linked list#include <climits>#include <iostream> using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; // Function to add a node at the// beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Function to count size of listint listSize(struct Node* node){ int count = 0; while (node != NULL) { count++; node = node->next; } return count;} // Function to print the second// largest elementvoid print2largest(struct Node* head){ int i, first, second; int list_size = listSize(head); /* There should be atleast two elements */ if (list_size < 2) { cout << \"Invalid Input\"; return; } first = second = INT_MIN; struct Node* temp = head; while (temp != NULL) { if (temp->data > first) { second = first; first = temp->data; } // If current node's data is in between // first and second then update second else if (temp->data > second && temp->data != first) second = temp->data; temp = temp->next; } if (second == INT_MIN) cout << \"There is no second largest element\\n\"; else cout << \"The second largest element is \" << second;} // Driver program to test above functionint main(){ struct Node* start = NULL; /* The constructed linked list is: 12 -> 35 -> 1 -> 10 -> 34 -> 1 */ push(&start, 1); push(&start, 34); push(&start, 10); push(&start, 1); push(&start, 35); push(&start, 12); print2largest(start); return 0;}",
"e": 27966,
"s": 26031,
"text": null
},
{
"code": "// Java program to print second largest// value in a linked listclass GFG{ // A linked list nodestatic class Node{ int data; Node next;}; // Function to add a node at the// beginning of Linked Liststatic Node push( Node head_ref, int new_data){ // allocate node / Node new_node = new Node(); // put in the data / new_node.data = new_data; // link the old list off the new node / new_node.next = (head_ref); // move the head to point to the new node / (head_ref) = new_node; return head_ref;} // Function to count size of liststatic int listSize( Node node){ int count = 0; while (node != null) { count++; node = node.next; } return count;} // Function to print the second// largest elementstatic void print2largest( Node head){ int i, first, second; int list_size = listSize(head); // There should be atleast two elements / if (list_size < 2) { System.out.print(\"Invalid Input\"); return; } first = second = Integer.MIN_VALUE; Node temp = head; while (temp != null) { if (temp.data > first) { second = first; first = temp.data; } // If current node's data is in between // first and second then update second else if (temp.data > second && temp.data != first) second = temp.data; temp = temp.next; } if (second == Integer.MIN_VALUE) System.out.print( \"There is no second largest element\\n\"); else System.out.print (\"The second largest element is \" + second);} // Driver program to test above functionpublic static void main(String args[]){ Node start = null; // The constructed linked list is: //12 . 35 . 1 . 10 . 34 . 1 start=push(start, 1); start=push(start, 34); start=push(start, 10); start=push(start, 1); start=push(start, 35); start=push(start, 12); print2largest(start);}} // This code is contributed by Arnab Kundu",
"e": 29951,
"s": 27966,
"text": null
},
{
"code": "# Python3 program to print second largest# value in a linked list # A linked list nodeclass Node : def __init__(self): self.data = 0 self.next = None # Function to add a node at the# beginning of Linked Listdef push( head_ref, new_data) : # allocate node / new_node = Node() # put in the data / new_node.data = new_data # link the old list off the new node / new_node.next = (head_ref) # move the head to point to the new node / (head_ref) = new_node return head_ref # Function to count size of listdef listSize( node): count = 0 while (node != None): count = count + 1 node = node.next return count # Function to print the second# largest elementdef print2largest( head): i = 0 first = 0 second = 0 list_size = listSize(head) # There should be atleast two elements / if (list_size < 2) : print(\"Invalid Input\") return first = second = -323767 temp = head while (temp != None): if (temp.data > first) : second = first first = temp.data # If current node's data is in between # first and second then update second elif (temp.data > second and temp.data != first) : second = temp.data temp = temp.next if (second == -323767) : print( \"There is no second largest element\\n\") else: print (\"The second largest element is \" , second) # Driver code start = None # The constructed linked list is:# 12 . 35 . 1 . 10 . 34 . 1start = push(start, 1)start = push(start, 34)start = push(start, 10)start = push(start, 1)start = push(start, 35)start = push(start, 12) print2largest(start) # This code is contributed by Arnab Kundu",
"e": 31699,
"s": 29951,
"text": null
},
{
"code": "// C# program to print second largest// value in a linked listusing System; class GFG{ // A linked list nodepublic class Node{ public int data; public Node next;}; // Function to add a node at the// beginning of Linked Liststatic Node push( Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = (head_ref); // move the head to point to the new node (head_ref) = new_node; return head_ref;} // Function to count size of liststatic int listSize( Node node){ int count = 0; while (node != null) { count++; node = node.next; } return count;} // Function to print the second// largest elementstatic void print2largest(Node head){ int first, second; int list_size = listSize(head); // There should be atleast two elements if (list_size < 2) { Console.Write(\"Invalid Input\"); return; } first = second = int.MinValue; Node temp = head; while (temp != null) { if (temp.data > first) { second = first; first = temp.data; } // If current node's data is in between // first and second then update second else if (temp.data > second && temp.data != first) second = temp.data; temp = temp.next; } if (second == int.MinValue) Console.Write( \"There is no second\" + \" largest element\\n\"); else Console.Write(\"The second largest \" + \"element is \" + second);} // Driver Codepublic static void Main(String []args){ Node start = null; // The constructed linked list is: //12 . 35 . 1 . 10 . 34 . 1 start = push(start, 1); start = push(start, 34); start = push(start, 10); start = push(start, 1); start = push(start, 35); start = push(start, 12); print2largest(start);}} // This code is contributed by 29AjayKumar",
"e": 33731,
"s": 31699,
"text": null
},
{
"code": "<script> // JavaScript program to print second largest // value in a linked list // A linked list node class Node { constructor() { this.data = 0; this.next = null; } } // Function to add a node at the // beginning of Linked List function push(head_ref, new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; return head_ref; } // Function to count size of list function listSize(node) { var count = 0; while (node != null) { count++; node = node.next; } return count; } // Function to print the second // largest element function print2largest(head) { var first, second; var list_size = listSize(head); // There should be atleast two elements if (list_size < 2) { document.write(\"Invalid Input\"); return; } first = second = -2147483648; var temp = head; while (temp != null) { if (temp.data > first) { second = first; first = temp.data; } // If current node's data is in between // first and second then update second else if (temp.data > second && temp.data != first) second = temp.data; temp = temp.next; } if (second == -2147483648) document.write(\"There is no second\" + \" largest element<br>\"); else document.write(\"The second largest \" + \"element is \" + second); } // Driver Code var start = null; // The constructed linked list is: //12 . 35 . 1 . 10 . 34 . 1 start = push(start, 1); start = push(start, 34); start = push(start, 10); start = push(start, 1); start = push(start, 35); start = push(start, 12); print2largest(start); </script>",
"e": 35848,
"s": 33731,
"text": null
},
{
"code": null,
"e": 35881,
"s": 35848,
"text": "The second largest element is 34"
},
{
"code": null,
"e": 35894,
"s": 35883,
"text": "andrew1234"
},
{
"code": null,
"e": 35906,
"s": 35894,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35919,
"s": 35906,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35926,
"s": 35919,
"text": "rdtank"
},
{
"code": null,
"e": 35939,
"s": 35926,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 35951,
"s": 35939,
"text": "Linked List"
},
{
"code": null,
"e": 35963,
"s": 35951,
"text": "Linked List"
},
{
"code": null,
"e": 36061,
"s": 35963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36070,
"s": 36061,
"text": "Comments"
},
{
"code": null,
"e": 36083,
"s": 36070,
"text": "Old Comments"
},
{
"code": null,
"e": 36121,
"s": 36083,
"text": "Delete a node in a Doubly Linked List"
},
{
"code": null,
"e": 36192,
"s": 36121,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 36246,
"s": 36192,
"text": "Insert a node at a specific position in a linked list"
},
{
"code": null,
"e": 36287,
"s": 36246,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 36346,
"s": 36287,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 36396,
"s": 36346,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 36429,
"s": 36396,
"text": "Priority Queue using Linked List"
},
{
"code": null,
"e": 36469,
"s": 36429,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 36510,
"s": 36469,
"text": "Real-time application of Data Structures"
}
]
|
PostgreSQL - TRIGGERS | PostgreSQL Triggers are database callback functions, which are automatically performed/invoked when a specified database event occurs.
The following are important points about PostgreSQL triggers −
PostgreSQL trigger can be specified to fire
Before the operation is attempted on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted)
After the operation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has completed)
Instead of the operation (in the case of inserts, updates or deletes on a view)
PostgreSQL trigger can be specified to fire
Before the operation is attempted on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted)
Before the operation is attempted on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted)
After the operation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has completed)
After the operation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has completed)
Instead of the operation (in the case of inserts, updates or deletes on a view)
Instead of the operation (in the case of inserts, updates or deletes on a view)
A trigger that is marked FOR EACH ROW is called once for every row that the operation modifies. In contrast, a trigger that is marked FOR EACH STATEMENT only executes once for any given operation, regardless of how many rows it modifies.
A trigger that is marked FOR EACH ROW is called once for every row that the operation modifies. In contrast, a trigger that is marked FOR EACH STATEMENT only executes once for any given operation, regardless of how many rows it modifies.
Both, the WHEN clause and the trigger actions, may access elements of the row being inserted, deleted or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with.
Both, the WHEN clause and the trigger actions, may access elements of the row being inserted, deleted or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with.
If a WHEN clause is supplied, the PostgreSQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the PostgreSQL statements are executed for all rows.
If a WHEN clause is supplied, the PostgreSQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the PostgreSQL statements are executed for all rows.
If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name.
If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name.
The BEFORE, AFTER or INSTEAD OF keyword determines when the trigger actions will be executed relative to the insertion, modification or removal of the associated row.
The BEFORE, AFTER or INSTEAD OF keyword determines when the trigger actions will be executed relative to the insertion, modification or removal of the associated row.
Triggers are automatically dropped when the table that they are associated with is dropped.
Triggers are automatically dropped when the table that they are associated with is dropped.
The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename, not database.tablename.
The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename, not database.tablename.
A CONSTRAINT option when specified creates a constraint trigger. This is the same as a regular trigger except that the timing of the trigger firing can be adjusted using SET CONSTRAINTS. Constraint triggers are expected to raise an exception when the constraints they implement are violated.
A CONSTRAINT option when specified creates a constraint trigger. This is the same as a regular trigger except that the timing of the trigger firing can be adjusted using SET CONSTRAINTS. Constraint triggers are expected to raise an exception when the constraints they implement are violated.
The basic syntax of creating a trigger is as follows −
CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_name
ON table_name
[
-- Trigger logic goes here....
];
Here, event_name could be INSERT, DELETE, UPDATE, and TRUNCATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name.
The following is the syntax of creating a trigger on an UPDATE operation on one or more specified columns of a table as follows −
CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name
ON table_name
[
-- Trigger logic goes here....
];
Let us consider a case where we want to keep audit trial for every record being inserted in COMPANY table, which we will create newly as follows (Drop COMPANY table if you already have it).
testdb=# CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
To keep audit trial, we will create a new table called AUDIT where log messages will be inserted whenever there is an entry in COMPANY table for a new record −
testdb=# CREATE TABLE AUDIT(
EMP_ID INT NOT NULL,
ENTRY_DATE TEXT NOT NULL
);
Here, ID is the AUDIT record ID, and EMP_ID is the ID, which will come from COMPANY table, and DATE will keep timestamp when the record will be created in COMPANY table. So now, let us create a trigger on COMPANY table as follows −
testdb=# CREATE TRIGGER example_trigger AFTER INSERT ON COMPANY
FOR EACH ROW EXECUTE PROCEDURE auditlogfunc();
Where auditlogfunc() is a PostgreSQL procedure and has the following definition −
CREATE OR REPLACE FUNCTION auditlogfunc() RETURNS TRIGGER AS $example_table$
BEGIN
INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, current_timestamp);
RETURN NEW;
END;
$example_table$ LANGUAGE plpgsql;
Now, we will start the actual work. Let us start inserting record in COMPANY table which should result in creating an audit log record in AUDIT table. So let us create one record in COMPANY table as follows −
testdb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
This will create one record in COMPANY table, which is as follows −
id | name | age | address | salary
----+------+-----+--------------+--------
1 | Paul | 32 | California | 20000
Same time, one record will be created in AUDIT table. This record is the result of a trigger, which we have created on INSERT operation on COMPANY table. Similarly, you can create your triggers on UPDATE and DELETE operations based on your requirements.
emp_id | entry_date
--------+-------------------------------
1 | 2013-05-05 15:49:59.968+05:30
(1 row)
You can list down all the triggers in the current database from pg_trigger table as follows −
testdb=# SELECT * FROM pg_trigger;
The above given PostgreSQL statement will list down all triggers.
If you want to list the triggers on a particular table, then use AND clause with table name as follows −
testdb=# SELECT tgname FROM pg_trigger, pg_class WHERE tgrelid=pg_class.oid AND relname='company';
The above given PostgreSQL statement will also list down only one entry as follows −
tgname
-----------------
example_trigger
(1 row)
The following is the DROP command, which can be used to drop an existing trigger −
testdb=# DROP TRIGGER trigger_name;
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2960,
"s": 2825,
"text": "PostgreSQL Triggers are database callback functions, which are automatically performed/invoked when a specified database event occurs."
},
{
"code": null,
"e": 3023,
"s": 2960,
"text": "The following are important points about PostgreSQL triggers −"
},
{
"code": null,
"e": 3386,
"s": 3023,
"text": "PostgreSQL trigger can be specified to fire\n\nBefore the operation is attempted on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted)\nAfter the operation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has completed)\nInstead of the operation (in the case of inserts, updates or deletes on a view)\n\n"
},
{
"code": null,
"e": 3430,
"s": 3386,
"text": "PostgreSQL trigger can be specified to fire"
},
{
"code": null,
"e": 3552,
"s": 3430,
"text": "Before the operation is attempted on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted)"
},
{
"code": null,
"e": 3674,
"s": 3552,
"text": "Before the operation is attempted on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted)"
},
{
"code": null,
"e": 3788,
"s": 3674,
"text": "After the operation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has completed)"
},
{
"code": null,
"e": 3902,
"s": 3788,
"text": "After the operation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has completed)"
},
{
"code": null,
"e": 3983,
"s": 3902,
"text": "Instead of the operation (in the case of inserts, updates or deletes on a view)\n"
},
{
"code": null,
"e": 4063,
"s": 3983,
"text": "Instead of the operation (in the case of inserts, updates or deletes on a view)"
},
{
"code": null,
"e": 4301,
"s": 4063,
"text": "A trigger that is marked FOR EACH ROW is called once for every row that the operation modifies. In contrast, a trigger that is marked FOR EACH STATEMENT only executes once for any given operation, regardless of how many rows it modifies."
},
{
"code": null,
"e": 4539,
"s": 4301,
"text": "A trigger that is marked FOR EACH ROW is called once for every row that the operation modifies. In contrast, a trigger that is marked FOR EACH STATEMENT only executes once for any given operation, regardless of how many rows it modifies."
},
{
"code": null,
"e": 4812,
"s": 4539,
"text": "Both, the WHEN clause and the trigger actions, may access elements of the row being inserted, deleted or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with."
},
{
"code": null,
"e": 5085,
"s": 4812,
"text": "Both, the WHEN clause and the trigger actions, may access elements of the row being inserted, deleted or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with."
},
{
"code": null,
"e": 5297,
"s": 5085,
"text": "If a WHEN clause is supplied, the PostgreSQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the PostgreSQL statements are executed for all rows."
},
{
"code": null,
"e": 5509,
"s": 5297,
"text": "If a WHEN clause is supplied, the PostgreSQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the PostgreSQL statements are executed for all rows."
},
{
"code": null,
"e": 5629,
"s": 5509,
"text": "If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name."
},
{
"code": null,
"e": 5749,
"s": 5629,
"text": "If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name."
},
{
"code": null,
"e": 5916,
"s": 5749,
"text": "The BEFORE, AFTER or INSTEAD OF keyword determines when the trigger actions will be executed relative to the insertion, modification or removal of the associated row."
},
{
"code": null,
"e": 6083,
"s": 5916,
"text": "The BEFORE, AFTER or INSTEAD OF keyword determines when the trigger actions will be executed relative to the insertion, modification or removal of the associated row."
},
{
"code": null,
"e": 6175,
"s": 6083,
"text": "Triggers are automatically dropped when the table that they are associated with is dropped."
},
{
"code": null,
"e": 6267,
"s": 6175,
"text": "Triggers are automatically dropped when the table that they are associated with is dropped."
},
{
"code": null,
"e": 6435,
"s": 6267,
"text": "The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename, not database.tablename."
},
{
"code": null,
"e": 6603,
"s": 6435,
"text": "The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename, not database.tablename."
},
{
"code": null,
"e": 6895,
"s": 6603,
"text": "A CONSTRAINT option when specified creates a constraint trigger. This is the same as a regular trigger except that the timing of the trigger firing can be adjusted using SET CONSTRAINTS. Constraint triggers are expected to raise an exception when the constraints they implement are violated."
},
{
"code": null,
"e": 7187,
"s": 6895,
"text": "A CONSTRAINT option when specified creates a constraint trigger. This is the same as a regular trigger except that the timing of the trigger firing can be adjusted using SET CONSTRAINTS. Constraint triggers are expected to raise an exception when the constraints they implement are violated."
},
{
"code": null,
"e": 7242,
"s": 7187,
"text": "The basic syntax of creating a trigger is as follows −"
},
{
"code": null,
"e": 7360,
"s": 7242,
"text": "CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_name\nON table_name\n[\n -- Trigger logic goes here....\n];\n"
},
{
"code": null,
"e": 7535,
"s": 7360,
"text": "Here, event_name could be INSERT, DELETE, UPDATE, and TRUNCATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name."
},
{
"code": null,
"e": 7665,
"s": 7535,
"text": "The following is the syntax of creating a trigger on an UPDATE operation on one or more specified columns of a table as follows −"
},
{
"code": null,
"e": 7782,
"s": 7665,
"text": "CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name\nON table_name\n[\n -- Trigger logic goes here....\n];"
},
{
"code": null,
"e": 7972,
"s": 7782,
"text": "Let us consider a case where we want to keep audit trial for every record being inserted in COMPANY table, which we will create newly as follows (Drop COMPANY table if you already have it)."
},
{
"code": null,
"e": 8165,
"s": 7972,
"text": "testdb=# CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);"
},
{
"code": null,
"e": 8325,
"s": 8165,
"text": "To keep audit trial, we will create a new table called AUDIT where log messages will be inserted whenever there is an entry in COMPANY table for a new record −"
},
{
"code": null,
"e": 8409,
"s": 8325,
"text": "testdb=# CREATE TABLE AUDIT(\n EMP_ID INT NOT NULL,\n ENTRY_DATE TEXT NOT NULL\n);"
},
{
"code": null,
"e": 8641,
"s": 8409,
"text": "Here, ID is the AUDIT record ID, and EMP_ID is the ID, which will come from COMPANY table, and DATE will keep timestamp when the record will be created in COMPANY table. So now, let us create a trigger on COMPANY table as follows −"
},
{
"code": null,
"e": 8752,
"s": 8641,
"text": "testdb=# CREATE TRIGGER example_trigger AFTER INSERT ON COMPANY\nFOR EACH ROW EXECUTE PROCEDURE auditlogfunc();"
},
{
"code": null,
"e": 8834,
"s": 8752,
"text": "Where auditlogfunc() is a PostgreSQL procedure and has the following definition −"
},
{
"code": null,
"e": 9060,
"s": 8834,
"text": "CREATE OR REPLACE FUNCTION auditlogfunc() RETURNS TRIGGER AS $example_table$\n BEGIN\n INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, current_timestamp);\n RETURN NEW;\n END;\n$example_table$ LANGUAGE plpgsql;"
},
{
"code": null,
"e": 9269,
"s": 9060,
"text": "Now, we will start the actual work. Let us start inserting record in COMPANY table which should result in creating an audit log record in AUDIT table. So let us create one record in COMPANY table as follows −"
},
{
"code": null,
"e": 9376,
"s": 9269,
"text": "testdb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (1, 'Paul', 32, 'California', 20000.00 );"
},
{
"code": null,
"e": 9444,
"s": 9376,
"text": "This will create one record in COMPANY table, which is as follows −"
},
{
"code": null,
"e": 9568,
"s": 9444,
"text": " id | name | age | address | salary\n----+------+-----+--------------+--------\n 1 | Paul | 32 | California | 20000"
},
{
"code": null,
"e": 9822,
"s": 9568,
"text": "Same time, one record will be created in AUDIT table. This record is the result of a trigger, which we have created on INSERT operation on COMPANY table. Similarly, you can create your triggers on UPDATE and DELETE operations based on your requirements."
},
{
"code": null,
"e": 9941,
"s": 9822,
"text": " emp_id | entry_date\n--------+-------------------------------\n 1 | 2013-05-05 15:49:59.968+05:30\n(1 row)"
},
{
"code": null,
"e": 10035,
"s": 9941,
"text": "You can list down all the triggers in the current database from pg_trigger table as follows −"
},
{
"code": null,
"e": 10070,
"s": 10035,
"text": "testdb=# SELECT * FROM pg_trigger;"
},
{
"code": null,
"e": 10136,
"s": 10070,
"text": "The above given PostgreSQL statement will list down all triggers."
},
{
"code": null,
"e": 10241,
"s": 10136,
"text": "If you want to list the triggers on a particular table, then use AND clause with table name as follows −"
},
{
"code": null,
"e": 10340,
"s": 10241,
"text": "testdb=# SELECT tgname FROM pg_trigger, pg_class WHERE tgrelid=pg_class.oid AND relname='company';"
},
{
"code": null,
"e": 10425,
"s": 10340,
"text": "The above given PostgreSQL statement will also list down only one entry as follows −"
},
{
"code": null,
"e": 10480,
"s": 10425,
"text": " tgname\n-----------------\n example_trigger\n(1 row)"
},
{
"code": null,
"e": 10563,
"s": 10480,
"text": "The following is the DROP command, which can be used to drop an existing trigger −"
},
{
"code": null,
"e": 10599,
"s": 10563,
"text": "testdb=# DROP TRIGGER trigger_name;"
},
{
"code": null,
"e": 10634,
"s": 10599,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10646,
"s": 10634,
"text": " John Elder"
},
{
"code": null,
"e": 10681,
"s": 10646,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10697,
"s": 10681,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 10734,
"s": 10697,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 10756,
"s": 10734,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 10789,
"s": 10756,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10803,
"s": 10789,
"text": " Karthikeya T"
},
{
"code": null,
"e": 10834,
"s": 10803,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 10847,
"s": 10834,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 10878,
"s": 10847,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 10891,
"s": 10878,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 10898,
"s": 10891,
"text": " Print"
},
{
"code": null,
"e": 10909,
"s": 10898,
"text": " Add Notes"
}
]
|
Design and Analysis Hill Climbing Algorithm | The algorithms discussed in the previous chapters run systematically. To achieve the goal, one or more previously explored paths toward the solution need to be stored to find the optimal solution.
For many problems, the path to the goal is irrelevant. For example, in N-Queens problem, we don’t need to care about the final configuration of the queens as well as in which order the queens are added.
Hill Climbing is a technique to solve certain optimization problems. In this technique, we start with a sub-optimal solution and the solution is improved repeatedly until some condition is maximized.
The idea of starting with a sub-optimal solution is compared to starting from the base of the hill, improving the solution is compared to walking up the hill, and finally maximizing some condition is compared to reaching the top of the hill.
Hence, the hill climbing technique can be considered as the following phases −
Constructing a sub-optimal solution obeying the constraints of the problem
Improving the solution step-by-step
Improving the solution until no more improvement is possible
Hill Climbing technique is mainly used for solving computationally hard problems. It looks only at the current state and immediate future state. Hence, this technique is memory efficient as it does not maintain a search tree.
Algorithm: Hill Climbing
Evaluate the initial state.
Loop until a solution is found or there are no new operators left to be applied:
- Select and apply a new operator
- Evaluate the new state:
goal -→ quit
better than current state -→ new current state
In iterative improvement method, the optimal solution is achieved by making progress towards an optimal solution in every iteration. However, this technique may encounter local maxima. In this situation, there is no nearby state for a better solution.
This problem can be avoided by different methods. One of these methods is simulated annealing.
This is another method of solving the problem of local optima. This technique conducts a series of searches. Every time, it starts from a randomly generated initial state. Hence, optima or nearly optimal solution can be obtained comparing the solutions of searches performed.
If the heuristic is not convex, Hill Climbing may converge to local maxima, instead of global maxima.
If the target function creates a narrow ridge, then the climber can only ascend the ridge or descend the alley by zig-zagging. In this scenario, the climber needs to take very small steps requiring more time to reach the goal.
A plateau is encountered when the search space is flat or sufficiently flat that the value returned by the target function is indistinguishable from the value returned for nearby regions, due to the precision used by the machine to represent its value.
This technique does not suffer from space related issues, as it looks only at the current state. Previously explored paths are not stored.
For most of the problems in Random-restart Hill Climbing technique, an optimal solution can be achieved in polynomial time. However, for NP-Complete problems, computational time can be exponential based on the number of local maxima.
Hill Climbing technique can be used to solve many problems, where the current state allows for an accurate evaluation function, such as Network-Flow, Travelling Salesman problem, 8-Queens problem, Integrated Circuit design, etc.
Hill Climbing is used in inductive learning methods too. This technique is used in robotics for coordination among multiple robots in a team. There are many other problems where this technique is used.
This technique can be applied to solve the travelling salesman problem. First an initial solution is determined that visits all the cities exactly once. Hence, this initial solution is not optimal in most of the cases. Even this solution can be very poor. The Hill Climbing algorithm starts with such an initial solution and makes improvements to it in an iterative way. Eventually, a much shorter route is likely to be obtained.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2796,
"s": 2599,
"text": "The algorithms discussed in the previous chapters run systematically. To achieve the goal, one or more previously explored paths toward the solution need to be stored to find the optimal solution."
},
{
"code": null,
"e": 2999,
"s": 2796,
"text": "For many problems, the path to the goal is irrelevant. For example, in N-Queens problem, we don’t need to care about the final configuration of the queens as well as in which order the queens are added."
},
{
"code": null,
"e": 3199,
"s": 2999,
"text": "Hill Climbing is a technique to solve certain optimization problems. In this technique, we start with a sub-optimal solution and the solution is improved repeatedly until some condition is maximized."
},
{
"code": null,
"e": 3441,
"s": 3199,
"text": "The idea of starting with a sub-optimal solution is compared to starting from the base of the hill, improving the solution is compared to walking up the hill, and finally maximizing some condition is compared to reaching the top of the hill."
},
{
"code": null,
"e": 3520,
"s": 3441,
"text": "Hence, the hill climbing technique can be considered as the following phases −"
},
{
"code": null,
"e": 3595,
"s": 3520,
"text": "Constructing a sub-optimal solution obeying the constraints of the problem"
},
{
"code": null,
"e": 3631,
"s": 3595,
"text": "Improving the solution step-by-step"
},
{
"code": null,
"e": 3692,
"s": 3631,
"text": "Improving the solution until no more improvement is possible"
},
{
"code": null,
"e": 3918,
"s": 3692,
"text": "Hill Climbing technique is mainly used for solving computationally hard problems. It looks only at the current state and immediate future state. Hence, this technique is memory efficient as it does not maintain a search tree."
},
{
"code": null,
"e": 4198,
"s": 3918,
"text": "Algorithm: Hill Climbing \nEvaluate the initial state. \nLoop until a solution is found or there are no new operators left to be applied: \n - Select and apply a new operator \n - Evaluate the new state: \n goal -→ quit \n better than current state -→ new current state \n"
},
{
"code": null,
"e": 4450,
"s": 4198,
"text": "In iterative improvement method, the optimal solution is achieved by making progress towards an optimal solution in every iteration. However, this technique may encounter local maxima. In this situation, there is no nearby state for a better solution."
},
{
"code": null,
"e": 4545,
"s": 4450,
"text": "This problem can be avoided by different methods. One of these methods is simulated annealing."
},
{
"code": null,
"e": 4821,
"s": 4545,
"text": "This is another method of solving the problem of local optima. This technique conducts a series of searches. Every time, it starts from a randomly generated initial state. Hence, optima or nearly optimal solution can be obtained comparing the solutions of searches performed."
},
{
"code": null,
"e": 4923,
"s": 4821,
"text": "If the heuristic is not convex, Hill Climbing may converge to local maxima, instead of global maxima."
},
{
"code": null,
"e": 5150,
"s": 4923,
"text": "If the target function creates a narrow ridge, then the climber can only ascend the ridge or descend the alley by zig-zagging. In this scenario, the climber needs to take very small steps requiring more time to reach the goal."
},
{
"code": null,
"e": 5403,
"s": 5150,
"text": "A plateau is encountered when the search space is flat or sufficiently flat that the value returned by the target function is indistinguishable from the value returned for nearby regions, due to the precision used by the machine to represent its value."
},
{
"code": null,
"e": 5542,
"s": 5403,
"text": "This technique does not suffer from space related issues, as it looks only at the current state. Previously explored paths are not stored."
},
{
"code": null,
"e": 5776,
"s": 5542,
"text": "For most of the problems in Random-restart Hill Climbing technique, an optimal solution can be achieved in polynomial time. However, for NP-Complete problems, computational time can be exponential based on the number of local maxima."
},
{
"code": null,
"e": 6005,
"s": 5776,
"text": "Hill Climbing technique can be used to solve many problems, where the current state allows for an accurate evaluation function, such as Network-Flow, Travelling Salesman problem, 8-Queens problem, Integrated Circuit design, etc."
},
{
"code": null,
"e": 6207,
"s": 6005,
"text": "Hill Climbing is used in inductive learning methods too. This technique is used in robotics for coordination among multiple robots in a team. There are many other problems where this technique is used."
},
{
"code": null,
"e": 6637,
"s": 6207,
"text": "This technique can be applied to solve the travelling salesman problem. First an initial solution is determined that visits all the cities exactly once. Hence, this initial solution is not optimal in most of the cases. Even this solution can be very poor. The Hill Climbing algorithm starts with such an initial solution and makes improvements to it in an iterative way. Eventually, a much shorter route is likely to be obtained."
},
{
"code": null,
"e": 6672,
"s": 6637,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6691,
"s": 6672,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6724,
"s": 6691,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6743,
"s": 6724,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6776,
"s": 6743,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6795,
"s": 6776,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6830,
"s": 6795,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6843,
"s": 6830,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 6875,
"s": 6843,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6888,
"s": 6875,
"text": " Zach Miller"
},
{
"code": null,
"e": 6921,
"s": 6888,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6935,
"s": 6921,
"text": " Sasha Miller"
},
{
"code": null,
"e": 6942,
"s": 6935,
"text": " Print"
},
{
"code": null,
"e": 6953,
"s": 6942,
"text": " Add Notes"
}
]
|
Counting passing traffic. Using Yolo3, MotionEye, Python and... | by David Moore | Towards Data Science | If you have been reading my column here on Towards Data Science, you will know that I am on a mission. I wanted to count the number of cars passing my house using Computer Vision and Motion Detection. This article will push on with the work and describe how I tooled up for an initial end to end exercise. Doing Data Science from Scratch is involved but incredibly great fun.
As a catch-up, I previously built a camera and then explained the need to tune the motion detection device(s). My earlier posts described the camera build and early scripts to review the data and make sense of passing traffic. We had even made a very early chart to plot motion events. Let’s get on with the next instalment.
Python really needs no introduction to the readers here on Towards Data Science. I will only add that I use Anaconda on my Mac M1 Mini these days and I see no difficulties. Spyder3 seems a bit dated and slightly slower on the Mac M1 than I expected. We have discussed MotionEyeOs already in the column, so I propose to skip most of the MotionEyeOs discussion and defer my earlier articles. That leaves me with Yolo3 and friends, and indeed that is fitting. I needed help from some friends with Yolo3 since Computer Vision is not my field. I am just a Finance guy at the end of the day. At least that is what I have been told by tech gurus for years. Let’s meet the friends first then discuss how I used Yolo3 in my project. We can close with the results so far.
Computer Vision, Deep Learning, and Machine Learning are not new topics for me. Indeed I can pull my own when I need to. However, since I do not believe in re-inventing the wheel, I chose some friends for the journey. Computer Vision is not my field, and I prefer to use experts rather than re-invent the wheel.
Joseph Howse, and Joe Minichino provide Learning OpenCV 4 Computer Vision with Python3, and an excellent explanation of the field. It is a little too technical for beginners, I think. They do work through a proper application using Object Orientation and it sort of shamed me into thinking about my practice carefully.
www.packtpub.com
My other friend is PyImageSearch.com, and they provided a useful tutorial with code. Adrian Rosebrock has done some brilliant work to make the entire field more accessible to the community.
www.pyimagesearch.com
With good friends, plenty of support, encouragement, and code available, I had no difficulty creating a service to process the Motion detection events and count those passing vehicles.
“You only look once (YOLO) is a state-of-the-art, real-time object detection system. On a Pascal Titan X it processes images at 30 FPS and has a mAP of 57.9% on COCO test-dev.” — Joseph Chet Redmon. You can read all about Darknet and Yolo from Joseph Redmon. One strategy would have been just to use Darknet and forget Python altogether.
./darknet detect cfg/yolov3.cfg yolov3.weights data/dog.jpg
However, there won’t have been any fun in that for me. I chose to modify one of pyimagesearch.com’s scripts and use that as the base. Since the original code base belongs to Adrian Rosebrock, I will only illustrate how I orchestrated his code to perform services for me. You can do the tutorial and let Adrian explain it to you. He does a far better job than I would.
I created a new class called myYolo. The class has an instantiator and some methods. myYolo.ImgList() examines a given directory and recovers a list of images. myYolo.ProcessImg() takes the path to an image file and runs it through Yolo doing object detection.
class myYolo(object): def __init__(self, modelPath=dirt, labelsPath=dirt, imgPath=imgs): def ImgList(self): #load the model config, weights, find layers and load labels. return self.images #a list of photos with file system path def ProcessImg(self,img): #read the image. Pass forward through Yolo. #Process the results and format object class label and confidence. return (texts, mess) #objects detected and run times def run(self): imgist = self.ImgList() #print(imgist) results = [] for snap in imgist: print(f" processing {snap} ") img = {} img['image'] = snap res, mess = self.ProcessImg(snap) img['result'] = res img['timing'] = mess results.append(img) time.sleep(5) #I had to slow things down as the machine #was over heating > 80degrees on CPU self.persist(results) return 'Done' def persist(self,obj): with open(self.imgPath+"result.picke","wb") as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
So I created a new class, and whilst it is a little underdeveloped, it is ready for a bit of test. Operation is fairly simple
from myYolo import myYolomyY = myYolo(path to images to be processed)myY.run()
Once I create an instance of myYolo, passing in the directory containing the images, that loads the Yolo3 model configuration, weights, labels and sets up the model ready for the inference workload. The .run() method simply triggers the process and creates a Python list object ( list of dictionaries ) which is persisted to disk. Three lines of code allow me to process all 192 photos of passing cars for the day of my experiment. We are counting the passing traffic.
Counting the passing traffic then requires only a limited amount of steps. Those are:-
Position the Motion Detector Camera with a line of sight of the road;
Run for one day bearing in mind I am only interested in counting traffic during daylight hours.
Retrieve the images from the Camera the following day
Run the photos through the myYolo class and create the dataset
Retrieve the dataset and clean for use in Excel.
As I am using MotionEyeOs, most steps are just managed by the MotionEyeOS image and my Camera. I added some screenshots below so you can see for yourself.
Privacy is important and to protect the privacy of everyone I did two things:-
The Camera is positioned sufficiently far away from occupants, and sufficient detail cannot be seen.
I use heavy privacy and detection masking that renders 80% of the image as out of scope for motion detection. It is imperative to not interfere with a drivers attention or to take pictures without their consent.
To retrieve the 192 images for December 22nd, I can simply press ‘Zipped’, which triggers the download. Unzipping the file creates a folder named 2020–12–22, and that folder contains 192 images. Processing those 192 images with Yolo is then a matter of three lines of code.
from myYolo import myYolomyY = myYolo('/home/pi/downloads/2020-12-22')myY.run()
Once the script completes, ‘done’, the results are stored on disk, allowing us to do some Python cleaning and shaping. The disk file contains a serialized Python object, and in this case, it is a list of dictionaries, or you could say a JSON object. That might seem all very well and good, but Excel cannot read a Python object, and therefore we need to clean and shape that. Let’s head over to Jupyter Notebooks to make an Excel file.
Often times, I use Excel to explore my data upfront. In the old days, Excel couldn’t handle large datasets, but with Power Query and Power Pivot, it turns out Excel is pretty handy these days. You can find my Jupyter Notebook in the GitHub repository for this article. If you wish to examine the code, you will find that convenient as I added many comments to explain the steps.
github.com
In broad terms, I use Pickle to de-serialize and load the data from disk. There are a few steps to turn a List of Dictionaries into a reliable 2D matrix. Finally, I save my data as a CSV. Come on, my LOVE of Excel doesn’t go as far as creating an actual Excel file. The end result is a 2D Data frame.
<class 'pandas.core.frame.DataFrame'>RangeIndex: 192 entries, 0 to 191Data columns (total 8 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Image 192 non-null object 1 InferTime 192 non-null float64 2 Obj1 90 non-null object 3 ConfObj1 90 non-null float64 4 Obj2 6 non-null object 5 ConfObj2 6 non-null float64 6 Obj3 1 non-null object 7 ConfObj3 1 non-null float64dtypes: float64(4), object(4)memory usage: 12.1+ KB
Image: holds the full file path to the photo;
InferTime: contains the minutes and seconds required to traverse the Yolo network;
Obj1: Holds the label for the first detected object;
ConfObj1: Holds the confidence level the model returned for the chosen label
Obj2, Obj3, ConfObj2, ConfObj3, hold values for multiple object detections in the specific photo. Yolo could detect many objects, and therefore there is a label and confidence level for each one. My code is a bit dynamic in this regard.
You can examine the data file here. Now, after much work, I have a repeatable process that allows me to count passing cars. Undoubtedly the process needs a lot more testing and tuning. Let us take a quick look at the results and draw some conclusions.
I hope you see the value of good friends and the re-use of code. I created my own class, wrapping tutorial code, and then using an instance of that class to process 192 pictures performing object detection with Yolo3. It seems like a crazy ride and well not as challenging as I expected so far. You could say I merely created a batch process using a script designed to load a single image.
Inference with Yolo3 is computing intense. On average, my Raspberry Pi took 9.5 seconds per image. During those 192 10 secs, the board got super hot, and I mean over 80degrees hot. I seriously doubt that Raspberry Pi will continue to be my favourite for much longer.
Here is a small table of the overall result.
On December 22nd — Yolo was able to detect objects in 90 pictures out of the 192 available. A little under 50% which seems brilliant for a first run. There were 2 buses seen with the kids going to school and coming home. 3 people were detected out walking. 20 trucks went by. 1 photo contained 3 cars. 1 image included 2 vehicles. The ‘tvmonitor’ is a weird one. The Camera is deployed internally, and there is a reflection in the window from the room. The reflected image looks like a ‘tvmonitor’ to YOLO. Overall 62 cars passed by, 2 buses, and 20 trucks but only 3 persons confirming that the road is hazardous to walk on.
Since I have the Neural Compute Stick, I will refactor my code to exploit OpenVino and transfer the CPU workload to the Inference Engine. I will report back on this effort and my investigation into 100 pictures where Yolo didn’t find an object. Is that pointing to a need to train Yolo on an Irish data set? Exciting, please do come back! | [
{
"code": null,
"e": 548,
"s": 172,
"text": "If you have been reading my column here on Towards Data Science, you will know that I am on a mission. I wanted to count the number of cars passing my house using Computer Vision and Motion Detection. This article will push on with the work and describe how I tooled up for an initial end to end exercise. Doing Data Science from Scratch is involved but incredibly great fun."
},
{
"code": null,
"e": 873,
"s": 548,
"text": "As a catch-up, I previously built a camera and then explained the need to tune the motion detection device(s). My earlier posts described the camera build and early scripts to review the data and make sense of passing traffic. We had even made a very early chart to plot motion events. Let’s get on with the next instalment."
},
{
"code": null,
"e": 1635,
"s": 873,
"text": "Python really needs no introduction to the readers here on Towards Data Science. I will only add that I use Anaconda on my Mac M1 Mini these days and I see no difficulties. Spyder3 seems a bit dated and slightly slower on the Mac M1 than I expected. We have discussed MotionEyeOs already in the column, so I propose to skip most of the MotionEyeOs discussion and defer my earlier articles. That leaves me with Yolo3 and friends, and indeed that is fitting. I needed help from some friends with Yolo3 since Computer Vision is not my field. I am just a Finance guy at the end of the day. At least that is what I have been told by tech gurus for years. Let’s meet the friends first then discuss how I used Yolo3 in my project. We can close with the results so far."
},
{
"code": null,
"e": 1947,
"s": 1635,
"text": "Computer Vision, Deep Learning, and Machine Learning are not new topics for me. Indeed I can pull my own when I need to. However, since I do not believe in re-inventing the wheel, I chose some friends for the journey. Computer Vision is not my field, and I prefer to use experts rather than re-invent the wheel."
},
{
"code": null,
"e": 2266,
"s": 1947,
"text": "Joseph Howse, and Joe Minichino provide Learning OpenCV 4 Computer Vision with Python3, and an excellent explanation of the field. It is a little too technical for beginners, I think. They do work through a proper application using Object Orientation and it sort of shamed me into thinking about my practice carefully."
},
{
"code": null,
"e": 2283,
"s": 2266,
"text": "www.packtpub.com"
},
{
"code": null,
"e": 2473,
"s": 2283,
"text": "My other friend is PyImageSearch.com, and they provided a useful tutorial with code. Adrian Rosebrock has done some brilliant work to make the entire field more accessible to the community."
},
{
"code": null,
"e": 2495,
"s": 2473,
"text": "www.pyimagesearch.com"
},
{
"code": null,
"e": 2680,
"s": 2495,
"text": "With good friends, plenty of support, encouragement, and code available, I had no difficulty creating a service to process the Motion detection events and count those passing vehicles."
},
{
"code": null,
"e": 3018,
"s": 2680,
"text": "“You only look once (YOLO) is a state-of-the-art, real-time object detection system. On a Pascal Titan X it processes images at 30 FPS and has a mAP of 57.9% on COCO test-dev.” — Joseph Chet Redmon. You can read all about Darknet and Yolo from Joseph Redmon. One strategy would have been just to use Darknet and forget Python altogether."
},
{
"code": null,
"e": 3078,
"s": 3018,
"text": "./darknet detect cfg/yolov3.cfg yolov3.weights data/dog.jpg"
},
{
"code": null,
"e": 3446,
"s": 3078,
"text": "However, there won’t have been any fun in that for me. I chose to modify one of pyimagesearch.com’s scripts and use that as the base. Since the original code base belongs to Adrian Rosebrock, I will only illustrate how I orchestrated his code to perform services for me. You can do the tutorial and let Adrian explain it to you. He does a far better job than I would."
},
{
"code": null,
"e": 3707,
"s": 3446,
"text": "I created a new class called myYolo. The class has an instantiator and some methods. myYolo.ImgList() examines a given directory and recovers a list of images. myYolo.ProcessImg() takes the path to an image file and runs it through Yolo doing object detection."
},
{
"code": null,
"e": 4694,
"s": 3707,
"text": "class myYolo(object): def __init__(self, modelPath=dirt, labelsPath=dirt, imgPath=imgs): def ImgList(self): #load the model config, weights, find layers and load labels. return self.images #a list of photos with file system path def ProcessImg(self,img): #read the image. Pass forward through Yolo. #Process the results and format object class label and confidence. return (texts, mess) #objects detected and run times def run(self): imgist = self.ImgList() #print(imgist) results = [] for snap in imgist: print(f\" processing {snap} \") img = {} img['image'] = snap res, mess = self.ProcessImg(snap) img['result'] = res img['timing'] = mess results.append(img) time.sleep(5) #I had to slow things down as the machine #was over heating > 80degrees on CPU self.persist(results) return 'Done' def persist(self,obj): with open(self.imgPath+\"result.picke\",\"wb\") as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)"
},
{
"code": null,
"e": 4820,
"s": 4694,
"text": "So I created a new class, and whilst it is a little underdeveloped, it is ready for a bit of test. Operation is fairly simple"
},
{
"code": null,
"e": 4899,
"s": 4820,
"text": "from myYolo import myYolomyY = myYolo(path to images to be processed)myY.run()"
},
{
"code": null,
"e": 5368,
"s": 4899,
"text": "Once I create an instance of myYolo, passing in the directory containing the images, that loads the Yolo3 model configuration, weights, labels and sets up the model ready for the inference workload. The .run() method simply triggers the process and creates a Python list object ( list of dictionaries ) which is persisted to disk. Three lines of code allow me to process all 192 photos of passing cars for the day of my experiment. We are counting the passing traffic."
},
{
"code": null,
"e": 5455,
"s": 5368,
"text": "Counting the passing traffic then requires only a limited amount of steps. Those are:-"
},
{
"code": null,
"e": 5525,
"s": 5455,
"text": "Position the Motion Detector Camera with a line of sight of the road;"
},
{
"code": null,
"e": 5621,
"s": 5525,
"text": "Run for one day bearing in mind I am only interested in counting traffic during daylight hours."
},
{
"code": null,
"e": 5675,
"s": 5621,
"text": "Retrieve the images from the Camera the following day"
},
{
"code": null,
"e": 5738,
"s": 5675,
"text": "Run the photos through the myYolo class and create the dataset"
},
{
"code": null,
"e": 5787,
"s": 5738,
"text": "Retrieve the dataset and clean for use in Excel."
},
{
"code": null,
"e": 5942,
"s": 5787,
"text": "As I am using MotionEyeOs, most steps are just managed by the MotionEyeOS image and my Camera. I added some screenshots below so you can see for yourself."
},
{
"code": null,
"e": 6021,
"s": 5942,
"text": "Privacy is important and to protect the privacy of everyone I did two things:-"
},
{
"code": null,
"e": 6122,
"s": 6021,
"text": "The Camera is positioned sufficiently far away from occupants, and sufficient detail cannot be seen."
},
{
"code": null,
"e": 6334,
"s": 6122,
"text": "I use heavy privacy and detection masking that renders 80% of the image as out of scope for motion detection. It is imperative to not interfere with a drivers attention or to take pictures without their consent."
},
{
"code": null,
"e": 6608,
"s": 6334,
"text": "To retrieve the 192 images for December 22nd, I can simply press ‘Zipped’, which triggers the download. Unzipping the file creates a folder named 2020–12–22, and that folder contains 192 images. Processing those 192 images with Yolo is then a matter of three lines of code."
},
{
"code": null,
"e": 6688,
"s": 6608,
"text": "from myYolo import myYolomyY = myYolo('/home/pi/downloads/2020-12-22')myY.run()"
},
{
"code": null,
"e": 7124,
"s": 6688,
"text": "Once the script completes, ‘done’, the results are stored on disk, allowing us to do some Python cleaning and shaping. The disk file contains a serialized Python object, and in this case, it is a list of dictionaries, or you could say a JSON object. That might seem all very well and good, but Excel cannot read a Python object, and therefore we need to clean and shape that. Let’s head over to Jupyter Notebooks to make an Excel file."
},
{
"code": null,
"e": 7503,
"s": 7124,
"text": "Often times, I use Excel to explore my data upfront. In the old days, Excel couldn’t handle large datasets, but with Power Query and Power Pivot, it turns out Excel is pretty handy these days. You can find my Jupyter Notebook in the GitHub repository for this article. If you wish to examine the code, you will find that convenient as I added many comments to explain the steps."
},
{
"code": null,
"e": 7514,
"s": 7503,
"text": "github.com"
},
{
"code": null,
"e": 7815,
"s": 7514,
"text": "In broad terms, I use Pickle to de-serialize and load the data from disk. There are a few steps to turn a List of Dictionaries into a reliable 2D matrix. Finally, I save my data as a CSV. Come on, my LOVE of Excel doesn’t go as far as creating an actual Excel file. The end result is a 2D Data frame."
},
{
"code": null,
"e": 8358,
"s": 7815,
"text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 192 entries, 0 to 191Data columns (total 8 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Image 192 non-null object 1 InferTime 192 non-null float64 2 Obj1 90 non-null object 3 ConfObj1 90 non-null float64 4 Obj2 6 non-null object 5 ConfObj2 6 non-null float64 6 Obj3 1 non-null object 7 ConfObj3 1 non-null float64dtypes: float64(4), object(4)memory usage: 12.1+ KB"
},
{
"code": null,
"e": 8404,
"s": 8358,
"text": "Image: holds the full file path to the photo;"
},
{
"code": null,
"e": 8487,
"s": 8404,
"text": "InferTime: contains the minutes and seconds required to traverse the Yolo network;"
},
{
"code": null,
"e": 8540,
"s": 8487,
"text": "Obj1: Holds the label for the first detected object;"
},
{
"code": null,
"e": 8617,
"s": 8540,
"text": "ConfObj1: Holds the confidence level the model returned for the chosen label"
},
{
"code": null,
"e": 8854,
"s": 8617,
"text": "Obj2, Obj3, ConfObj2, ConfObj3, hold values for multiple object detections in the specific photo. Yolo could detect many objects, and therefore there is a label and confidence level for each one. My code is a bit dynamic in this regard."
},
{
"code": null,
"e": 9106,
"s": 8854,
"text": "You can examine the data file here. Now, after much work, I have a repeatable process that allows me to count passing cars. Undoubtedly the process needs a lot more testing and tuning. Let us take a quick look at the results and draw some conclusions."
},
{
"code": null,
"e": 9496,
"s": 9106,
"text": "I hope you see the value of good friends and the re-use of code. I created my own class, wrapping tutorial code, and then using an instance of that class to process 192 pictures performing object detection with Yolo3. It seems like a crazy ride and well not as challenging as I expected so far. You could say I merely created a batch process using a script designed to load a single image."
},
{
"code": null,
"e": 9763,
"s": 9496,
"text": "Inference with Yolo3 is computing intense. On average, my Raspberry Pi took 9.5 seconds per image. During those 192 10 secs, the board got super hot, and I mean over 80degrees hot. I seriously doubt that Raspberry Pi will continue to be my favourite for much longer."
},
{
"code": null,
"e": 9808,
"s": 9763,
"text": "Here is a small table of the overall result."
},
{
"code": null,
"e": 10434,
"s": 9808,
"text": "On December 22nd — Yolo was able to detect objects in 90 pictures out of the 192 available. A little under 50% which seems brilliant for a first run. There were 2 buses seen with the kids going to school and coming home. 3 people were detected out walking. 20 trucks went by. 1 photo contained 3 cars. 1 image included 2 vehicles. The ‘tvmonitor’ is a weird one. The Camera is deployed internally, and there is a reflection in the window from the room. The reflected image looks like a ‘tvmonitor’ to YOLO. Overall 62 cars passed by, 2 buses, and 20 trucks but only 3 persons confirming that the road is hazardous to walk on."
}
]
|
C program to find sum and difference using pointers in function | Suppose we have two numbers a and b. We shall have to define a function that can calculate (a + b) and (a - b) both. But using a function in C, we can return at most one value. To find more than one output, we can use output parameters into function arguments using pointers. Here in this problem we shall update a with a+b and b with a-b. When we call the function we shall have to pass the address of these two variables.
So, if the input is like a = 5, b = 8, then the output will be a + b = 13 and a - b = -3
To solve this, we will follow these steps −
define a function solve(), this will take addresses of a and b
define a function solve(), this will take addresses of a and b
temp := sum of the values of variable whose addresses are given
temp := sum of the values of variable whose addresses are given
b := difference of the values of variable whose addresses are given
b := difference of the values of variable whose addresses are given
a = temp
a = temp
Let us see the following implementation to get better understanding −
#include <stdio.h>
int solve(int *a, int *b){
int temp = *a + *b;
*b = *a - *b;
*a = temp;
}
int main(){
int a = 5, b = 8;
solve(&a, &b);
printf("a + b = %d and a - b = %d", a, b);
}
a = 5, b = 8
a + b = 13 and a - b = -3 | [
{
"code": null,
"e": 1486,
"s": 1062,
"text": "Suppose we have two numbers a and b. We shall have to define a function that can calculate (a + b) and (a - b) both. But using a function in C, we can return at most one value. To find more than one output, we can use output parameters into function arguments using pointers. Here in this problem we shall update a with a+b and b with a-b. When we call the function we shall have to pass the address of these two variables."
},
{
"code": null,
"e": 1575,
"s": 1486,
"text": "So, if the input is like a = 5, b = 8, then the output will be a + b = 13 and a - b = -3"
},
{
"code": null,
"e": 1619,
"s": 1575,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1682,
"s": 1619,
"text": "define a function solve(), this will take addresses of a and b"
},
{
"code": null,
"e": 1745,
"s": 1682,
"text": "define a function solve(), this will take addresses of a and b"
},
{
"code": null,
"e": 1809,
"s": 1745,
"text": "temp := sum of the values of variable whose addresses are given"
},
{
"code": null,
"e": 1873,
"s": 1809,
"text": "temp := sum of the values of variable whose addresses are given"
},
{
"code": null,
"e": 1941,
"s": 1873,
"text": "b := difference of the values of variable whose addresses are given"
},
{
"code": null,
"e": 2009,
"s": 1941,
"text": "b := difference of the values of variable whose addresses are given"
},
{
"code": null,
"e": 2018,
"s": 2009,
"text": "a = temp"
},
{
"code": null,
"e": 2027,
"s": 2018,
"text": "a = temp"
},
{
"code": null,
"e": 2097,
"s": 2027,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2305,
"s": 2097,
"text": "#include <stdio.h>\nint solve(int *a, int *b){\n int temp = *a + *b;\n *b = *a - *b;\n *a = temp;\n}\nint main(){\n int a = 5, b = 8;\n solve(&a, &b);\n printf(\"a + b = %d and a - b = %d\", a, b);\n}\n"
},
{
"code": null,
"e": 2318,
"s": 2305,
"text": "a = 5, b = 8"
},
{
"code": null,
"e": 2344,
"s": 2318,
"text": "a + b = 13 and a - b = -3"
}
]
|
Create an alert message box with Bootstrap | Use the .alert class in Bootstrap to create an alert message box −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<div class = "alert alert-warning">
<p>Warning!</p>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "Use the .alert class in Bootstrap to create an alert message box −"
},
{
"code": null,
"e": 1139,
"s": 1129,
"text": "Live Demo"
},
{
"code": null,
"e": 1693,
"s": 1139,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <div class = \"alert alert-warning\">\n <p>Warning!</p>\n </div>\n </div>\n </body>\n</html>"
}
]
|
Palindromic Array | Practice | GeeksforGeeks | Given a Integer array A[] of n elements. Your task is to complete the function PalinArray. Which will return 1 if all the elements of the Array are palindrome otherwise it will return 0.
Example:
Input:
2
5
111 222 333 444 555
3
121 131 20
Output:
1
0
Explanation:
For First test case.
n=5;
A[0] = 111 //which is a palindrome number.
A[1] = 222 //which is a palindrome number.
A[2] = 333 //which is a palindrome number.
A[3] = 444 //which is a palindrome number.
A[4] = 555 //which is a palindrome number.
As all numbers are palindrome so This will return 1.
Constraints:
1 <=T<= 50
1 <=n<= 20
1 <=A[]<= 10000
0
jpragati052 days ago
CAN ANYONE TELL ME WHAT'S WRONG IN THIS CODE????
class GfG
{
static boolean is_palindrome(int i){
int n=i;
int num=0;
while(n!=0){
int rem=n%10;
num=num*10+rem;
n=n/10;
}
if(num==i)
return true;
return false;
}
public static int palinArray(int[] a, int n)
{
//add code here.
for(int i=0;i<n;i++)
if(is_palindrome(a[i]))
return 1;
return 0;
}
}
IT IS NOT PASSING THE T.C.
0
harshscode5 days ago
int PalinArray(int a[], int n) { int sum=0; for(int j=0;j<n;j++) { int p=a[j]; sum=0; while(p) { int rev=p%10; sum=sum*10+rev; p=p/10; } if(sum==a[j]) continue; else return 0; } return 1; }
0
alexrace182 weeks ago
int digito,reversa=0,copia; for(int i=0;i<n;i++){ copia=a[i]; reversa=0; while(a[i]!=0){ digito=a[i]%10; reversa=reversa*10+digito; a[i]=a[i]/10; } if(copia!=reversa){ return 0; } } return 1;
0
rsbly730095
This comment was deleted.
0
kartikkeyankant2 weeks ago
C++ easy solution using array
class Solution {
public:
bool pal(int x){
int arr[10000];
int i=0;
while(x){
arr[i++]=x%10;
x=x/10;
}
for(int j=0;j<=i/2;j++){
if(arr[j]!=arr[i-1-j])return false;
}
return true;
}
int PalinArray(int a[], int n)
{
for(int i=0;i<n;i++){
if(!pal(a[i]))return 0;
}
return 1;
}
};
0
pratyushparida83 weeks ago
def PalinArray(arr ,n): for i in arr: if str(i)!=str(i)[::-1]: return 0 else : return 1
0
avijit1126be203 weeks ago
//java solution
class GfG{public static int palinArray(int[] a, int n) { //add code here. boolean flag = true; for(int i=0;i<a.length;i++) { String str1=Integer.toString(a[i]); String str2 = ""; while(a[i]!=0) { int rem = a[i]%10; str2 += rem; a[i] /= 10; } if(!str1.equals(str2)) { flag = false; break; } } if(flag==false) { return 0; } return 1; }}
+1
aloksinghbais023 weeks ago
C++ solution having time complexity as O(N*max(log(arr[i]))) and space complexity as O(max(log(arr[i]))) is as follows :-
Execution Time :- 0.0 / 1.1 sec
string helper(int n){ string ans{}; while(n){ int ld = n % 10; n /= 10; ans += to_string(ld); } return (ans); } bool check(string str){ int i = 0, j = str.length()-1; while(i < j){ if(str[i] != str[j]) return (false); i++,j--; } return (true); } int PalinArray(int a[], int n){ for(int i = 0; i < n; i++){ string str = helper(a[i]); if(!check(str)) return (0); } return (1); }
+1
hashshamkhan200361 month ago
int PalinArray(int a[], int n) { // code here for(int i=0;i<n;i++){ int temp=a[i]; int ans=0; while(temp>0){ int r = temp%10; temp=temp/10; ans=(ans*10)+r; } if(ans!=a[i]){ return 0; } } return 1; }
0
pravinshelke844
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 413,
"s": 226,
"text": "Given a Integer array A[] of n elements. Your task is to complete the function PalinArray. Which will return 1 if all the elements of the Array are palindrome otherwise it will return 0."
},
{
"code": null,
"e": 800,
"s": 415,
"text": "Example:\nInput:\n2\n5\n111 222 333 444 555\n3\n121 131 20\n\nOutput:\n1\n0\n\nExplanation:\nFor First test case.\nn=5;\nA[0] = 111 //which is a palindrome number.\nA[1] = 222 //which is a palindrome number.\nA[2] = 333 //which is a palindrome number.\nA[3] = 444 //which is a palindrome number.\nA[4] = 555 //which is a palindrome number.\nAs all numbers are palindrome so This will return 1.\n\n"
},
{
"code": null,
"e": 851,
"s": 800,
"text": "Constraints:\n1 <=T<= 50\n1 <=n<= 20\n1 <=A[]<= 10000"
},
{
"code": null,
"e": 853,
"s": 851,
"text": "0"
},
{
"code": null,
"e": 874,
"s": 853,
"text": "jpragati052 days ago"
},
{
"code": null,
"e": 1438,
"s": 874,
"text": "CAN ANYONE TELL ME WHAT'S WRONG IN THIS CODE????\nclass GfG\n{\n static boolean is_palindrome(int i){\n int n=i;\n int num=0;\n while(n!=0){\n int rem=n%10;\n num=num*10+rem;\n n=n/10;\n }\n if(num==i)\n return true;\n return false;\n }\n\tpublic static int palinArray(int[] a, int n)\n {\n //add code here.\n for(int i=0;i<n;i++)\n if(is_palindrome(a[i]))\n return 1;\n return 0;\n }\n}"
},
{
"code": null,
"e": 1465,
"s": 1438,
"text": "IT IS NOT PASSING THE T.C."
},
{
"code": null,
"e": 1467,
"s": 1465,
"text": "0"
},
{
"code": null,
"e": 1488,
"s": 1467,
"text": "harshscode5 days ago"
},
{
"code": null,
"e": 1775,
"s": 1488,
"text": "int PalinArray(int a[], int n) { int sum=0; for(int j=0;j<n;j++) { int p=a[j]; sum=0; while(p) { int rev=p%10; sum=sum*10+rev; p=p/10; } if(sum==a[j]) continue; else return 0; } return 1; }"
},
{
"code": null,
"e": 1777,
"s": 1775,
"text": "0"
},
{
"code": null,
"e": 1799,
"s": 1777,
"text": "alexrace182 weeks ago"
},
{
"code": null,
"e": 2311,
"s": 1799,
"text": " int digito,reversa=0,copia; for(int i=0;i<n;i++){ copia=a[i]; reversa=0; while(a[i]!=0){ digito=a[i]%10; reversa=reversa*10+digito; a[i]=a[i]/10; } if(copia!=reversa){ return 0; } } return 1;"
},
{
"code": null,
"e": 2313,
"s": 2311,
"text": "0"
},
{
"code": null,
"e": 2325,
"s": 2313,
"text": "rsbly730095"
},
{
"code": null,
"e": 2351,
"s": 2325,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2353,
"s": 2351,
"text": "0"
},
{
"code": null,
"e": 2380,
"s": 2353,
"text": "kartikkeyankant2 weeks ago"
},
{
"code": null,
"e": 2410,
"s": 2380,
"text": "C++ easy solution using array"
},
{
"code": null,
"e": 2812,
"s": 2410,
"text": "class Solution {\npublic:\n bool pal(int x){\n int arr[10000];\n int i=0;\n while(x){\n arr[i++]=x%10;\n x=x/10;\n }\n for(int j=0;j<=i/2;j++){\n if(arr[j]!=arr[i-1-j])return false;\n }\n return true;\n \n }\n int PalinArray(int a[], int n)\n {\n for(int i=0;i<n;i++){\n if(!pal(a[i]))return 0;\n }\n return 1;\n }\n};\n"
},
{
"code": null,
"e": 2814,
"s": 2812,
"text": "0"
},
{
"code": null,
"e": 2841,
"s": 2814,
"text": "pratyushparida83 weeks ago"
},
{
"code": null,
"e": 2956,
"s": 2841,
"text": "def PalinArray(arr ,n): for i in arr: if str(i)!=str(i)[::-1]: return 0 else : return 1 "
},
{
"code": null,
"e": 2958,
"s": 2956,
"text": "0"
},
{
"code": null,
"e": 2984,
"s": 2958,
"text": "avijit1126be203 weeks ago"
},
{
"code": null,
"e": 3000,
"s": 2984,
"text": "//java solution"
},
{
"code": null,
"e": 3801,
"s": 3000,
"text": "class GfG{public static int palinArray(int[] a, int n) { //add code here. boolean flag = true; for(int i=0;i<a.length;i++) { String str1=Integer.toString(a[i]); String str2 = \"\"; while(a[i]!=0) { int rem = a[i]%10; str2 += rem; a[i] /= 10; } if(!str1.equals(str2)) { flag = false; break; } } if(flag==false) { return 0; } return 1; }}"
},
{
"code": null,
"e": 3804,
"s": 3801,
"text": "+1"
},
{
"code": null,
"e": 3831,
"s": 3804,
"text": "aloksinghbais023 weeks ago"
},
{
"code": null,
"e": 3954,
"s": 3831,
"text": "C++ solution having time complexity as O(N*max(log(arr[i]))) and space complexity as O(max(log(arr[i]))) is as follows :- "
},
{
"code": null,
"e": 3988,
"s": 3956,
"text": "Execution Time :- 0.0 / 1.1 sec"
},
{
"code": null,
"e": 4504,
"s": 3990,
"text": "string helper(int n){ string ans{}; while(n){ int ld = n % 10; n /= 10; ans += to_string(ld); } return (ans); } bool check(string str){ int i = 0, j = str.length()-1; while(i < j){ if(str[i] != str[j]) return (false); i++,j--; } return (true); } int PalinArray(int a[], int n){ for(int i = 0; i < n; i++){ string str = helper(a[i]); if(!check(str)) return (0); } return (1); }"
},
{
"code": null,
"e": 4507,
"s": 4504,
"text": "+1"
},
{
"code": null,
"e": 4536,
"s": 4507,
"text": "hashshamkhan200361 month ago"
},
{
"code": null,
"e": 4862,
"s": 4536,
"text": " int PalinArray(int a[], int n) { // code here for(int i=0;i<n;i++){ int temp=a[i]; int ans=0; while(temp>0){ int r = temp%10; temp=temp/10; ans=(ans*10)+r; } if(ans!=a[i]){ return 0; } } return 1; }"
},
{
"code": null,
"e": 4864,
"s": 4862,
"text": "0"
},
{
"code": null,
"e": 4880,
"s": 4864,
"text": "pravinshelke844"
},
{
"code": null,
"e": 4906,
"s": 4880,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5052,
"s": 4906,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5088,
"s": 5052,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5098,
"s": 5088,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5108,
"s": 5098,
"text": "\nContest\n"
},
{
"code": null,
"e": 5171,
"s": 5108,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5319,
"s": 5171,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5527,
"s": 5319,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5633,
"s": 5527,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Time2Vec for Time Series features encoding | by Marco Cerliani | Towards Data Science | Time is golden information in every Machine Learning problem which engages Time Series. As Data Scientists, we must do our best to extract time patterns and make our data speak themself. During preprocessing, common procedures are for example standardization (stationarity check, autocorrelation removal...), creating and encoding categorical time features (day, week, month, season...), manual feature engineering (Fourier transformations...). Not always our efforts are repaid because, during modelization, our selected model can fail to treat time itself properly as a feature.
In this post, I try to reproduce the approach proposed in the paper ‘Time2Vec: Learning a Vector Representation of Time’, which final scope is to develop a general-purpose model-agnostic representation for time that can be potentially used in any architecture (I adapt this solution developing a Neural Network in Keras). The authors don’t want to propose a new model for time series analysis, but instead, their goal is to provide a representation of time, in form of vector embedding, in order to automatize the feature engineering process and model time in a better way.
To give evidence and a concrete utility of the whole solution, we need an adequate dataset. In my case, I need data in time series format without any redundant information in form of extra features. This scenario is typical in autoregressive problems, where we have only one time series and we use it as a feature to forecast the future. In real life this is a common task, so is not difficult to find a dataset. I found a nice one on Kaggle. It stores a great number of historical levels of water in Venice. Forecasting these values is a serious task; daily tourists can access a well detailed and accurate report of the level of the sea in various parts of the city.
I love Venice and my aim is not to compete with them. We also have not enough information to provide truly evident performances (extra regressors such as temperature, moon phases, weather conditions and so on, provide an adequate boost). Here we have to squeeze the only historical data at our disposal to provide the forecasts of the next hour levels of water.
Mathematically speaking, implement Time2Vec is quite easy:
Where k is the time2vec dimension, tau is a raw time series, F is a periodic activation function, omega and phi are a set of learnable parameters. In my experiment, I set F to be a sin function in order to able a selected algorithm to capture periodic behaviors in data. At the same time, the linear term represents the progression of time and can be used for capturing non-periodic patterns in the input that depend on time.
The simplicity makes this vector representation for time easily consumable by different architectures. In my case, I try to transfer this concept in a Neural Network structure modifying a simple Keras dense layer.
class T2V(Layer): def __init__(self, output_dim=None, **kwargs): self.output_dim = output_dim super(T2V, self).__init__(**kwargs) def build(self, input_shape): self.W = self.add_weight(name='W', shape=(input_shape[-1], self.output_dim), initializer='uniform', trainable=True) self.P = self.add_weight(name='P', shape=(input_shape[1], self.output_dim), initializer='uniform', trainable=True) self.w = self.add_weight(name='w', shape=(input_shape[1], 1), initializer='uniform', trainable=True) self.p = self.add_weight(name='p', shape=(input_shape[1], 1), initializer='uniform', trainable=True) super(T2V, self).build(input_shape) def call(self, x): original = self.w * x + self.p sin_trans = K.sin(K.dot(x, self.W) + self.P) return K.concatenate([sin_trans, original], -1)
The output dimension of this custom layer is the hidden dimension specified by the user (1 ≤ i ≤ k), i.e. the learned sinusoids from the network, plus a linear representation of the input (i = 0). With this instrument in our hands, we just have to stack it with other layers and try its power in our case study.
Is Time2Vec a good representation of time? In order to answer this question, I compare the performances achieved in our forecasting task, building two different Sequential Neural Network models. The first one has as input our custom Time2Vec layer, stacked on a simple LSTM layer. The second one is composed of only the simple LSTM layer used in the previous structure.
def T2V_NN(param, dim): inp = Input(shape=(dim,1)) x = T2V(param['t2v_dim'], dim)(inp) x = LSTM(param['unit'], activation=param['act'])(x) x = Dense(1)(x) m = Model(inp, x) m.compile(loss='mse', optimizer=Adam(lr=param['lr'])) return mdef NN(param, dim): inp = Input(shape=(dim,1)) x = LSTM(param['unit'], activation=param['act'])(inp) x = Dense(1)(x) m = Model(inp, x) m.compile(loss='mse', optimizer=Adam(lr=param['lr'])) return m
We carry out the fitting procedures operating hyperparameters optimization. This is done using keras-hypetune. This framework provides hyperparameter optimization of the neural network structures in a very intuitive way. We operate a standard grid search of some parameter combinations. This is done for all two training procedures involved.
I use the first 70% of the data as train set and the remaining 30% as test set. The train is also split into validation, inside the fitting process, in order to operate hyperparameter tuning. The best and optimized T2V + LSTM achieves around 1.67 MAE on the test, while the simple and optimized LSTM achieves around 2.02.
Both the networks seem to be able to identify the pattern in the data really well. The usage of T2V encoding can grant a little boost in performance.
In this post, I presented an approach that automatically learns the features of the time. In particular, I reproduced Time2Vec, a vector representation for time, adapting it to a Neural Network architecture. In the end, I was able to show the effectiveness, in terms of performances, of this representation on a real task. I want to remark, as the authors of the paper suggest, that T2V is not a new model for time series analysis, but it is a simple vector representation that can be easily imported into many existing and future architectures and improve their performances.
CHECK MY GITHUB REPO
Keep in touch: Linkedin
REFERENCES
Time2Vec: Learning a Vector Representation of Time. Seyed Mehran Kazemi, Rishab Goel, Sepehr Eghbali, Janahan Ramanan, Jaspreet Sahota, Sanjay Thakur, Stella Wu, Cathal Smyth, Pascal Poupart, Marcus Brubaker | [
{
"code": null,
"e": 628,
"s": 47,
"text": "Time is golden information in every Machine Learning problem which engages Time Series. As Data Scientists, we must do our best to extract time patterns and make our data speak themself. During preprocessing, common procedures are for example standardization (stationarity check, autocorrelation removal...), creating and encoding categorical time features (day, week, month, season...), manual feature engineering (Fourier transformations...). Not always our efforts are repaid because, during modelization, our selected model can fail to treat time itself properly as a feature."
},
{
"code": null,
"e": 1202,
"s": 628,
"text": "In this post, I try to reproduce the approach proposed in the paper ‘Time2Vec: Learning a Vector Representation of Time’, which final scope is to develop a general-purpose model-agnostic representation for time that can be potentially used in any architecture (I adapt this solution developing a Neural Network in Keras). The authors don’t want to propose a new model for time series analysis, but instead, their goal is to provide a representation of time, in form of vector embedding, in order to automatize the feature engineering process and model time in a better way."
},
{
"code": null,
"e": 1871,
"s": 1202,
"text": "To give evidence and a concrete utility of the whole solution, we need an adequate dataset. In my case, I need data in time series format without any redundant information in form of extra features. This scenario is typical in autoregressive problems, where we have only one time series and we use it as a feature to forecast the future. In real life this is a common task, so is not difficult to find a dataset. I found a nice one on Kaggle. It stores a great number of historical levels of water in Venice. Forecasting these values is a serious task; daily tourists can access a well detailed and accurate report of the level of the sea in various parts of the city."
},
{
"code": null,
"e": 2233,
"s": 1871,
"text": "I love Venice and my aim is not to compete with them. We also have not enough information to provide truly evident performances (extra regressors such as temperature, moon phases, weather conditions and so on, provide an adequate boost). Here we have to squeeze the only historical data at our disposal to provide the forecasts of the next hour levels of water."
},
{
"code": null,
"e": 2292,
"s": 2233,
"text": "Mathematically speaking, implement Time2Vec is quite easy:"
},
{
"code": null,
"e": 2718,
"s": 2292,
"text": "Where k is the time2vec dimension, tau is a raw time series, F is a periodic activation function, omega and phi are a set of learnable parameters. In my experiment, I set F to be a sin function in order to able a selected algorithm to capture periodic behaviors in data. At the same time, the linear term represents the progression of time and can be used for capturing non-periodic patterns in the input that depend on time."
},
{
"code": null,
"e": 2932,
"s": 2718,
"text": "The simplicity makes this vector representation for time easily consumable by different architectures. In my case, I try to transfer this concept in a Neural Network structure modifying a simple Keras dense layer."
},
{
"code": null,
"e": 4071,
"s": 2932,
"text": "class T2V(Layer): def __init__(self, output_dim=None, **kwargs): self.output_dim = output_dim super(T2V, self).__init__(**kwargs) def build(self, input_shape): self.W = self.add_weight(name='W', shape=(input_shape[-1], self.output_dim), initializer='uniform', trainable=True) self.P = self.add_weight(name='P', shape=(input_shape[1], self.output_dim), initializer='uniform', trainable=True) self.w = self.add_weight(name='w', shape=(input_shape[1], 1), initializer='uniform', trainable=True) self.p = self.add_weight(name='p', shape=(input_shape[1], 1), initializer='uniform', trainable=True) super(T2V, self).build(input_shape) def call(self, x): original = self.w * x + self.p sin_trans = K.sin(K.dot(x, self.W) + self.P) return K.concatenate([sin_trans, original], -1)"
},
{
"code": null,
"e": 4383,
"s": 4071,
"text": "The output dimension of this custom layer is the hidden dimension specified by the user (1 ≤ i ≤ k), i.e. the learned sinusoids from the network, plus a linear representation of the input (i = 0). With this instrument in our hands, we just have to stack it with other layers and try its power in our case study."
},
{
"code": null,
"e": 4753,
"s": 4383,
"text": "Is Time2Vec a good representation of time? In order to answer this question, I compare the performances achieved in our forecasting task, building two different Sequential Neural Network models. The first one has as input our custom Time2Vec layer, stacked on a simple LSTM layer. The second one is composed of only the simple LSTM layer used in the previous structure."
},
{
"code": null,
"e": 5249,
"s": 4753,
"text": "def T2V_NN(param, dim): inp = Input(shape=(dim,1)) x = T2V(param['t2v_dim'], dim)(inp) x = LSTM(param['unit'], activation=param['act'])(x) x = Dense(1)(x) m = Model(inp, x) m.compile(loss='mse', optimizer=Adam(lr=param['lr'])) return mdef NN(param, dim): inp = Input(shape=(dim,1)) x = LSTM(param['unit'], activation=param['act'])(inp) x = Dense(1)(x) m = Model(inp, x) m.compile(loss='mse', optimizer=Adam(lr=param['lr'])) return m"
},
{
"code": null,
"e": 5591,
"s": 5249,
"text": "We carry out the fitting procedures operating hyperparameters optimization. This is done using keras-hypetune. This framework provides hyperparameter optimization of the neural network structures in a very intuitive way. We operate a standard grid search of some parameter combinations. This is done for all two training procedures involved."
},
{
"code": null,
"e": 5913,
"s": 5591,
"text": "I use the first 70% of the data as train set and the remaining 30% as test set. The train is also split into validation, inside the fitting process, in order to operate hyperparameter tuning. The best and optimized T2V + LSTM achieves around 1.67 MAE on the test, while the simple and optimized LSTM achieves around 2.02."
},
{
"code": null,
"e": 6063,
"s": 5913,
"text": "Both the networks seem to be able to identify the pattern in the data really well. The usage of T2V encoding can grant a little boost in performance."
},
{
"code": null,
"e": 6640,
"s": 6063,
"text": "In this post, I presented an approach that automatically learns the features of the time. In particular, I reproduced Time2Vec, a vector representation for time, adapting it to a Neural Network architecture. In the end, I was able to show the effectiveness, in terms of performances, of this representation on a real task. I want to remark, as the authors of the paper suggest, that T2V is not a new model for time series analysis, but it is a simple vector representation that can be easily imported into many existing and future architectures and improve their performances."
},
{
"code": null,
"e": 6661,
"s": 6640,
"text": "CHECK MY GITHUB REPO"
},
{
"code": null,
"e": 6685,
"s": 6661,
"text": "Keep in touch: Linkedin"
},
{
"code": null,
"e": 6696,
"s": 6685,
"text": "REFERENCES"
}
]
|
How to overwrite a line in a .txt file using Java? | The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String.
The java.util class (constructor) accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. To read various datatypes from the source using the nextXXX() methods provided.
The StringBuffer class is a mutable alternative to String, after instantiating this class you can add data to it using the append() method.
To overwrite a particular line of a file −
Read the contents of a file to String −
Instantiate the File class.
Instantiate the File class.
Instantiate the Scanner class passing the file as parameter to its constructor.
Instantiate the Scanner class passing the file as parameter to its constructor.
Create an empty StringBuffer object.
Create an empty StringBuffer object.
add the contents of the file line by line to the StringBuffer object using the append() method.
add the contents of the file line by line to the StringBuffer object using the append() method.
Convert the StringBuffer to String using the toString() method.
Convert the StringBuffer to String using the toString() method.
Close the Scanner object.
Close the Scanner object.
Invoke the replaceAll() method on the obtained string passing the line to be replaced (old line) and replacement line (new line) as parameters.
Rewrite the file contents −
Instantiate the FileWriter class.
Instantiate the FileWriter class.
Add the results of the replaceAll() method the FileWriter object using the append() method.
Add the results of the replaceAll() method the FileWriter object using the append() method.
Push the added data to the file using the flush() method.
Push the added data to the file using the flush() method.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class OverwriteLine {
public static void main(String args[]) throws IOException {
//Instantiating the File class
String filePath = "D://input.txt";
//Instantiating the Scanner class to read the file
Scanner sc = new Scanner(new File(filePath));
//instantiating the StringBuffer class
StringBuffer buffer = new StringBuffer();
//Reading lines of the file and appending them to StringBuffer
while (sc.hasNextLine()) {
buffer.append(sc.nextLine()+System.lineSeparator());
}
String fileContents = buffer.toString();
System.out.println("Contents of the file: "+fileContents);
//closing the Scanner object
sc.close();
String oldLine = "No preconditions and no impediments. Simply Easy Learning!";
String newLine = "Enjoy the free content";
//Replacing the old line with new line
fileContents = fileContents.replaceAll(oldLine, newLine);
//instantiating the FileWriter class
FileWriter writer = new FileWriter(filePath);
System.out.println("");
System.out.println("new data: "+fileContents);
writer.append(fileContents);
writer.flush();
}
}
Contents of the file: Tutorials Point originated from the idea that there exists a
class of readers who respond better to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to
encourage our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
No preconditions and no impediments. Simply Easy Learning!
new data: Tutorials Point originated from the idea that there exists a class of readers
who respond better to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to
encourage our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
Enjoy the free content | [
{
"code": null,
"e": 1236,
"s": 1062,
"text": "The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String."
},
{
"code": null,
"e": 1518,
"s": 1236,
"text": "The java.util class (constructor) accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. To read various datatypes from the source using the nextXXX() methods provided."
},
{
"code": null,
"e": 1658,
"s": 1518,
"text": "The StringBuffer class is a mutable alternative to String, after instantiating this class you can add data to it using the append() method."
},
{
"code": null,
"e": 1701,
"s": 1658,
"text": "To overwrite a particular line of a file −"
},
{
"code": null,
"e": 1741,
"s": 1701,
"text": "Read the contents of a file to String −"
},
{
"code": null,
"e": 1769,
"s": 1741,
"text": "Instantiate the File class."
},
{
"code": null,
"e": 1797,
"s": 1769,
"text": "Instantiate the File class."
},
{
"code": null,
"e": 1877,
"s": 1797,
"text": "Instantiate the Scanner class passing the file as parameter to its constructor."
},
{
"code": null,
"e": 1957,
"s": 1877,
"text": "Instantiate the Scanner class passing the file as parameter to its constructor."
},
{
"code": null,
"e": 1994,
"s": 1957,
"text": "Create an empty StringBuffer object."
},
{
"code": null,
"e": 2031,
"s": 1994,
"text": "Create an empty StringBuffer object."
},
{
"code": null,
"e": 2127,
"s": 2031,
"text": "add the contents of the file line by line to the StringBuffer object using the append() method."
},
{
"code": null,
"e": 2223,
"s": 2127,
"text": "add the contents of the file line by line to the StringBuffer object using the append() method."
},
{
"code": null,
"e": 2287,
"s": 2223,
"text": "Convert the StringBuffer to String using the toString() method."
},
{
"code": null,
"e": 2351,
"s": 2287,
"text": "Convert the StringBuffer to String using the toString() method."
},
{
"code": null,
"e": 2377,
"s": 2351,
"text": "Close the Scanner object."
},
{
"code": null,
"e": 2403,
"s": 2377,
"text": "Close the Scanner object."
},
{
"code": null,
"e": 2547,
"s": 2403,
"text": "Invoke the replaceAll() method on the obtained string passing the line to be replaced (old line) and replacement line (new line) as parameters."
},
{
"code": null,
"e": 2575,
"s": 2547,
"text": "Rewrite the file contents −"
},
{
"code": null,
"e": 2609,
"s": 2575,
"text": "Instantiate the FileWriter class."
},
{
"code": null,
"e": 2643,
"s": 2609,
"text": "Instantiate the FileWriter class."
},
{
"code": null,
"e": 2735,
"s": 2643,
"text": "Add the results of the replaceAll() method the FileWriter object using the append() method."
},
{
"code": null,
"e": 2827,
"s": 2735,
"text": "Add the results of the replaceAll() method the FileWriter object using the append() method."
},
{
"code": null,
"e": 2885,
"s": 2827,
"text": "Push the added data to the file using the flush() method."
},
{
"code": null,
"e": 2943,
"s": 2885,
"text": "Push the added data to the file using the flush() method."
},
{
"code": null,
"e": 4277,
"s": 2943,
"text": "import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Scanner;\npublic class OverwriteLine {\n public static void main(String args[]) throws IOException {\n //Instantiating the File class\n String filePath = \"D://input.txt\";\n //Instantiating the Scanner class to read the file\n Scanner sc = new Scanner(new File(filePath));\n //instantiating the StringBuffer class\n StringBuffer buffer = new StringBuffer();\n //Reading lines of the file and appending them to StringBuffer\n while (sc.hasNextLine()) {\n buffer.append(sc.nextLine()+System.lineSeparator());\n }\n String fileContents = buffer.toString();\n System.out.println(\"Contents of the file: \"+fileContents);\n //closing the Scanner object\n sc.close();\n String oldLine = \"No preconditions and no impediments. Simply Easy Learning!\";\n String newLine = \"Enjoy the free content\";\n //Replacing the old line with new line\n fileContents = fileContents.replaceAll(oldLine, newLine);\n //instantiating the FileWriter class\n FileWriter writer = new FileWriter(filePath);\n System.out.println(\"\");\n System.out.println(\"new data: \"+fileContents);\n writer.append(fileContents);\n writer.flush();\n }\n}"
},
{
"code": null,
"e": 5150,
"s": 4277,
"text": "Contents of the file: Tutorials Point originated from the idea that there exists a \nclass of readers who respond better to online content and prefer to learn new skills.\nOur content and resources are freely available and we prefer to keep it that way to \nencourage our readers acquire as many skills as they would like to.\nWe don’t force our readers to sign up with us or submit their details either.\nNo preconditions and no impediments. Simply Easy Learning!\n\nnew data: Tutorials Point originated from the idea that there exists a class of readers \nwho respond better to online content and prefer to learn new skills.\nOur content and resources are freely available and we prefer to keep it that way to \nencourage our readers acquire as many skills as they would like to.\nWe don’t force our readers to sign up with us or submit their details either.\nEnjoy the free content"
}
]
|
Tryit Editor v3.6 - Show Python | mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
#If this page is executed with no error, the database "mydatabase" exists in your system | [
{
"code": null,
"e": 57,
"s": 25,
"text": "mydb = mysql.connector.connect("
},
{
"code": null,
"e": 77,
"s": 57,
"text": " host=\"localhost\","
},
{
"code": null,
"e": 98,
"s": 77,
"text": " user=\"myusername\","
},
{
"code": null,
"e": 123,
"s": 98,
"text": " password=\"mypassword\","
},
{
"code": null,
"e": 147,
"s": 123,
"text": " database=\"mydatabase\""
},
{
"code": null,
"e": 149,
"s": 147,
"text": ")"
},
{
"code": null,
"e": 151,
"s": 149,
"text": ""
}
]
|
How to convert a string in lower case in Golang? - GeeksforGeeks | 26 Aug, 2019
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go string, you are allowed to convert a string in the lowercase using ToLower() function. This function returns a copy of the given string in which all the Unicode letters mapped into lower case. This function is defined under strings package, so you have to import strings package in your program to access this function.
Syntax:
func ToLower(str string) string
Here, str represents a string which you want to convert to lowercase.
Example:
// Go program to illustrate how to convert// the given string to lowercasepackage main import ( "fmt" "strings") // Main methodfunc main() { // Creating and initializing string // Using shorthand declaration str1 := "WelcomE, GeeksforGeeks**" str2 := "$$This is the, tuTorial oF Golang##" str3 := "HELLO! GOLANG" str4 := "lowercase conversion" // Displaying strings fmt.Println("Strings (before):") fmt.Println("String 1: ", str1) fmt.Println("String 2:", str2) fmt.Println("String 3:", str3) fmt.Println("String 4:", str4) // Converting all the string into lowercase // Using ToLower() function res1 := strings.ToLower(str1) res2 := strings.ToLower(str2) res3 := strings.ToLower(str3) res4 := strings.ToLower(str4) // Displaying the results fmt.Println("\nStrings (after):") fmt.Println("Result 1: ", res1) fmt.Println("Result 2:", res2) fmt.Println("Result 3:", res3) fmt.Println("Result 4:", res4)}
Output:
Strings (before):
String 1: WelcomE, GeeksforGeeks**
String 2: $$This is the, tuTorial oF Golang##
String 3: HELLO! GOLANG
String 4: lowercase conversion
Strings (after):
Result 1: welcome, geeksforgeeks**
Result 2: $$this is the, tutorial of golang##
Result 3: hello! golang
Result 4: lowercase conversion
Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Arrays in Go
Golang Maps
Slices in Golang
How to compare times in Golang?
How to Trim a String in Golang?
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang | [
{
"code": null,
"e": 24418,
"s": 24390,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 24966,
"s": 24418,
"text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go string, you are allowed to convert a string in the lowercase using ToLower() function. This function returns a copy of the given string in which all the Unicode letters mapped into lower case. This function is defined under strings package, so you have to import strings package in your program to access this function."
},
{
"code": null,
"e": 24974,
"s": 24966,
"text": "Syntax:"
},
{
"code": null,
"e": 25006,
"s": 24974,
"text": "func ToLower(str string) string"
},
{
"code": null,
"e": 25076,
"s": 25006,
"text": "Here, str represents a string which you want to convert to lowercase."
},
{
"code": null,
"e": 25085,
"s": 25076,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to convert// the given string to lowercasepackage main import ( \"fmt\" \"strings\") // Main methodfunc main() { // Creating and initializing string // Using shorthand declaration str1 := \"WelcomE, GeeksforGeeks**\" str2 := \"$$This is the, tuTorial oF Golang##\" str3 := \"HELLO! GOLANG\" str4 := \"lowercase conversion\" // Displaying strings fmt.Println(\"Strings (before):\") fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2:\", str2) fmt.Println(\"String 3:\", str3) fmt.Println(\"String 4:\", str4) // Converting all the string into lowercase // Using ToLower() function res1 := strings.ToLower(str1) res2 := strings.ToLower(str2) res3 := strings.ToLower(str3) res4 := strings.ToLower(str4) // Displaying the results fmt.Println(\"\\nStrings (after):\") fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2:\", res2) fmt.Println(\"Result 3:\", res3) fmt.Println(\"Result 4:\", res4)}",
"e": 26075,
"s": 25085,
"text": null
},
{
"code": null,
"e": 26083,
"s": 26075,
"text": "Output:"
},
{
"code": null,
"e": 26394,
"s": 26083,
"text": "Strings (before):\nString 1: WelcomE, GeeksforGeeks**\nString 2: $$This is the, tuTorial oF Golang##\nString 3: HELLO! GOLANG\nString 4: lowercase conversion\n\nStrings (after):\nResult 1: welcome, geeksforgeeks**\nResult 2: $$this is the, tutorial of golang##\nResult 3: hello! golang\nResult 4: lowercase conversion\n"
},
{
"code": null,
"e": 26401,
"s": 26394,
"text": "Golang"
},
{
"code": null,
"e": 26415,
"s": 26401,
"text": "Golang-String"
},
{
"code": null,
"e": 26427,
"s": 26415,
"text": "Go Language"
},
{
"code": null,
"e": 26525,
"s": 26427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26576,
"s": 26525,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 26623,
"s": 26576,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 26656,
"s": 26623,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 26669,
"s": 26656,
"text": "Arrays in Go"
},
{
"code": null,
"e": 26681,
"s": 26669,
"text": "Golang Maps"
},
{
"code": null,
"e": 26698,
"s": 26681,
"text": "Slices in Golang"
},
{
"code": null,
"e": 26730,
"s": 26698,
"text": "How to compare times in Golang?"
},
{
"code": null,
"e": 26762,
"s": 26730,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 26784,
"s": 26762,
"text": "Inheritance in GoLang"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.