title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C++ Program to Implement Sparse Array
A sparse matrix is a matrix in which majority of the elements are 0. An example for this is given as follows. The matrix given below contains 5 zeroes. Since the number of zeroes is more than half the elements of the matrix, it is a sparse matrix. 0 0 9 5 0 8 7 0 0 Begin Declare a 2D array a[10][10] to the integer datatype. Initialize some values of array. Declare i, j, count to the integer datatype. Initialize count = 0. Declare row, col to the integer datatype. Initialize row = 3, col = 3. for (i = 0; i < row; ++i) { for (j = 0; j < col; ++j) if (a[i][j] == 0) count++. Print “The matrix is:” . for (i = 0; i < row; ++i) for (j = 0; j < col; ++j) Print the values of array. Print “The number of zeros in the matrix are”. if (count > ((row * col)/ 2)) then Print "This is a sparse matrix". else Print "This is not a sparse matrix". End. Live Demo #include<iostream> using namespace std; int main () { int a[10][10] = { {0, 0, 9} , {5, 0, 8} , {7, 0, 0} }; int i, j, count = 0; int row = 3, col = 3; for (i = 0; i < row; ++i) { for (j = 0; j < col; ++j) { if (a[i][j] == 0) count++; } } cout<<"The matrix is:"<<endl; for (i = 0; i < row; ++i) { for (j = 0; j < col; ++j) { cout<<a[i][j]<<" "; } cout<<endl; } cout<<"The number of zeros in the matrix are "<< count <<endl; if (count > ((row * col)/ 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl; return 0; } The matrix is: 0 0 9 5 0 8 7 0 0 The number of zeros in the matrix are 5 This is a sparse matrix
[ { "code": null, "e": 1172, "s": 1062, "text": "A sparse matrix is a matrix in which majority of the elements are 0. An example for this is given as follows." }, { "code": null, "e": 1310, "s": 1172, "text": "The matrix given below contains 5 zeroes. Since the number of zeroes is more than half the elements of the matrix, it is a sparse matrix." }, { "code": null, "e": 1328, "s": 1310, "text": "0 0 9\n5 0 8\n7 0 0" }, { "code": null, "e": 2020, "s": 1328, "text": "Begin\n Declare a 2D array a[10][10] to the integer datatype.\n Initialize some values of array.\n Declare i, j, count to the integer datatype.\n Initialize count = 0.\n Declare row, col to the integer datatype.\n Initialize row = 3, col = 3.\n for (i = 0; i < row; ++i) {\n for (j = 0; j < col; ++j)\n if (a[i][j] == 0)\n count++.\n Print “The matrix is:” .\n for (i = 0; i < row; ++i)\n for (j = 0; j < col; ++j)\n Print the values of array.\n Print “The number of zeros in the matrix are”.\n if (count > ((row * col)/ 2)) then\n Print \"This is a sparse matrix\".\n else\n Print \"This is not a sparse matrix\".\nEnd." }, { "code": null, "e": 2031, "s": 2020, "text": " Live Demo" }, { "code": null, "e": 2692, "s": 2031, "text": "#include<iostream>\nusing namespace std;\nint main () {\n int a[10][10] = { {0, 0, 9} , {5, 0, 8} , {7, 0, 0} };\n int i, j, count = 0;\n int row = 3, col = 3;\n for (i = 0; i < row; ++i) {\n for (j = 0; j < col; ++j) {\n if (a[i][j] == 0)\n count++;\n }\n }\n cout<<\"The matrix is:\"<<endl;\n for (i = 0; i < row; ++i) {\n for (j = 0; j < col; ++j) {\n cout<<a[i][j]<<\" \";\n }\n cout<<endl;\n }\n cout<<\"The number of zeros in the matrix are \"<< count <<endl;\n if (count > ((row * col)/ 2))\n cout<<\"This is a sparse matrix\"<<endl;\n else\n cout<<\"This is not a sparse matrix\"<<endl;\n return 0;\n}" }, { "code": null, "e": 2789, "s": 2692, "text": "The matrix is:\n0 0 9\n5 0 8\n7 0 0\nThe number of zeros in the matrix are 5\nThis is a sparse matrix" } ]
Count of smaller elements on right side of each element in an Array using Merge sort - GeeksforGeeks
02 Jun, 2021 Given an array arr[] of N integers, the task is to count the number of smaller elements on the right side for each of the element in the array Examples: Input: arr[] = {6, 3, 7, 2} Output: 2, 1, 1, 0 Explanation: Smaller elements after 6 = 2 [3, 2] Smaller elements after 3 = 1 [2] Smaller elements after 7 = 1 [2] Smaller elements after 2 = 0 Input: arr[] = {6, 19, 111, 13} Output: 0, 1, 1, 0 Explanation: Smaller elements after 6 = 0 Smaller elements after 19 = 1 [13] Smaller elements after 111 = 1 [13] Smaller elements after 13 = 0 Approach: Use the idea of the merge sort at the time of merging two arrays. When higher index element is less than the lower index element, it represents that the higher index element is smaller than all the elements after that lower index because the left part is already sorted. Hence add up to all the elements after the lower index element for the required count. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ program to find the count of// smaller elements on right side of// each element in an Array// using Merge sort#include <bits/stdc++.h>using namespace std; const int N = 100001;int ans[N]; // Utility function that merge the array// and count smaller element on right sidevoid merge(pair<int, int> a[], int start, int mid, int end){ pair<int, int> f[mid - start + 1], s[end - mid]; int n = mid - start + 1; int m = end - mid; for(int i = start; i <= mid; i++) f[i - start] = a[i]; for(int i = mid + 1; i <= end; i++) s[i - mid - 1] = a[i]; int i = 0, j = 0, k = start; int cnt = 0; // Loop to store the count of smaller // Elements on right side when both // Array have some elements while(i < n && j < m) { if (f[i].second <= s[j].second) { ans[f[i].first] += cnt; a[k++] = f[i++]; } else { cnt++; a[k++] = s[j++]; } } // Loop to store the count of smaller // elements in right side when only // left array have some element while(i < n) { ans[f[i].first] += cnt; a[k++] = f[i++]; } // Loop to store the count of smaller // elements in right side when only // right array have some element while(j < m) { a[k++] = s[j++]; }} // Function to invoke merge sort.void mergesort(pair<int, int> item[], int low, int high){ if (low >= high) return; int mid = (low + high) / 2; mergesort(item, low, mid); mergesort(item, mid + 1, high); merge(item, low, mid, high);} // Utility function that prints// out an array on a linevoid print(int arr[], int n){ for(int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver code.int main(){ int arr[] = { 10, 9, 5, 2, 7, 6, 11, 0, 2 }; int n = sizeof(arr) / sizeof(int); pair<int, int> a[n]; memset(ans, 0, sizeof(ans)); for(int i = 0; i < n; i++) { a[i].second = arr[i]; a[i].first = i; } mergesort(a, 0, n - 1); print(ans, n); return 0;} // This code is contributed by rishabhtyagi2306 // Java program to find the count of smaller elements// on right side of each element in an Array// using Merge sort import java.util.*; public class GFG { // Class for storing the index // and Value pairs class Item { int val; int index; public Item(int val, int index) { this.val = val; this.index = index; } } // Function to count the number of // smaller elements on right side public ArrayList<Integer> countSmall(int[] A) { int len = A.length; Item[] items = new Item[len]; for (int i = 0; i < len; i++) { items[i] = new Item(A[i], i); } int[] count = new int[len]; mergeSort(items, 0, len - 1, count); ArrayList<Integer> res = new ArrayList<>(); for (int i : count) { res.add(i); } return res; } // Function for Merge Sort private void mergeSort(Item[] items, int low, int high, int[] count) { if (low >= high) { return; } int mid = low + (high - low) / 2; mergeSort(items, low, mid, count); mergeSort(items, mid + 1, high, count); merge(items, low, mid, mid + 1, high, count); } // Utility function that merge the array // and count smaller element on right side private void merge(Item[] items, int low, int lowEnd, int high, int highEnd, int[] count) { int m = highEnd - low + 1; Item[] sorted = new Item[m]; int rightCounter = 0; int lowPtr = low, highPtr = high; int index = 0; // Loop to store the count of smaller // Elements on right side when both // Array have some elements while (lowPtr <= lowEnd && highPtr <= highEnd) { if (items[lowPtr].val > items[highPtr].val) { rightCounter++; sorted[index++] = items[highPtr++]; } else { count[items[lowPtr].index] += rightCounter; sorted[index++] = items[lowPtr++]; } } // Loop to store the count of smaller // elements in right side when only // left array have some element while (lowPtr <= lowEnd) { count[items[lowPtr].index] += rightCounter; sorted[index++] = items[lowPtr++]; } // Loop to store the count of smaller // elements in right side when only // right array have some element while (highPtr <= highEnd) { sorted[index++] = items[highPtr++]; } System.arraycopy(sorted, 0, items, low, m); } // Utility function that prints // out an array on a line void printArray(ArrayList<Integer> countList) { for (Integer i : countList) System.out.print(i + " "); System.out.println(""); } // Driver Code public static void main(String[] args) { GFG cntSmall = new GFG(); int arr[] = { 10, 9, 5, 2, 7, 6, 11, 0, 2 }; int n = arr.length; ArrayList<Integer> countList = cntSmall.countSmall(arr); cntSmall.printArray(countList); }} # Python3 program to find the count of# smaller elements on right side of# each element in an Array# using Merge sortN = 100001ans = [0] * N # Utility function that merge the array# and count smaller element on right sidedef merge(a, start, mid, end): f = [0] * (mid - start + 1) s = [0] * (end - mid) n = mid - start + 1 m = end - mid for i in range(start, mid + 1): f[i - start] = a[i] for i in range ( mid + 1, end + 1): s[i - mid - 1] = a[i] i = 0 j = 0 k = start cnt = 0 # Loop to store the count of smaller # Elements on right side when both # Array have some elements while (i < n and j < m): if (f[i][1] <= s[j][1]): ans[f[i][0]] += cnt a[k] = f[i] k += 1 i += 1 else: cnt += 1 a[k] = s[j] k += 1 j += 1 # Loop to store the count of smaller # elements in right side when only # left array have some element while (i < n): ans[f[i][0]] += cnt a[k] = f[i]; k += 1 i += 1 # Loop to store the count of smaller # elements in right side when only # right array have some element while (j < m): a[k] = s[j] k += 1 j += 1 # Function to invoke merge sort.def mergesort(item, low, high): if (low >= high): return mid = (low + high) // 2 mergesort(item, low, mid) mergesort(item, mid + 1, high) merge(item, low, mid, high) # Utility function that prints# out an array on a linedef print_(arr, n): for i in range(n): print(arr[i], end = " ") # Driver code.if __name__ == "__main__": arr = [ 10, 9, 5, 2, 7, 6, 11, 0, 2 ] n = len(arr) a = [[0 for x in range(2)] for y in range(n)] for i in range(n): a[i][1] = arr[i] a[i][0] = i mergesort(a, 0, n - 1) print_(ans, n) # This code is contributed by chitranayal // C# program to find the count of smaller elements// on right side of each element in an Array// using Merge sortusing System;using System.Collections.Generic; class GFG{ // Class for storing the index // and Value pairs public class Item { public int val; public int index; public Item(int val, int index) { this.val = val; this.index = index; } } // Function to count the number of // smaller elements on right side public List<int> countSmall(int[] A) { int len = A.Length; Item[] items = new Item[len]; for (int i = 0; i < len; i++) { items[i] = new Item(A[i], i); } int[] count = new int[len]; mergeSort(items, 0, len - 1, count); List<int> res = new List<int>(); foreach (int i in count) { res.Add(i); } return res; } // Function for Merge Sort private void mergeSort(Item[] items, int low, int high, int[] count) { if (low >= high) { return; } int mid = low + (high - low) / 2; mergeSort(items, low, mid, count); mergeSort(items, mid + 1, high, count); merge(items, low, mid, mid + 1, high, count); } // Utility function that merge the array // and count smaller element on right side private void merge(Item[] items, int low, int lowEnd, int high, int highEnd, int[] count) { int m = highEnd - low + 1; Item[] sorted = new Item[m]; int rightCounter = 0; int lowPtr = low, highPtr = high; int index = 0; // Loop to store the count of smaller // Elements on right side when both // Array have some elements while (lowPtr <= lowEnd && highPtr <= highEnd) { if (items[lowPtr].val > items[highPtr].val) { rightCounter++; sorted[index++] = items[highPtr++]; } else { count[items[lowPtr].index] += rightCounter; sorted[index++] = items[lowPtr++]; } } // Loop to store the count of smaller // elements in right side when only // left array have some element while (lowPtr <= lowEnd) { count[items[lowPtr].index] += rightCounter; sorted[index++] = items[lowPtr++]; } // Loop to store the count of smaller // elements in right side when only // right array have some element while (highPtr <= highEnd) { sorted[index++] = items[highPtr++]; } Array.Copy(sorted, 0, items, low, m); } // Utility function that prints // out an array on a line void printArray(List<int> countList) { foreach (int i in countList) Console.Write(i + " "); Console.WriteLine(""); } // Driver Code public static void Main(String[] args) { GFG cntSmall = new GFG(); int []arr = { 10, 9, 5, 2, 7, 6, 11, 0, 2 }; int n = arr.Length; List<int> countList = cntSmall.countSmall(arr); cntSmall.printArray(countList); }} // This code is contributed by 29AjayKumar <script> // Javascript program to find the count of// smaller elements on right side of each// element in an Array using Merge sortlet N = 100001;let ans = new Array(N); // Utility function that merge the array// and count smaller element on right sidefunction merge(a, start, mid, end){ let f = new Array((mid - start + 1)); let s = new Array(end - mid); let n = mid - start + 1; let m = end - mid; for(let i = start; i <= mid; i++) f[i - start] = a[i]; for(let i = mid + 1; i <= end; i++) s[i - mid - 1] = a[i]; let i = 0, j = 0, k = start; let cnt = 0; // Loop to store the count of smaller // Elements on right side when both // Array have some elements while(i < n && j < m) { if (f[i][1] <= s[j][1]) { ans[f[i][0]] += cnt; a[k++] = f[i++]; } else { cnt++; a[k++] = s[j++]; } } // Loop to store the count of smaller // elements in right side when only // left array have some element while(i < n) { ans[f[i][0]] += cnt; a[k++] = f[i++]; } // Loop to store the count of smaller // elements in right side when only // right array have some element while(j < m) { a[k++] = s[j++]; } } // Function to invoke merge sort.function mergesort(item, low, high){ if (low >= high) return; let mid = Math.floor((low + high) / 2); mergesort(item, low, mid); mergesort(item, mid + 1, high); merge(item, low, mid, high);} // Utility function that prints// out an array on a linefunction print(arr, n){ for(let i = 0; i < n; i++) document.write(arr[i] + " ");} // Driver Codelet arr = [ 10, 9, 5, 2, 7, 6, 11, 0, 2 ];let n = arr.length;let a = new Array(n);for(let i = 0; i < a.length; i++){ a[i] = new Array(2);}for(let i = 0; i < ans.length; i++){ ans[i] = 0;} for(let i = 0; i < n; i++){ a[i][1] = arr[i]; a[i][0] = i;}mergesort(a, 0, n - 1);print(ans, n); // This code is contributed by rag2127 </script> 7 6 3 1 3 2 2 0 0 Time Complexity: O(N log N)Related Article: Count smaller elements on right side 29AjayKumar rishabhtyagi2306 ukasp rag2127 Arrays Divide and Conquer Sorting Arrays Divide and Conquer Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Building Heap from Array Reversal algorithm for array rotation Program to find sum of elements in a given array Merge Sort QuickSort Binary Search Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 24820, "s": 24792, "text": "\n02 Jun, 2021" }, { "code": null, "e": 24963, "s": 24820, "text": "Given an array arr[] of N integers, the task is to count the number of smaller elements on the right side for each of the element in the array" }, { "code": null, "e": 24974, "s": 24963, "text": "Examples: " }, { "code": null, "e": 25166, "s": 24974, "text": "Input: arr[] = {6, 3, 7, 2} Output: 2, 1, 1, 0 Explanation: Smaller elements after 6 = 2 [3, 2] Smaller elements after 3 = 1 [2] Smaller elements after 7 = 1 [2] Smaller elements after 2 = 0 " }, { "code": null, "e": 25361, "s": 25166, "text": "Input: arr[] = {6, 19, 111, 13} Output: 0, 1, 1, 0 Explanation: Smaller elements after 6 = 0 Smaller elements after 19 = 1 [13] Smaller elements after 111 = 1 [13] Smaller elements after 13 = 0 " }, { "code": null, "e": 25730, "s": 25361, "text": "Approach: Use the idea of the merge sort at the time of merging two arrays. When higher index element is less than the lower index element, it represents that the higher index element is smaller than all the elements after that lower index because the left part is already sorted. Hence add up to all the elements after the lower index element for the required count. " }, { "code": null, "e": 25781, "s": 25730, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 25785, "s": 25781, "text": "C++" }, { "code": null, "e": 25790, "s": 25785, "text": "Java" }, { "code": null, "e": 25798, "s": 25790, "text": "Python3" }, { "code": null, "e": 25801, "s": 25798, "text": "C#" }, { "code": null, "e": 25812, "s": 25801, "text": "Javascript" }, { "code": "// C++ program to find the count of// smaller elements on right side of// each element in an Array// using Merge sort#include <bits/stdc++.h>using namespace std; const int N = 100001;int ans[N]; // Utility function that merge the array// and count smaller element on right sidevoid merge(pair<int, int> a[], int start, int mid, int end){ pair<int, int> f[mid - start + 1], s[end - mid]; int n = mid - start + 1; int m = end - mid; for(int i = start; i <= mid; i++) f[i - start] = a[i]; for(int i = mid + 1; i <= end; i++) s[i - mid - 1] = a[i]; int i = 0, j = 0, k = start; int cnt = 0; // Loop to store the count of smaller // Elements on right side when both // Array have some elements while(i < n && j < m) { if (f[i].second <= s[j].second) { ans[f[i].first] += cnt; a[k++] = f[i++]; } else { cnt++; a[k++] = s[j++]; } } // Loop to store the count of smaller // elements in right side when only // left array have some element while(i < n) { ans[f[i].first] += cnt; a[k++] = f[i++]; } // Loop to store the count of smaller // elements in right side when only // right array have some element while(j < m) { a[k++] = s[j++]; }} // Function to invoke merge sort.void mergesort(pair<int, int> item[], int low, int high){ if (low >= high) return; int mid = (low + high) / 2; mergesort(item, low, mid); mergesort(item, mid + 1, high); merge(item, low, mid, high);} // Utility function that prints// out an array on a linevoid print(int arr[], int n){ for(int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver code.int main(){ int arr[] = { 10, 9, 5, 2, 7, 6, 11, 0, 2 }; int n = sizeof(arr) / sizeof(int); pair<int, int> a[n]; memset(ans, 0, sizeof(ans)); for(int i = 0; i < n; i++) { a[i].second = arr[i]; a[i].first = i; } mergesort(a, 0, n - 1); print(ans, n); return 0;} // This code is contributed by rishabhtyagi2306", "e": 28060, "s": 25812, "text": null }, { "code": "// Java program to find the count of smaller elements// on right side of each element in an Array// using Merge sort import java.util.*; public class GFG { // Class for storing the index // and Value pairs class Item { int val; int index; public Item(int val, int index) { this.val = val; this.index = index; } } // Function to count the number of // smaller elements on right side public ArrayList<Integer> countSmall(int[] A) { int len = A.length; Item[] items = new Item[len]; for (int i = 0; i < len; i++) { items[i] = new Item(A[i], i); } int[] count = new int[len]; mergeSort(items, 0, len - 1, count); ArrayList<Integer> res = new ArrayList<>(); for (int i : count) { res.add(i); } return res; } // Function for Merge Sort private void mergeSort(Item[] items, int low, int high, int[] count) { if (low >= high) { return; } int mid = low + (high - low) / 2; mergeSort(items, low, mid, count); mergeSort(items, mid + 1, high, count); merge(items, low, mid, mid + 1, high, count); } // Utility function that merge the array // and count smaller element on right side private void merge(Item[] items, int low, int lowEnd, int high, int highEnd, int[] count) { int m = highEnd - low + 1; Item[] sorted = new Item[m]; int rightCounter = 0; int lowPtr = low, highPtr = high; int index = 0; // Loop to store the count of smaller // Elements on right side when both // Array have some elements while (lowPtr <= lowEnd && highPtr <= highEnd) { if (items[lowPtr].val > items[highPtr].val) { rightCounter++; sorted[index++] = items[highPtr++]; } else { count[items[lowPtr].index] += rightCounter; sorted[index++] = items[lowPtr++]; } } // Loop to store the count of smaller // elements in right side when only // left array have some element while (lowPtr <= lowEnd) { count[items[lowPtr].index] += rightCounter; sorted[index++] = items[lowPtr++]; } // Loop to store the count of smaller // elements in right side when only // right array have some element while (highPtr <= highEnd) { sorted[index++] = items[highPtr++]; } System.arraycopy(sorted, 0, items, low, m); } // Utility function that prints // out an array on a line void printArray(ArrayList<Integer> countList) { for (Integer i : countList) System.out.print(i + \" \"); System.out.println(\"\"); } // Driver Code public static void main(String[] args) { GFG cntSmall = new GFG(); int arr[] = { 10, 9, 5, 2, 7, 6, 11, 0, 2 }; int n = arr.length; ArrayList<Integer> countList = cntSmall.countSmall(arr); cntSmall.printArray(countList); }}", "e": 31305, "s": 28060, "text": null }, { "code": "# Python3 program to find the count of# smaller elements on right side of# each element in an Array# using Merge sortN = 100001ans = [0] * N # Utility function that merge the array# and count smaller element on right sidedef merge(a, start, mid, end): f = [0] * (mid - start + 1) s = [0] * (end - mid) n = mid - start + 1 m = end - mid for i in range(start, mid + 1): f[i - start] = a[i] for i in range ( mid + 1, end + 1): s[i - mid - 1] = a[i] i = 0 j = 0 k = start cnt = 0 # Loop to store the count of smaller # Elements on right side when both # Array have some elements while (i < n and j < m): if (f[i][1] <= s[j][1]): ans[f[i][0]] += cnt a[k] = f[i] k += 1 i += 1 else: cnt += 1 a[k] = s[j] k += 1 j += 1 # Loop to store the count of smaller # elements in right side when only # left array have some element while (i < n): ans[f[i][0]] += cnt a[k] = f[i]; k += 1 i += 1 # Loop to store the count of smaller # elements in right side when only # right array have some element while (j < m): a[k] = s[j] k += 1 j += 1 # Function to invoke merge sort.def mergesort(item, low, high): if (low >= high): return mid = (low + high) // 2 mergesort(item, low, mid) mergesort(item, mid + 1, high) merge(item, low, mid, high) # Utility function that prints# out an array on a linedef print_(arr, n): for i in range(n): print(arr[i], end = \" \") # Driver code.if __name__ == \"__main__\": arr = [ 10, 9, 5, 2, 7, 6, 11, 0, 2 ] n = len(arr) a = [[0 for x in range(2)] for y in range(n)] for i in range(n): a[i][1] = arr[i] a[i][0] = i mergesort(a, 0, n - 1) print_(ans, n) # This code is contributed by chitranayal", "e": 33340, "s": 31305, "text": null }, { "code": "// C# program to find the count of smaller elements// on right side of each element in an Array// using Merge sortusing System;using System.Collections.Generic; class GFG{ // Class for storing the index // and Value pairs public class Item { public int val; public int index; public Item(int val, int index) { this.val = val; this.index = index; } } // Function to count the number of // smaller elements on right side public List<int> countSmall(int[] A) { int len = A.Length; Item[] items = new Item[len]; for (int i = 0; i < len; i++) { items[i] = new Item(A[i], i); } int[] count = new int[len]; mergeSort(items, 0, len - 1, count); List<int> res = new List<int>(); foreach (int i in count) { res.Add(i); } return res; } // Function for Merge Sort private void mergeSort(Item[] items, int low, int high, int[] count) { if (low >= high) { return; } int mid = low + (high - low) / 2; mergeSort(items, low, mid, count); mergeSort(items, mid + 1, high, count); merge(items, low, mid, mid + 1, high, count); } // Utility function that merge the array // and count smaller element on right side private void merge(Item[] items, int low, int lowEnd, int high, int highEnd, int[] count) { int m = highEnd - low + 1; Item[] sorted = new Item[m]; int rightCounter = 0; int lowPtr = low, highPtr = high; int index = 0; // Loop to store the count of smaller // Elements on right side when both // Array have some elements while (lowPtr <= lowEnd && highPtr <= highEnd) { if (items[lowPtr].val > items[highPtr].val) { rightCounter++; sorted[index++] = items[highPtr++]; } else { count[items[lowPtr].index] += rightCounter; sorted[index++] = items[lowPtr++]; } } // Loop to store the count of smaller // elements in right side when only // left array have some element while (lowPtr <= lowEnd) { count[items[lowPtr].index] += rightCounter; sorted[index++] = items[lowPtr++]; } // Loop to store the count of smaller // elements in right side when only // right array have some element while (highPtr <= highEnd) { sorted[index++] = items[highPtr++]; } Array.Copy(sorted, 0, items, low, m); } // Utility function that prints // out an array on a line void printArray(List<int> countList) { foreach (int i in countList) Console.Write(i + \" \"); Console.WriteLine(\"\"); } // Driver Code public static void Main(String[] args) { GFG cntSmall = new GFG(); int []arr = { 10, 9, 5, 2, 7, 6, 11, 0, 2 }; int n = arr.Length; List<int> countList = cntSmall.countSmall(arr); cntSmall.printArray(countList); }} // This code is contributed by 29AjayKumar", "e": 36678, "s": 33340, "text": null }, { "code": "<script> // Javascript program to find the count of// smaller elements on right side of each// element in an Array using Merge sortlet N = 100001;let ans = new Array(N); // Utility function that merge the array// and count smaller element on right sidefunction merge(a, start, mid, end){ let f = new Array((mid - start + 1)); let s = new Array(end - mid); let n = mid - start + 1; let m = end - mid; for(let i = start; i <= mid; i++) f[i - start] = a[i]; for(let i = mid + 1; i <= end; i++) s[i - mid - 1] = a[i]; let i = 0, j = 0, k = start; let cnt = 0; // Loop to store the count of smaller // Elements on right side when both // Array have some elements while(i < n && j < m) { if (f[i][1] <= s[j][1]) { ans[f[i][0]] += cnt; a[k++] = f[i++]; } else { cnt++; a[k++] = s[j++]; } } // Loop to store the count of smaller // elements in right side when only // left array have some element while(i < n) { ans[f[i][0]] += cnt; a[k++] = f[i++]; } // Loop to store the count of smaller // elements in right side when only // right array have some element while(j < m) { a[k++] = s[j++]; } } // Function to invoke merge sort.function mergesort(item, low, high){ if (low >= high) return; let mid = Math.floor((low + high) / 2); mergesort(item, low, mid); mergesort(item, mid + 1, high); merge(item, low, mid, high);} // Utility function that prints// out an array on a linefunction print(arr, n){ for(let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Driver Codelet arr = [ 10, 9, 5, 2, 7, 6, 11, 0, 2 ];let n = arr.length;let a = new Array(n);for(let i = 0; i < a.length; i++){ a[i] = new Array(2);}for(let i = 0; i < ans.length; i++){ ans[i] = 0;} for(let i = 0; i < n; i++){ a[i][1] = arr[i]; a[i][0] = i;}mergesort(a, 0, n - 1);print(ans, n); // This code is contributed by rag2127 </script>", "e": 38757, "s": 36678, "text": null }, { "code": null, "e": 38775, "s": 38757, "text": "7 6 3 1 3 2 2 0 0" }, { "code": null, "e": 38857, "s": 38775, "text": "Time Complexity: O(N log N)Related Article: Count smaller elements on right side " }, { "code": null, "e": 38869, "s": 38857, "text": "29AjayKumar" }, { "code": null, "e": 38886, "s": 38869, "text": "rishabhtyagi2306" }, { "code": null, "e": 38892, "s": 38886, "text": "ukasp" }, { "code": null, "e": 38900, "s": 38892, "text": "rag2127" }, { "code": null, "e": 38907, "s": 38900, "text": "Arrays" }, { "code": null, "e": 38926, "s": 38907, "text": "Divide and Conquer" }, { "code": null, "e": 38934, "s": 38926, "text": "Sorting" }, { "code": null, "e": 38941, "s": 38934, "text": "Arrays" }, { "code": null, "e": 38960, "s": 38941, "text": "Divide and Conquer" }, { "code": null, "e": 38968, "s": 38960, "text": "Sorting" }, { "code": null, "e": 39066, "s": 38968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39091, "s": 39066, "text": "Window Sliding Technique" }, { "code": null, "e": 39111, "s": 39091, "text": "Trapping Rain Water" }, { "code": null, "e": 39136, "s": 39111, "text": "Building Heap from Array" }, { "code": null, "e": 39174, "s": 39136, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 39223, "s": 39174, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 39234, "s": 39223, "text": "Merge Sort" }, { "code": null, "e": 39244, "s": 39234, "text": "QuickSort" }, { "code": null, "e": 39258, "s": 39244, "text": "Binary Search" }, { "code": null, "e": 39285, "s": 39258, "text": "Program for Tower of Hanoi" } ]
How to read multiple text files from a folder in Python?(Tkinter)
Python is capable of handling files, objects, and creating different applications. We can use Python's extensions and packages to build and develop fully featured applications. Suppose you want to control the files in your system; then Python provides an OS Module which has system-enabled functionalities to allow you interact with the files in the operating system. Let us see how we can read multiple text files from a folder using the OS module in Python. Import the OS module in your notebook. Import the OS module in your notebook. Define a path where the text files are located in your system. Define a path where the text files are located in your system. Create a list of files and iterate over to find if they all are having the correct extension or not. Create a list of files and iterate over to find if they all are having the correct extension or not. Read the files using the defined function in the module. Read the files using the defined function in the module. # Import the required libraries import os # Define the location of the directory path =r"C:/Users/Sairam/Documents/" # Change the directory os.chdir(path) def read_files(file_path): with open(file_path, 'r') as file: print(file.read()) # Iterate over all the files in the directory for file in os.listdir(): if file.endswith('.txt'): # Create the filepath of particular file file_path =f"{path}/{file}" read_files(file_path) Sample 1 ======== Welcome to Tutorialspoint. You are browsing the best resource for Online Education. Sample 2 ======== A distributed ledger is a type of data structure which resides across multiple computer devices, generally spread across locations or regions. Distributed ledger technology (DLT) includes blockchain technologies and smart contracts. While distributed ledgers existed prior to Bitcoin, the Bitcoin blockchain marks the convergence of a host of technologies, including timestamping of transactions, Peer-to-Peer (P2P) networks, cryptography, and shared computational power, along with a new consensus algorithm. We have two text files in the specified location and the program read the contents of these two files and displayed the text on the console.
[ { "code": null, "e": 1239, "s": 1062, "text": "Python is capable of handling files, objects, and creating different applications. We can use Python's extensions and packages to build and develop fully featured applications." }, { "code": null, "e": 1430, "s": 1239, "text": "Suppose you want to control the files in your system; then Python provides an OS Module which has system-enabled functionalities to allow you interact with the files in the operating system." }, { "code": null, "e": 1522, "s": 1430, "text": "Let us see how we can read multiple text files from a folder using the OS module in Python." }, { "code": null, "e": 1561, "s": 1522, "text": "Import the OS module in your notebook." }, { "code": null, "e": 1600, "s": 1561, "text": "Import the OS module in your notebook." }, { "code": null, "e": 1663, "s": 1600, "text": "Define a path where the text files are located in your system." }, { "code": null, "e": 1726, "s": 1663, "text": "Define a path where the text files are located in your system." }, { "code": null, "e": 1827, "s": 1726, "text": "Create a list of files and iterate over to find if they all are having the correct extension or not." }, { "code": null, "e": 1928, "s": 1827, "text": "Create a list of files and iterate over to find if they all are having the correct extension or not." }, { "code": null, "e": 1985, "s": 1928, "text": "Read the files using the defined function in the module." }, { "code": null, "e": 2042, "s": 1985, "text": "Read the files using the defined function in the module." }, { "code": null, "e": 2496, "s": 2042, "text": "# Import the required libraries\nimport os\n\n# Define the location of the directory\npath =r\"C:/Users/Sairam/Documents/\"\n\n# Change the directory\nos.chdir(path)\n\ndef read_files(file_path):\n with open(file_path, 'r') as file:\n print(file.read())\n\n# Iterate over all the files in the directory\nfor file in os.listdir():\n if file.endswith('.txt'):\n # Create the filepath of particular file\n file_path =f\"{path}/{file}\"\n\nread_files(file_path)" }, { "code": null, "e": 3130, "s": 2496, "text": "Sample 1\n========\nWelcome to Tutorialspoint.\n\nYou are browsing the best resource for Online Education.\n\nSample 2\n========\nA distributed ledger is a type of data structure which resides across multiple computer devices, generally spread across locations or regions.\n\nDistributed ledger technology (DLT) includes blockchain technologies and smart contracts.\n\nWhile distributed ledgers existed prior to Bitcoin, the Bitcoin blockchain marks the convergence of a host of technologies, including timestamping of transactions, Peer-to-Peer (P2P) networks, cryptography, and shared computational power, along with a new consensus algorithm." }, { "code": null, "e": 3271, "s": 3130, "text": "We have two text files in the specified location and the program read the contents of these two files and displayed the text on the console." } ]
Print number of words, vowels and frequency of each character - GeeksforGeeks
28 Jun, 2021 Given a string str with uppercase, lowercase and special characters. The input string is to end with either a space or a dot. The problem is to calculate the number of words, vowels and frequency of each character of the string in a separate line.Example : Input : How Good GOD Is. Output : Number of words = 4 Number of vowels = 5 Number of upper case characters = 6 Character = Frequency = 3 Character = . Frequency = 1 Character = D Frequency = 1 Character = G Frequency = 2 Character = H Frequency = 1 Character = I Frequency = 1 Character = O Frequency = 1 Character = d Frequency = 1 Character = o Frequency = 3 Character = s Frequency = 1 Character = w Frequency = 1 Approach : We use a TreeMap to store characters and their frequencies. TreeMap is used to get the output in sorted order.Below is Java implementation of above approach : C++ Java Python 3 // C++ program to print Number of Words,// Vowels and Frequency of Each Character#include <bits/stdc++.h>using namespace std; void words(string str){ int wcount = 0, ucount = 0, vcount = 0; for (int i = 0; i < str.length(); i++) { char c = str[i]; switch (c) { case ' ': case '.': wcount++; // more delimiters can be given } switch (c) { case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': vcount++; } if (c >= 65 and c <= 90) ucount++; } cout << "Number of words = " << wcount << endl; cout << "Number of vowels = " << vcount << endl; cout << "Number of upper case characters = " << ucount << endl;} // Function to calculate the frequency// of each character in the stringvoid frequency(string str){ // Creates an empty TreeMap map<char, int> hmap; // Traverse through the given array for (int i = 0; i < str.length(); i++) hmap[str[i]]++; // Print result for (auto i : hmap) { cout << "Character = " << i.first; cout << " Frequency = " << i.second << endl; }} // Driver Codeint main(int argc, char const *argv[]){ string str = "Geeks for Geeks."; words(str); frequency(str); return 0;} // This code is contributed by// sanjeev2552 // Java program to print Number of Words,// Vowels and Frequency of Each Characterimport java.util.*;import java.lang.*;import java.io.*; public class Stringfun{ String str = "Geeks for Geeks."; void words() { int wCount = 0, uCount = 0, vCount = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case ' ': case '.': wCount++; // more delimiters can be given } switch (c) { // program for calculating number of vowels case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': vCount++; } if (c >= 65 && c <= 90) { uCount++; } } System.out.println("Number of words = " + wCount); System.out.println("Number of vowels = " + vCount); System.out.println("Number of upper case characters = " + uCount); } // Function to calculate the frequency // of each character in the string void frequency() { // Creates an empty TreeMap TreeMap<Character, Integer> hmap = new TreeMap<Character, Integer>(); // Traverse through the given array for (int i = 0; i < str.length(); i++) { Integer c = hmap.get(str.charAt(i)); // If this is first occurrence of element if (hmap.get(str.charAt(i)) == null) hmap.put(str.charAt(i), 1); // If elements already exists in hash map else hmap.put(str.charAt(i), ++c); } // Print result for (Map.Entry m:hmap.entrySet()) System.out.println("Character = " + m.getKey() + " Frequency = " + m.getValue()); } // Driver program to run and test above program public static void main(String args[]) throws IOException { Stringfun obj = new Stringfun(); obj.words(); obj.frequency(); }} # Python3 program to print Number of Words,# Vowels and Frequency of Each Character # A method to count the number of# uppercase character, vowels and number of wordsdef words(str): wcount = vcount = ucount = i = 0 while i < len(str): ch = str[i] # condition checking for word count if (ch == " " or ch == "."): wcount += 1 # condition checking for vowels # in lower case if(ch == "a" or ch == "e" or ch == "i" or ch == 'o' or ch == "u"): vcount += 1 # condition checking for vowels in uppercase if (ch == "A" or ch == "E" or ch == "I" or ch == 'O' or ch == "U"): vcount += 1 # condition checking for upper case characters if (ord(ch) >= 65 and ord(ch) <= 90): ucount += 1 i += 1 print("number of words = ", wcount) print("number of vowels = ", vcount) print("number of upper case characters = ", ucount) # a method to print the frequency# of each character.def frequency(str): i = 1 # checking each and every # ascii code character while i < 127: ch1 = chr(i) c = 0 j = 0 while j < len(str): ch2 = str[j] if(ch1 == ch2): c += 1 j += 1 # condition to print the frequency if c > 0: print("Character:", ch1 + " Frequency:", c) i += 1 # Driver Code # sample string to check the code s = "Geeks for Geeks." # function callingwords(s)frequency(s) # This code is contributed by Animesh_Gupta Output : Number of words = 3 Number of vowels = 5 Number of upper case characters = 2 Character = Frequency = 2 Character = . Frequency = 1 Character = G Frequency = 2 Character = e Frequency = 4 Character = f Frequency = 1 Character = k Frequency = 2 Character = o Frequency = 1 Character = r Frequency = 1 Character = s Frequency = 2 Time Complexity : O(n), where n is the number of characters in the string. Auxiliary Space : O(1). sanjeev2552 Animesh_Gupta surinderdawra388 Java-String-Programs Java-Strings java-TreeMap Java Strings Java-Strings Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Singleton Class in Java LinkedList in Java Collections in Java Set in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types Python program to check if a string is palindrome or not
[ { "code": null, "e": 24432, "s": 24404, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24691, "s": 24432, "text": "Given a string str with uppercase, lowercase and special characters. The input string is to end with either a space or a dot. The problem is to calculate the number of words, vowels and frequency of each character of the string in a separate line.Example : " }, { "code": null, "e": 25112, "s": 24691, "text": "Input : How Good GOD Is.\n\nOutput : \nNumber of words = 4\nNumber of vowels = 5\nNumber of upper case characters = 6\nCharacter = Frequency = 3\nCharacter = . Frequency = 1\nCharacter = D Frequency = 1\nCharacter = G Frequency = 2\nCharacter = H Frequency = 1\nCharacter = I Frequency = 1\nCharacter = O Frequency = 1\nCharacter = d Frequency = 1\nCharacter = o Frequency = 3\nCharacter = s Frequency = 1\nCharacter = w Frequency = 1" }, { "code": null, "e": 25286, "s": 25114, "text": "Approach : We use a TreeMap to store characters and their frequencies. TreeMap is used to get the output in sorted order.Below is Java implementation of above approach : " }, { "code": null, "e": 25290, "s": 25286, "text": "C++" }, { "code": null, "e": 25295, "s": 25290, "text": "Java" }, { "code": null, "e": 25304, "s": 25295, "text": "Python 3" }, { "code": "// C++ program to print Number of Words,// Vowels and Frequency of Each Character#include <bits/stdc++.h>using namespace std; void words(string str){ int wcount = 0, ucount = 0, vcount = 0; for (int i = 0; i < str.length(); i++) { char c = str[i]; switch (c) { case ' ': case '.': wcount++; // more delimiters can be given } switch (c) { case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': vcount++; } if (c >= 65 and c <= 90) ucount++; } cout << \"Number of words = \" << wcount << endl; cout << \"Number of vowels = \" << vcount << endl; cout << \"Number of upper case characters = \" << ucount << endl;} // Function to calculate the frequency// of each character in the stringvoid frequency(string str){ // Creates an empty TreeMap map<char, int> hmap; // Traverse through the given array for (int i = 0; i < str.length(); i++) hmap[str[i]]++; // Print result for (auto i : hmap) { cout << \"Character = \" << i.first; cout << \" Frequency = \" << i.second << endl; }} // Driver Codeint main(int argc, char const *argv[]){ string str = \"Geeks for Geeks.\"; words(str); frequency(str); return 0;} // This code is contributed by// sanjeev2552", "e": 26818, "s": 25304, "text": null }, { "code": "// Java program to print Number of Words,// Vowels and Frequency of Each Characterimport java.util.*;import java.lang.*;import java.io.*; public class Stringfun{ String str = \"Geeks for Geeks.\"; void words() { int wCount = 0, uCount = 0, vCount = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case ' ': case '.': wCount++; // more delimiters can be given } switch (c) { // program for calculating number of vowels case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': vCount++; } if (c >= 65 && c <= 90) { uCount++; } } System.out.println(\"Number of words = \" + wCount); System.out.println(\"Number of vowels = \" + vCount); System.out.println(\"Number of upper case characters = \" + uCount); } // Function to calculate the frequency // of each character in the string void frequency() { // Creates an empty TreeMap TreeMap<Character, Integer> hmap = new TreeMap<Character, Integer>(); // Traverse through the given array for (int i = 0; i < str.length(); i++) { Integer c = hmap.get(str.charAt(i)); // If this is first occurrence of element if (hmap.get(str.charAt(i)) == null) hmap.put(str.charAt(i), 1); // If elements already exists in hash map else hmap.put(str.charAt(i), ++c); } // Print result for (Map.Entry m:hmap.entrySet()) System.out.println(\"Character = \" + m.getKey() + \" Frequency = \" + m.getValue()); } // Driver program to run and test above program public static void main(String args[]) throws IOException { Stringfun obj = new Stringfun(); obj.words(); obj.frequency(); }}", "e": 29066, "s": 26818, "text": null }, { "code": "# Python3 program to print Number of Words,# Vowels and Frequency of Each Character # A method to count the number of# uppercase character, vowels and number of wordsdef words(str): wcount = vcount = ucount = i = 0 while i < len(str): ch = str[i] # condition checking for word count if (ch == \" \" or ch == \".\"): wcount += 1 # condition checking for vowels # in lower case if(ch == \"a\" or ch == \"e\" or ch == \"i\" or ch == 'o' or ch == \"u\"): vcount += 1 # condition checking for vowels in uppercase if (ch == \"A\" or ch == \"E\" or ch == \"I\" or ch == 'O' or ch == \"U\"): vcount += 1 # condition checking for upper case characters if (ord(ch) >= 65 and ord(ch) <= 90): ucount += 1 i += 1 print(\"number of words = \", wcount) print(\"number of vowels = \", vcount) print(\"number of upper case characters = \", ucount) # a method to print the frequency# of each character.def frequency(str): i = 1 # checking each and every # ascii code character while i < 127: ch1 = chr(i) c = 0 j = 0 while j < len(str): ch2 = str[j] if(ch1 == ch2): c += 1 j += 1 # condition to print the frequency if c > 0: print(\"Character:\", ch1 + \" Frequency:\", c) i += 1 # Driver Code # sample string to check the code s = \"Geeks for Geeks.\" # function callingwords(s)frequency(s) # This code is contributed by Animesh_Gupta", "e": 30779, "s": 29066, "text": null }, { "code": null, "e": 30790, "s": 30779, "text": "Output : " }, { "code": null, "e": 31119, "s": 30790, "text": "Number of words = 3\nNumber of vowels = 5\nNumber of upper case characters = 2\nCharacter = Frequency = 2\nCharacter = . Frequency = 1\nCharacter = G Frequency = 2\nCharacter = e Frequency = 4\nCharacter = f Frequency = 1\nCharacter = k Frequency = 2\nCharacter = o Frequency = 1\nCharacter = r Frequency = 1\nCharacter = s Frequency = 2" }, { "code": null, "e": 31219, "s": 31119, "text": "Time Complexity : O(n), where n is the number of characters in the string. Auxiliary Space : O(1). " }, { "code": null, "e": 31231, "s": 31219, "text": "sanjeev2552" }, { "code": null, "e": 31245, "s": 31231, "text": "Animesh_Gupta" }, { "code": null, "e": 31262, "s": 31245, "text": "surinderdawra388" }, { "code": null, "e": 31283, "s": 31262, "text": "Java-String-Programs" }, { "code": null, "e": 31296, "s": 31283, "text": "Java-Strings" }, { "code": null, "e": 31309, "s": 31296, "text": "java-TreeMap" }, { "code": null, "e": 31314, "s": 31309, "text": "Java" }, { "code": null, "e": 31322, "s": 31314, "text": "Strings" }, { "code": null, "e": 31335, "s": 31322, "text": "Java-Strings" }, { "code": null, "e": 31343, "s": 31335, "text": "Strings" }, { "code": null, "e": 31348, "s": 31343, "text": "Java" }, { "code": null, "e": 31446, "s": 31348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31455, "s": 31446, "text": "Comments" }, { "code": null, "e": 31468, "s": 31455, "text": "Old Comments" }, { "code": null, "e": 31487, "s": 31468, "text": "Interfaces in Java" }, { "code": null, "e": 31511, "s": 31487, "text": "Singleton Class in Java" }, { "code": null, "e": 31530, "s": 31511, "text": "LinkedList in Java" }, { "code": null, "e": 31550, "s": 31530, "text": "Collections in Java" }, { "code": null, "e": 31562, "s": 31550, "text": "Set in Java" }, { "code": null, "e": 31608, "s": 31562, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31642, "s": 31608, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 31702, "s": 31642, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31717, "s": 31702, "text": "C++ Data Types" } ]
Style up your photos with a touch of Deep Learning magic | by George Seif | Towards Data Science
Style Transfer in the context of imaging refers to the process of transferring the “style” of one image to another, while maintaining the “content” of the second image. For example, the image on the far left is the “content” image. We apply the “style” of the the middle image (the “style” image) to our content image. We expect that since the middle image has kind of a big city night time vibe to it that this will be reflected in the final image — which is exactly what happens in the result on the far right! One of the most ground-breaking pieces of research in this area came from Adobe Research. They called it Deep Photo Style Transfer (DPST). To properly perform a style transfer from one photo to another, the Adobe team framed the goal of their DPST: “to transfer the style of the reference to the input while keeping the result photorealistic” The key part here is maintaining the “photorealistic” property of the output. If we have a content photo like the one above, we don’t want any of the building to change at all. We just want it to look like that exact same photo was taken at night time. Many style transfer algorithms that came before the publication of this research distorted a lot of the content present the original image. Things like making straight lines wavy and changing the shapes of objects were common to see in the results of Neural Style Transfer techniques at the time. And that was totally acceptable. Many of algorithms were designed for artistic style transfer, so a bit of distortion was even welcomed! But in this case, the aim was to create images that were still realistic — as if they were taken by a real-world camera. There are 2 main things that the authors do to accomplish this: (1) a photorealism regularisation term in the loss function (2) a semantic segmentation of the content image to be used as a guidance. Think of how we would intuitively maintain photorealism in an image. We’d want the lines and shapes of the original image to remain the same. The colors and lighting might change, but a person should still look like a person, a tree like a tree, a dog like a dog, etc. Based on this intuitive idea, the regularisation term implemented by the authors forces the transformation of the pixels from the input to the output to be locally affine in colorspace. An Affine transform by definition must maintain the points, straight lines, and planes when mapping the input to the output. With this constraint, straight lines never go wavy and there won’t be any weird shape shifting in our output! In addition to maintaining the points, straight lines, and planes we also want to make sure that the style of various “things” in the style image are actually transferred realistically. Imagine if you had a style image that showed a beautiful orange sunset like the one down below. Most of the image is a red-ish orange. If we were to style transfer this to, say, a city image, all of the buildings would turn red! That’s not really what we want though — a more realistic transfer would make most of the buildings very dark (close to black) and only the sky would have a sunset and water color. The Deep Photo Style Transfer algorithm uses the results of a Semantic Segmentation applied to the content image in order to guide the style transfer. When the algorithms knows exactly which pixels belong to the foreground and background, it can more realistically transfer the style. Sky pixels will always be transferred to sky pixels, background pixels to background pixels, and so on. You can download the repository for Photo Realistic Style Transfer from GitHub: git clone https://github.com/GeorgeSeif/DeepPhotoStyle_pytorch.git All that’s required for it to run is a recent version of Pytorch. Once that’s done, move into the folder and download the models for the Semantic Segmentation with the downloading script: cd DeepPhotoStyle_pytorchsh download_seg_model.sh Now we’re ready to run our code! Download a style image and a content image — any image of your choice! City and landscape images tend to work best in my experience. Finally, run the code like so: python main.py --style_image path_style_image --content_image path_content_image The algorithm will iteratively improve the style transfer result, so the more you wait the better it will get! By default it’s set to run for 3000 steps, but you can increase that if you feel that more steps is improving the results. Give the code a try yourself, it’s great fun! See how your photos look after the style transfer. Feel free to post a link below to share your photos with the community. Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too! Want to learn more about Deep Learning? The Deep Learning with Python book will teach you how to do real Deep Learning with the easiest Python library ever: Keras! And just a heads up, I support this blog with Amazon affiliate links to great books, because sharing great books helps everyone! As an Amazon Associate I earn from qualifying purchases.
[ { "code": null, "e": 216, "s": 47, "text": "Style Transfer in the context of imaging refers to the process of transferring the “style” of one image to another, while maintaining the “content” of the second image." }, { "code": null, "e": 560, "s": 216, "text": "For example, the image on the far left is the “content” image. We apply the “style” of the the middle image (the “style” image) to our content image. We expect that since the middle image has kind of a big city night time vibe to it that this will be reflected in the final image — which is exactly what happens in the result on the far right!" }, { "code": null, "e": 699, "s": 560, "text": "One of the most ground-breaking pieces of research in this area came from Adobe Research. They called it Deep Photo Style Transfer (DPST)." }, { "code": null, "e": 903, "s": 699, "text": "To properly perform a style transfer from one photo to another, the Adobe team framed the goal of their DPST: “to transfer the style of the reference to the input while keeping the result photorealistic”" }, { "code": null, "e": 1156, "s": 903, "text": "The key part here is maintaining the “photorealistic” property of the output. If we have a content photo like the one above, we don’t want any of the building to change at all. We just want it to look like that exact same photo was taken at night time." }, { "code": null, "e": 1453, "s": 1156, "text": "Many style transfer algorithms that came before the publication of this research distorted a lot of the content present the original image. Things like making straight lines wavy and changing the shapes of objects were common to see in the results of Neural Style Transfer techniques at the time." }, { "code": null, "e": 1590, "s": 1453, "text": "And that was totally acceptable. Many of algorithms were designed for artistic style transfer, so a bit of distortion was even welcomed!" }, { "code": null, "e": 1711, "s": 1590, "text": "But in this case, the aim was to create images that were still realistic — as if they were taken by a real-world camera." }, { "code": null, "e": 1910, "s": 1711, "text": "There are 2 main things that the authors do to accomplish this: (1) a photorealism regularisation term in the loss function (2) a semantic segmentation of the content image to be used as a guidance." }, { "code": null, "e": 2179, "s": 1910, "text": "Think of how we would intuitively maintain photorealism in an image. We’d want the lines and shapes of the original image to remain the same. The colors and lighting might change, but a person should still look like a person, a tree like a tree, a dog like a dog, etc." }, { "code": null, "e": 2490, "s": 2179, "text": "Based on this intuitive idea, the regularisation term implemented by the authors forces the transformation of the pixels from the input to the output to be locally affine in colorspace. An Affine transform by definition must maintain the points, straight lines, and planes when mapping the input to the output." }, { "code": null, "e": 2600, "s": 2490, "text": "With this constraint, straight lines never go wavy and there won’t be any weird shape shifting in our output!" }, { "code": null, "e": 2786, "s": 2600, "text": "In addition to maintaining the points, straight lines, and planes we also want to make sure that the style of various “things” in the style image are actually transferred realistically." }, { "code": null, "e": 2882, "s": 2786, "text": "Imagine if you had a style image that showed a beautiful orange sunset like the one down below." }, { "code": null, "e": 3195, "s": 2882, "text": "Most of the image is a red-ish orange. If we were to style transfer this to, say, a city image, all of the buildings would turn red! That’s not really what we want though — a more realistic transfer would make most of the buildings very dark (close to black) and only the sky would have a sunset and water color." }, { "code": null, "e": 3584, "s": 3195, "text": "The Deep Photo Style Transfer algorithm uses the results of a Semantic Segmentation applied to the content image in order to guide the style transfer. When the algorithms knows exactly which pixels belong to the foreground and background, it can more realistically transfer the style. Sky pixels will always be transferred to sky pixels, background pixels to background pixels, and so on." }, { "code": null, "e": 3664, "s": 3584, "text": "You can download the repository for Photo Realistic Style Transfer from GitHub:" }, { "code": null, "e": 3731, "s": 3664, "text": "git clone https://github.com/GeorgeSeif/DeepPhotoStyle_pytorch.git" }, { "code": null, "e": 3919, "s": 3731, "text": "All that’s required for it to run is a recent version of Pytorch. Once that’s done, move into the folder and download the models for the Semantic Segmentation with the downloading script:" }, { "code": null, "e": 3969, "s": 3919, "text": "cd DeepPhotoStyle_pytorchsh download_seg_model.sh" }, { "code": null, "e": 4002, "s": 3969, "text": "Now we’re ready to run our code!" }, { "code": null, "e": 4166, "s": 4002, "text": "Download a style image and a content image — any image of your choice! City and landscape images tend to work best in my experience. Finally, run the code like so:" }, { "code": null, "e": 4247, "s": 4166, "text": "python main.py --style_image path_style_image --content_image path_content_image" }, { "code": null, "e": 4481, "s": 4247, "text": "The algorithm will iteratively improve the style transfer result, so the more you wait the better it will get! By default it’s set to run for 3000 steps, but you can increase that if you feel that more steps is improving the results." }, { "code": null, "e": 4650, "s": 4481, "text": "Give the code a try yourself, it’s great fun! See how your photos look after the style transfer. Feel free to post a link below to share your photos with the community." }, { "code": null, "e": 4780, "s": 4650, "text": "Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!" }, { "code": null, "e": 4944, "s": 4780, "text": "Want to learn more about Deep Learning? The Deep Learning with Python book will teach you how to do real Deep Learning with the easiest Python library ever: Keras!" } ]
Mastering Indexing and Slicing in Python | by Giorgos Myrianthous | Towards Data Science
In Python, the elements of ordered sequences like strings or lists can be -individually- accessed through their indices. This can be achieved by providing the numerical index of the element we wish to extract from the sequence. Additionally, Python supports slicing that is a characteristic that lets us extract a subset of the original sequence object. In this article, we are going to explore how both indexing and slicing work, and how they can be used in order to write cleaner and more Pythonic code. Like most programming languages, Python offsets start at position 0 and end at position N-1, where N is defined to be the total length of the sequence. For instance, the total length of the string Hello is equal to 5 and each individual character can be accessed through indices 0 to 4 as shown in the diagram below: Now you can programmatically access individual characters in the string, by providing the corresponding offset you wish to fetch, enclosed in square brackets: >>> my_string = 'Hello'>>> print(my_string[0])'H'>>> print(my_string[2])'l'>>> print(my_string[3])'l' It is also important to know that when you attempt to access an offset which is greater than the length of the sequence (minus 1), Python will throw an IndexError informing you that the requested offset is out of range: >>> my_string[5]Traceback (most recent call last): File "<input>", line 1, in <module>IndexError: string index out of range It is also possible to access an element by providing a negative index that essentially corresponds to the index starting from the right of the sequence. The last item can be accessed through offset -1, the last but one through offset -2 and so on Technically when a negative offset is used, Python adds that offset to the length of the sequence in order to infer the exact position. For example, say we want to extract character e from the string my_string = 'Hello’ using a negative offset. Now the expression my_string[-4] will essentially be translated into my_string[len(my_string) — 4] which is equivalent to my_string[5 — 4] and my_string[1]that finally gives us the desired output: >>> my_string[-4]'e' Slicing is one form of indexing that allows us to infer an entire (sub)section of the original sequence rather than just a single item. To perform a slicing over a sequence in Python, you need to provide two offsets separated by a colon although in some cases you can define just one of the two, or even none (more on these cases are discussed below). The first offset denotes the starting point and is inclusive while the second offset denotes the ending point but in contrast to the starting offset, it is non-inclusive. my_string[start:end] Therefore, when performing slicing Python will return a new object including all the elements starting from the lower index up to the position which is one less the upper index. As an example, consider a use-case where we need to take the first two elements of the string: >>> my_string[0:2]'He' As I already mentioned, it is not mandatory to provide explicit offsets. When the starting offset is omitted, then its value will default to 0. On the other hand, when the ending offset is not provided, its default value will be equal to the length of the sequence. There are actually three different scenarios which are shown below: my_string[0:] # Omit ending offsetmy_string[:-1] # Omit starting offsetmy_string[:] # Omit both starting and ending offsets The first notation is typically useful when we want to chop off leading text. Say we want to get all but the first character of our string. We can do so by using the following notation >>> my_string = 'Hello'>>> my_string[1:]'ello' As we already mentioned, when the ending offset is omitted the length of the sequence will be used instead: >>> my_string[1:] == my_string[1:len(my_string)]True Let’s assume that we now want all but the first character of our string. In this case, omitting the starting offset will do the trick: >>> my_string = 'Hello'>>> my_string[:-1]'Hell' Given that the lower bound is skipped, its value will default to 0: >>> my_string[:-1] == my_string[0:-1]True Slicing notation in Python allows us to omit both the starting and ending offsets. >>> my_string = 'Hello'>>> my_string[:] == my_string[0:len(my_string)]True Given that when lower and upper bounds are ignored will default to 0 and len(sequence) respectively you might be wondering whether this could be of any help or use. Well, this is a quick way to take a copy of the object as shown below >>> my_string = 'Hello'>>> my_string_copy = my_string[:] Note that when this slicing technique will generated a different object that will be allocated to a different memory location. This doesn’t make any sort of difference for immutable object types like strings, however it is quite important to be aware of this when dealing with mutable object types such as lists. For more details on this, you can refer to my article Dynamic Typing in Python that discusses how objects are created and (properly) copied. Slicing expressions in Python come with a third index which is optional and when specified is used as a step. Obviously, when the step value is omitted it defaults to 1 which means that no element in the requested sequence sub-section will be skipped. The notation is shown below [start:end:step] As an example, consider that we have a string with the letters of the alphabet from which we want to extract every other item in it, between letters in positions 1 and 19: >>> import string>>> my_string = string.ascii_lowercase # 'abcdefg...'>>> my_string[1:20:2]'bdfhjlnprt' Such notation can be used to replace list comprehensions. For instance, let’s say we want to get all the elements of a list that have an even index. A list comprehension that achieves this would be >>> my_list = [100, 400, 34, 179, 0, 89, 121]>>> [value for index, value in enumerate(my_list) if index % 2 == 0][100, 34, 0, 121] In this occasion, slicing notation could make our code simpler and much more readable: >>> my_list = [100, 400, 34, 179, 0, 89, 121]>>> my_list[::2][100, 34, 0, 121] Like start and end offsets, the step index can be a negative number. Technically this is useful when we want to reverse the order of the elements in an ordered sequence >>> my_string = 'Hello'>>> my_string[::-1]'olleH' In other words, when a negative step index is applied the effect of starting and ending offsets is reversed. To make this clear let’s jump into another example where we actually define all three possible offsets. >>> import string>>> my_string = string.ascii_lowercase # 'abcdefg...'>>> my_string[20:10:-1]'utsrqponml' In the example above, we essentially create a new string from indices 11 to 20 in reversed order. In this article, we explored how indexing and slicing work in Python. Both of these notations are used extensively in most Python applications so you need to make sure you understand how they work. Below we revisit the key points we’ve covered — feel free to use it as a cheatsheet, too. The first item starts at offset 0 The last item ends at offset len(my_sequence) — 1 Negative indices indicate that the count will start backwards. Essentially it is being added to the length of the sequence. For example, my_string[-1] translates to my_string[len(my_string) — 1] The starting index (lower bound) is inclusive The ending index (upper bound) is non-inclusive When the starting index it omitted, it defaults to 0 When the ending index is omitted, it defaults to the length of the sequence When both starting and ending indices are omitted, a copy of the original object is created — my_string[:] The third index denotes the step When the step index is omitted, it defaults to 1 (i.e. no element is skipped) A negative step index helps us create reversed sequences (e.g. my_string[::-1] )
[ { "code": null, "e": 401, "s": 47, "text": "In Python, the elements of ordered sequences like strings or lists can be -individually- accessed through their indices. This can be achieved by providing the numerical index of the element we wish to extract from the sequence. Additionally, Python supports slicing that is a characteristic that lets us extract a subset of the original sequence object." }, { "code": null, "e": 553, "s": 401, "text": "In this article, we are going to explore how both indexing and slicing work, and how they can be used in order to write cleaner and more Pythonic code." }, { "code": null, "e": 870, "s": 553, "text": "Like most programming languages, Python offsets start at position 0 and end at position N-1, where N is defined to be the total length of the sequence. For instance, the total length of the string Hello is equal to 5 and each individual character can be accessed through indices 0 to 4 as shown in the diagram below:" }, { "code": null, "e": 1029, "s": 870, "text": "Now you can programmatically access individual characters in the string, by providing the corresponding offset you wish to fetch, enclosed in square brackets:" }, { "code": null, "e": 1131, "s": 1029, "text": ">>> my_string = 'Hello'>>> print(my_string[0])'H'>>> print(my_string[2])'l'>>> print(my_string[3])'l'" }, { "code": null, "e": 1351, "s": 1131, "text": "It is also important to know that when you attempt to access an offset which is greater than the length of the sequence (minus 1), Python will throw an IndexError informing you that the requested offset is out of range:" }, { "code": null, "e": 1476, "s": 1351, "text": ">>> my_string[5]Traceback (most recent call last): File \"<input>\", line 1, in <module>IndexError: string index out of range" }, { "code": null, "e": 1724, "s": 1476, "text": "It is also possible to access an element by providing a negative index that essentially corresponds to the index starting from the right of the sequence. The last item can be accessed through offset -1, the last but one through offset -2 and so on" }, { "code": null, "e": 2166, "s": 1724, "text": "Technically when a negative offset is used, Python adds that offset to the length of the sequence in order to infer the exact position. For example, say we want to extract character e from the string my_string = 'Hello’ using a negative offset. Now the expression my_string[-4] will essentially be translated into my_string[len(my_string) — 4] which is equivalent to my_string[5 — 4] and my_string[1]that finally gives us the desired output:" }, { "code": null, "e": 2187, "s": 2166, "text": ">>> my_string[-4]'e'" }, { "code": null, "e": 2539, "s": 2187, "text": "Slicing is one form of indexing that allows us to infer an entire (sub)section of the original sequence rather than just a single item. To perform a slicing over a sequence in Python, you need to provide two offsets separated by a colon although in some cases you can define just one of the two, or even none (more on these cases are discussed below)." }, { "code": null, "e": 2710, "s": 2539, "text": "The first offset denotes the starting point and is inclusive while the second offset denotes the ending point but in contrast to the starting offset, it is non-inclusive." }, { "code": null, "e": 2731, "s": 2710, "text": "my_string[start:end]" }, { "code": null, "e": 3004, "s": 2731, "text": "Therefore, when performing slicing Python will return a new object including all the elements starting from the lower index up to the position which is one less the upper index. As an example, consider a use-case where we need to take the first two elements of the string:" }, { "code": null, "e": 3027, "s": 3004, "text": ">>> my_string[0:2]'He'" }, { "code": null, "e": 3361, "s": 3027, "text": "As I already mentioned, it is not mandatory to provide explicit offsets. When the starting offset is omitted, then its value will default to 0. On the other hand, when the ending offset is not provided, its default value will be equal to the length of the sequence. There are actually three different scenarios which are shown below:" }, { "code": null, "e": 3491, "s": 3361, "text": "my_string[0:] # Omit ending offsetmy_string[:-1] # Omit starting offsetmy_string[:] # Omit both starting and ending offsets" }, { "code": null, "e": 3676, "s": 3491, "text": "The first notation is typically useful when we want to chop off leading text. Say we want to get all but the first character of our string. We can do so by using the following notation" }, { "code": null, "e": 3723, "s": 3676, "text": ">>> my_string = 'Hello'>>> my_string[1:]'ello'" }, { "code": null, "e": 3831, "s": 3723, "text": "As we already mentioned, when the ending offset is omitted the length of the sequence will be used instead:" }, { "code": null, "e": 3884, "s": 3831, "text": ">>> my_string[1:] == my_string[1:len(my_string)]True" }, { "code": null, "e": 4019, "s": 3884, "text": "Let’s assume that we now want all but the first character of our string. In this case, omitting the starting offset will do the trick:" }, { "code": null, "e": 4067, "s": 4019, "text": ">>> my_string = 'Hello'>>> my_string[:-1]'Hell'" }, { "code": null, "e": 4135, "s": 4067, "text": "Given that the lower bound is skipped, its value will default to 0:" }, { "code": null, "e": 4177, "s": 4135, "text": ">>> my_string[:-1] == my_string[0:-1]True" }, { "code": null, "e": 4260, "s": 4177, "text": "Slicing notation in Python allows us to omit both the starting and ending offsets." }, { "code": null, "e": 4335, "s": 4260, "text": ">>> my_string = 'Hello'>>> my_string[:] == my_string[0:len(my_string)]True" }, { "code": null, "e": 4570, "s": 4335, "text": "Given that when lower and upper bounds are ignored will default to 0 and len(sequence) respectively you might be wondering whether this could be of any help or use. Well, this is a quick way to take a copy of the object as shown below" }, { "code": null, "e": 4627, "s": 4570, "text": ">>> my_string = 'Hello'>>> my_string_copy = my_string[:]" }, { "code": null, "e": 5081, "s": 4627, "text": "Note that when this slicing technique will generated a different object that will be allocated to a different memory location. This doesn’t make any sort of difference for immutable object types like strings, however it is quite important to be aware of this when dealing with mutable object types such as lists. For more details on this, you can refer to my article Dynamic Typing in Python that discusses how objects are created and (properly) copied." }, { "code": null, "e": 5361, "s": 5081, "text": "Slicing expressions in Python come with a third index which is optional and when specified is used as a step. Obviously, when the step value is omitted it defaults to 1 which means that no element in the requested sequence sub-section will be skipped. The notation is shown below" }, { "code": null, "e": 5378, "s": 5361, "text": "[start:end:step]" }, { "code": null, "e": 5550, "s": 5378, "text": "As an example, consider that we have a string with the letters of the alphabet from which we want to extract every other item in it, between letters in positions 1 and 19:" }, { "code": null, "e": 5654, "s": 5550, "text": ">>> import string>>> my_string = string.ascii_lowercase # 'abcdefg...'>>> my_string[1:20:2]'bdfhjlnprt'" }, { "code": null, "e": 5852, "s": 5654, "text": "Such notation can be used to replace list comprehensions. For instance, let’s say we want to get all the elements of a list that have an even index. A list comprehension that achieves this would be" }, { "code": null, "e": 5983, "s": 5852, "text": ">>> my_list = [100, 400, 34, 179, 0, 89, 121]>>> [value for index, value in enumerate(my_list) if index % 2 == 0][100, 34, 0, 121]" }, { "code": null, "e": 6070, "s": 5983, "text": "In this occasion, slicing notation could make our code simpler and much more readable:" }, { "code": null, "e": 6149, "s": 6070, "text": ">>> my_list = [100, 400, 34, 179, 0, 89, 121]>>> my_list[::2][100, 34, 0, 121]" }, { "code": null, "e": 6318, "s": 6149, "text": "Like start and end offsets, the step index can be a negative number. Technically this is useful when we want to reverse the order of the elements in an ordered sequence" }, { "code": null, "e": 6368, "s": 6318, "text": ">>> my_string = 'Hello'>>> my_string[::-1]'olleH'" }, { "code": null, "e": 6581, "s": 6368, "text": "In other words, when a negative step index is applied the effect of starting and ending offsets is reversed. To make this clear let’s jump into another example where we actually define all three possible offsets." }, { "code": null, "e": 6687, "s": 6581, "text": ">>> import string>>> my_string = string.ascii_lowercase # 'abcdefg...'>>> my_string[20:10:-1]'utsrqponml'" }, { "code": null, "e": 6785, "s": 6687, "text": "In the example above, we essentially create a new string from indices 11 to 20 in reversed order." }, { "code": null, "e": 7073, "s": 6785, "text": "In this article, we explored how indexing and slicing work in Python. Both of these notations are used extensively in most Python applications so you need to make sure you understand how they work. Below we revisit the key points we’ve covered — feel free to use it as a cheatsheet, too." }, { "code": null, "e": 7107, "s": 7073, "text": "The first item starts at offset 0" }, { "code": null, "e": 7157, "s": 7107, "text": "The last item ends at offset len(my_sequence) — 1" }, { "code": null, "e": 7352, "s": 7157, "text": "Negative indices indicate that the count will start backwards. Essentially it is being added to the length of the sequence. For example, my_string[-1] translates to my_string[len(my_string) — 1]" }, { "code": null, "e": 7398, "s": 7352, "text": "The starting index (lower bound) is inclusive" }, { "code": null, "e": 7446, "s": 7398, "text": "The ending index (upper bound) is non-inclusive" }, { "code": null, "e": 7499, "s": 7446, "text": "When the starting index it omitted, it defaults to 0" }, { "code": null, "e": 7575, "s": 7499, "text": "When the ending index is omitted, it defaults to the length of the sequence" }, { "code": null, "e": 7682, "s": 7575, "text": "When both starting and ending indices are omitted, a copy of the original object is created — my_string[:]" }, { "code": null, "e": 7715, "s": 7682, "text": "The third index denotes the step" }, { "code": null, "e": 7793, "s": 7715, "text": "When the step index is omitted, it defaults to 1 (i.e. no element is skipped)" } ]
Bootstrap - Interview Questions
Dear readers, these BOOTSTRAP Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of BOOTSTRAP Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer − Bootstrap is a sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development. It uses HTML, CSS and Javascript. Bootstrap can be used as − Mobile first approach − Since Bootstrap 3, the framework consists of Mobile first styles throughout the entire library instead of in separate files. Mobile first approach − Since Bootstrap 3, the framework consists of Mobile first styles throughout the entire library instead of in separate files. Browser Support − It is supported by all popular browsers. Browser Support − It is supported by all popular browsers. Easy to get started − With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation. Easy to get started − With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation. Responsive design − Bootstrap's responsive CSS adjusts to Desktops,Tablets and Mobiles. Responsive design − Bootstrap's responsive CSS adjusts to Desktops,Tablets and Mobiles. Provides a clean and uniform solution for building an interface for developers. Provides a clean and uniform solution for building an interface for developers. It contains beautiful and functional built-in components which are easy to customize. It contains beautiful and functional built-in components which are easy to customize. It also provides web based customization. It also provides web based customization. And best of all it is an open source. And best of all it is an open source. Bootstrap package includes − Scaffolding − Bootstrap provides a basic structure with Grid System, link styles, background. This is is covered in detail in the section Bootstrap Basic Structure Scaffolding − Bootstrap provides a basic structure with Grid System, link styles, background. This is is covered in detail in the section Bootstrap Basic Structure CSS − Bootstrap comes with feature of global CSS settings, fundamental HTML elements styled and enhanced with extensible classes, and an advanced grid system. This is covered in detail in the section Bootstrap with CSS. CSS − Bootstrap comes with feature of global CSS settings, fundamental HTML elements styled and enhanced with extensible classes, and an advanced grid system. This is covered in detail in the section Bootstrap with CSS. Components − Bootstrap contains over a dozen reusable components built to provide iconography, dropdowns, navigation, alerts, popovers, and much more. This is covered in detail in the section Layout Components. Components − Bootstrap contains over a dozen reusable components built to provide iconography, dropdowns, navigation, alerts, popovers, and much more. This is covered in detail in the section Layout Components. JavaScript Plugins − Bootstrap contains over a dozen custom jQuery plugins. You can easily include them all, or one by one. This is covered in details in the section Bootstrap Plugins. JavaScript Plugins − Bootstrap contains over a dozen custom jQuery plugins. You can easily include them all, or one by one. This is covered in details in the section Bootstrap Plugins. Customize − You can customize Bootstrap's components, LESS variables, and jQuery plugins to get your very own version. Customize − You can customize Bootstrap's components, LESS variables, and jQuery plugins to get your very own version. The Contextual classes allow you to change the background color of your table rows or individual cells. .active Applies the hover color to a particular row or cell .success Indicates a successful or positive action .warning Indicates a warning that might need attention .danger Indicates a dangerous or potentially negative action Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. It includes predefined classes for easy layout options, as well as powerful mixins for generating more semantic layouts. Media Queries in Bootstrap allow you to move, show and hide content based on viewport size. Following is basic structure of Bootstrap grid − <div class = "container"> <div class = "row"> <div class = "col-*-*"></div> <div class = "col-*-*"></div> </div> <div class = "row">...</div> </div> <div class = "container">.... Offsets are a useful feature for more specialized layouts. They can be used to push columns over for more spacing, for example. The .col-xs = * classes don't support offsets, but they are easily replicated by using an empty cell. You can easily change the order of built-in grid columns with .col-md-push-* and .col-md-pull-* modifier classes where * range from 1 to 11. Bootstrap 3 allows to make the images responsive by adding a class .img-responsive to the <img> tag. This class applies max-width: 100%; and height: auto; to the image so that it scales nicely to the parent element. Bootstrap sets a basic global display (background), typography, and link styles − Basic Global display − Sets background-color: #fff; on the <body> element. Basic Global display − Sets background-color: #fff; on the <body> element. Typography − Uses the @font-family-base, @font-size-base, and @line-height-base attributes as the typographic base Typography − Uses the @font-family-base, @font-size-base, and @line-height-base attributes as the typographic base Link styles − Sets the global link color via attribute @link-color and apply link underlines only on :hover. Link styles − Sets the global link color via attribute @link-color and apply link underlines only on :hover. Bootstrap uses Normalize to establish cross browser consistency. Normalize.css is a modern, HTML5-ready alternative to CSS resets. It is a small CSS file that provides better cross-browser consistency in the default styling of HTML elements. To add some emphasis to a paragraph, add class = "lead". This will give you larger font size, lighter weight, and a taller line height Bootstrap supports ordered lists, unordered lists, and definition lists. Ordered lists − An ordered list is a list that falls in some sort of sequential order and is prefaced by numbers. Ordered lists − An ordered list is a list that falls in some sort of sequential order and is prefaced by numbers. Unordered lists − An unordered list is a list that doesn't have any particular order and is traditionally styled with bullets. If you do not want the bullets to appear then you can remove the styling by using the class .list-unstyled. You can also place all list items on a single line using the class .list-inline. Unordered lists − An unordered list is a list that doesn't have any particular order and is traditionally styled with bullets. If you do not want the bullets to appear then you can remove the styling by using the class .list-unstyled. You can also place all list items on a single line using the class .list-inline. Definition lists − In this type of list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal. Definition lists − In this type of list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. Glyphicons are icon fonts which you can use in your web projects. Glyphicons Halflings are not free and require licensing, however their creator has made them available for Bootstrap projects free of cost. To use the icons, simply use the following code just about anywhere in your code. Leave a space between the icon and text for proper padding. <span class = "glyphicon glyphicon-search"></span> The transition plugin provides simple transition effects such as Sliding or fading in modals. A modal is a child window that is layered over its parent window. Typically, the purpose is to display content from a separate source that can have some interaction without leaving the parent window. Child windows can provide information, interaction, or more. You can toggle the dropdown plugin's hidden content − Via data attributes − Add data-toggle = "dropdown" to a link or button to toggle a dropdown as shown below − Via data attributes − Add data-toggle = "dropdown" to a link or button to toggle a dropdown as shown below − <div class = "dropdown"> <a data-toggle = "dropdown" href = "#">Dropdown trigger</a> <ul class = "dropdown-menu" role = "menu" aria-labelledby = "dLabel"> ... </ul> </div> If you need to keep links intact (which is useful if the browser is not enabling JavaScript), use the data-target attribute instead of href="#" − If you need to keep links intact (which is useful if the browser is not enabling JavaScript), use the data-target attribute instead of href="#" − <div class = "dropdown"> <a id = "dLabel" role = "button" data-toggle = "dropdown" data-target = "#" href = "/page.html"> Dropdown <span class = "caret"></span> </a> <ul class = "dropdown-menu" role = "menu" aria-labelledby = "dLabel"> ... </ul> </div> Via JavaScript − To call the dropdown toggle via JavaScript, use the following method − Via JavaScript − To call the dropdown toggle via JavaScript, use the following method − $('.dropdown-toggle').dropdown() The Bootstrap carousel is a flexible, responsive way to add a slider to your site. In addition to being responsive, the content is flexible enough to allow images, iframes, videos, or just about any type of content that you might want. Button groups allow multiple buttons to be stacked together on a single line. This is useful when you want to place items like alignment buttons together. .btn-group class is used for a basic button group. Wrap a series of buttons with class .btn in .btn-group. .btn-toolbar helps to combine sets of <div class = "btn-group"> into a <div class = "btn-toolbar"> for more complex components. .btn-group-lg, .btn-group-sm, .btn-group-xs classes can be applied to button group instead of resizing each button. .btn-group-vertical class make a set of buttons appear vertically stacked rather than horizontally. Input groups are extended Form Controls. Using input groups you can easily prepend and append text or buttons to the text-based inputs. By adding prepended and appended content to an input field, you can add common elements to the user's input. For example, you can add the dollar symbol, the @ for a Twitter username, or anything else that might be common for your application interface. To prepend or append elements to a .form-control − Wrap it in a <div> with class .input-group Wrap it in a <div> with class .input-group As a next step, within that same <div> , place your extra content inside a <span> with class .input-group-addon. As a next step, within that same <div> , place your extra content inside a <span> with class .input-group-addon. Now place this <span> either before or after the <input> element. Now place this <span> either before or after the <input> element. To create a tabbed navigation menu − Start with a basic unordered list with the base class of .nav. Add class .nav-tabs. To create a pills navigation menu − Start with a basic unordered list with the base class of .nav. Add class .nav-pills. You can stack the pills vertically using the class .nav-stacked along with the classes: .nav, .nav-pills. The navbar is one of the prominent features of Bootstrap sites. Navbars are responsive 'meta' components that serve as navigation headers for your application or site. Navbars collapse in mobile views and become horizontal as the available viewport width increases. At its core, the navbar includes styling for site names and basic navigation. To create a default navbar − Add the classes .navbar, .navbar-default to the <nav> tag. Add the classes .navbar, .navbar-default to the <nav> tag. Add role = "navigation" to the above element, to help with accessibility. Add role = "navigation" to the above element, to help with accessibility. Add a header class .navbar-header to the <div> element. Include an <a> element with class navbar-brand. This will give the text a slightly larger size. Add a header class .navbar-header to the <div> element. Include an <a> element with class navbar-brand. This will give the text a slightly larger size. To add links to the navbar, simply add an unordered list with the classes of .nav, .navbar-nav. To add links to the navbar, simply add an unordered list with the classes of .nav, .navbar-nav. Breadcrumbs are a great way to show hierarchy-based information for a site. In the case of blogs, breadcrumbs can show the dates of publishing, categories, or tags. They indicate the current page's location within a navigational hierarchy. A breadcrumb in Bootstrap is simply an unordered list with a class of .breadcrumb. The separator is automatically added by CSS (bootstrap.min.css). .pagination class is uesed to add the pagination on a page. You can customize links by using .disabled for unclickable links and .active to indicate the current page. Bootstrap labels are great for offering counts, tips, or other markup for pages. Use class .label to display labels. Badges are similar to labels; the primary difference is that the corners are more rounded. Badges are mainly used to highlight new or unread items. To use badges just add <span class = "badge"> to links, Bootstrap navs, and more. As the name suggest this component can optionally increase the size of headings and add a lot of margin for landing page content. To use the Jumbotron − Create a container <div> with the class of .jumbotron. In addition to a larger <h1>, the font-weight is reduced to 200px. The page header is a nice little feature to add appropriate spacing around the headings on a page. This is particularly helpful on a web page where you may have several post titles and need a way to add distinction to each of them. To use a page header, wrap your heading in a <div> with a class of .page-header. To create thumbnails using Bootstrap − Add an <a> tag with the class of .thumbnail around an image. This adds four pixels of padding and a gray border. On hover, an animated glow outlines the image. it's possible to add any kind of HTML content like headings, paragraphs, or buttons into thumbnails. Follow the steps below − Change the <a> tag that has a class of .thumbnail to a <div>. Change the <a> tag that has a class of .thumbnail to a <div>. Inside of that <div>, you can add anything you need. As this is a <div>, we can use the default span-based naming convention for sizing. Inside of that <div>, you can add anything you need. As this is a <div>, we can use the default span-based naming convention for sizing. If you want to group multiple images, place them in an unordered list, and each list item will be floated to the left. If you want to group multiple images, place them in an unordered list, and each list item will be floated to the left. Bootstrap Alerts provide a way to style messages to the user. They provide contextual feedback messages for typical user actions. You can add an optional close icon to alert. You can add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger). To build a dismissal alert − Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger). Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger). Also add optional .alert-dismissable to the above <div> class. Also add optional .alert-dismissable to the above <div> class. Add a close button. Add a close button. Use the <button> element with the data-dismiss = "alert" data attribute. Use the <button> element with the data-dismiss = "alert" data attribute. To create a basic progress bar − Add a <div> with a class of .progress. Add a <div> with a class of .progress. Next, inside the above <div>, add an empty <div> with a class of .progress-bar. Next, inside the above <div>, add an empty <div> with a class of .progress-bar. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. To create a progress bar with different styles − Add a <div> with a class of .progress. Add a <div> with a class of .progress. Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger. Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. To create a striped progress bar − Add a <div> with a class of .progress and .progress-striped. Add a <div> with a class of .progress and .progress-striped. Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger. Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. To create an animated progress bar − Add a <div> with a class of .progress and .progress-striped. Also add class .active to .progress-striped. Add a <div> with a class of .progress and .progress-striped. Also add class .active to .progress-striped. Next, inside the above <div>, add an empty <div> with a class of .progress-bar. Next, inside the above <div>, add an empty <div> with a class of .progress-bar. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. You can even stack multiple progress bars. Place the multiple progress bars into the same .progress to stack them. These are abstract object styles for building various types of components (like blog comments, Tweets, etc.) that feature a left-aligned or right-aligned image alongside the textual content. The goal of the media object is to make the code for developing these blocks of information drastically shorter. The goal of media objects (light markup, easy extendability) is achieved by applying classes to some of the simple markup. This class allows to float a media object (images, video, and audio) to the left or right of a content block. If you are preparing a list where the items will be part of an unordered list, use a class. useful for comment threads or articles lists. Panel components are used when you want to put your DOM component in a box. To get a basic panel, just add class .panel to the <div> element. Also add class .panel-default to this element. here are two ways to add panel heading − Use .panel-heading class to easily add a heading container to your panel. Use .panel-heading class to easily add a heading container to your panel. Use any <h1>-<h6> with a .panel-title class to add a pre-styled heading. Use any <h1>-<h6> with a .panel-title class to add a pre-styled heading. You can add footers to panels, by wrapping buttons or secondary text in a <div> containing class .panel-footer. Use contextual state classes such as, panel-primary, panel-success, panel-info, panel-warning, panel-danger, to make a panel more meaningful to a particular context. Yes! To get a non-bordered table within a panel, use the class .table within the panel. Suppose there is a <div> containing .panel-body, we add an extra border to the top of the table for separation. If there is no <div> containing .panel-body, then the component moves from panel header to table without interruption. Yes! You can include list groups within any panel. Create a panel by adding class .panel to the <div> element. Also add class .panel-default to this element. Now within this panel include your list groups. A well is a container in <div> that causes the content to appear sunken or an inset effect on the page. To create a well, simply wrap the content that you would like to appear in the well with a <div> containing the class of .well. The Scrollspy (auto updating nav) plugin allows you to target sections of the page based on the scroll position. In its basic implementation, as you scroll, you can add .active classes to the navbar based on the scroll position. The affix plugin allows a <div> to become affixed to a location on the page. You can also toggle it's pinning on and off using this plugin. A common example of this are social icons. They will start in a location, but as the page hits a certain mark, the <div> will be locked in place and will stop scrolling with the rest of the page. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3783, "s": 3331, "text": "Dear readers, these BOOTSTRAP Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of BOOTSTRAP Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −" }, { "code": null, "e": 3935, "s": 3783, "text": "Bootstrap is a sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development. It uses HTML, CSS and Javascript." }, { "code": null, "e": 3962, "s": 3935, "text": "Bootstrap can be used as −" }, { "code": null, "e": 4111, "s": 3962, "text": "Mobile first approach − Since Bootstrap 3, the framework consists of Mobile first styles throughout the entire library instead of in separate files." }, { "code": null, "e": 4260, "s": 4111, "text": "Mobile first approach − Since Bootstrap 3, the framework consists of Mobile first styles throughout the entire library instead of in separate files." }, { "code": null, "e": 4321, "s": 4260, "text": "Browser Support − It is supported by all popular browsers.\n\n" }, { "code": null, "e": 4380, "s": 4321, "text": "Browser Support − It is supported by all popular browsers." }, { "code": null, "e": 4540, "s": 4380, "text": "Easy to get started − With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation." }, { "code": null, "e": 4700, "s": 4540, "text": "Easy to get started − With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation." }, { "code": null, "e": 4788, "s": 4700, "text": "Responsive design − Bootstrap's responsive CSS adjusts to Desktops,Tablets and Mobiles." }, { "code": null, "e": 4876, "s": 4788, "text": "Responsive design − Bootstrap's responsive CSS adjusts to Desktops,Tablets and Mobiles." }, { "code": null, "e": 4956, "s": 4876, "text": "Provides a clean and uniform solution for building an interface for developers." }, { "code": null, "e": 5036, "s": 4956, "text": "Provides a clean and uniform solution for building an interface for developers." }, { "code": null, "e": 5122, "s": 5036, "text": "It contains beautiful and functional built-in components which are easy to customize." }, { "code": null, "e": 5208, "s": 5122, "text": "It contains beautiful and functional built-in components which are easy to customize." }, { "code": null, "e": 5250, "s": 5208, "text": "It also provides web based customization." }, { "code": null, "e": 5292, "s": 5250, "text": "It also provides web based customization." }, { "code": null, "e": 5330, "s": 5292, "text": "And best of all it is an open source." }, { "code": null, "e": 5368, "s": 5330, "text": "And best of all it is an open source." }, { "code": null, "e": 5397, "s": 5368, "text": "Bootstrap package includes −" }, { "code": null, "e": 5561, "s": 5397, "text": "Scaffolding − Bootstrap provides a basic structure with Grid System, link styles, background. This is is covered in detail in the section Bootstrap Basic Structure" }, { "code": null, "e": 5725, "s": 5561, "text": "Scaffolding − Bootstrap provides a basic structure with Grid System, link styles, background. This is is covered in detail in the section Bootstrap Basic Structure" }, { "code": null, "e": 5945, "s": 5725, "text": "CSS − Bootstrap comes with feature of global CSS settings, fundamental HTML elements styled and enhanced with extensible classes, and an advanced grid system. This is covered in detail in the section Bootstrap with CSS." }, { "code": null, "e": 6165, "s": 5945, "text": "CSS − Bootstrap comes with feature of global CSS settings, fundamental HTML elements styled and enhanced with extensible classes, and an advanced grid system. This is covered in detail in the section Bootstrap with CSS." }, { "code": null, "e": 6376, "s": 6165, "text": "Components − Bootstrap contains over a dozen reusable components built to provide iconography, dropdowns, navigation, alerts, popovers, and much more. This is covered in detail in the section Layout Components." }, { "code": null, "e": 6587, "s": 6376, "text": "Components − Bootstrap contains over a dozen reusable components built to provide iconography, dropdowns, navigation, alerts, popovers, and much more. This is covered in detail in the section Layout Components." }, { "code": null, "e": 6772, "s": 6587, "text": "JavaScript Plugins − Bootstrap contains over a dozen custom jQuery plugins. You can easily include them all, or one by one. This is covered in details in the section Bootstrap Plugins." }, { "code": null, "e": 6957, "s": 6772, "text": "JavaScript Plugins − Bootstrap contains over a dozen custom jQuery plugins. You can easily include them all, or one by one. This is covered in details in the section Bootstrap Plugins." }, { "code": null, "e": 7076, "s": 6957, "text": "Customize − You can customize Bootstrap's components, LESS variables, and jQuery plugins to get your very own version." }, { "code": null, "e": 7195, "s": 7076, "text": "Customize − You can customize Bootstrap's components, LESS variables, and jQuery plugins to get your very own version." }, { "code": null, "e": 7299, "s": 7195, "text": "The Contextual classes allow you to change the background color of your table rows or individual cells." }, { "code": null, "e": 7307, "s": 7299, "text": ".active" }, { "code": null, "e": 7359, "s": 7307, "text": "Applies the hover color to a particular row or cell" }, { "code": null, "e": 7368, "s": 7359, "text": ".success" }, { "code": null, "e": 7410, "s": 7368, "text": "Indicates a successful or positive action" }, { "code": null, "e": 7419, "s": 7410, "text": ".warning" }, { "code": null, "e": 7465, "s": 7419, "text": "Indicates a warning that might need attention" }, { "code": null, "e": 7473, "s": 7465, "text": ".danger" }, { "code": null, "e": 7526, "s": 7473, "text": "Indicates a dangerous or potentially negative action" }, { "code": null, "e": 7796, "s": 7526, "text": "Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. It includes predefined classes for easy layout options, as well as powerful mixins for generating more semantic layouts." }, { "code": null, "e": 7888, "s": 7796, "text": "Media Queries in Bootstrap allow you to move, show and hide content based on viewport size." }, { "code": null, "e": 7937, "s": 7888, "text": "Following is basic structure of Bootstrap grid −" }, { "code": null, "e": 8147, "s": 7937, "text": "<div class = \"container\">\n <div class = \"row\">\n <div class = \"col-*-*\"></div>\n <div class = \"col-*-*\"></div> \n </div>\n \n <div class = \"row\">...</div>\n</div>\n<div class = \"container\">...." }, { "code": null, "e": 8377, "s": 8147, "text": "Offsets are a useful feature for more specialized layouts. They can be used to push columns over for more spacing, for example. The .col-xs = * classes don't support offsets, but they are easily replicated by using an empty cell." }, { "code": null, "e": 8518, "s": 8377, "text": "You can easily change the order of built-in grid columns with .col-md-push-* and .col-md-pull-* modifier classes where * range from 1 to 11." }, { "code": null, "e": 8734, "s": 8518, "text": "Bootstrap 3 allows to make the images responsive by adding a class .img-responsive to the <img> tag. This class applies max-width: 100%; and height: auto; to the image so that it scales nicely to the parent element." }, { "code": null, "e": 8816, "s": 8734, "text": "Bootstrap sets a basic global display (background), typography, and link styles −" }, { "code": null, "e": 8891, "s": 8816, "text": "Basic Global display − Sets background-color: #fff; on the <body> element." }, { "code": null, "e": 8966, "s": 8891, "text": "Basic Global display − Sets background-color: #fff; on the <body> element." }, { "code": null, "e": 9081, "s": 8966, "text": "Typography − Uses the @font-family-base, @font-size-base, and @line-height-base attributes as the typographic base" }, { "code": null, "e": 9196, "s": 9081, "text": "Typography − Uses the @font-family-base, @font-size-base, and @line-height-base attributes as the typographic base" }, { "code": null, "e": 9305, "s": 9196, "text": "Link styles − Sets the global link color via attribute @link-color and apply link underlines only on :hover." }, { "code": null, "e": 9414, "s": 9305, "text": "Link styles − Sets the global link color via attribute @link-color and apply link underlines only on :hover." }, { "code": null, "e": 9479, "s": 9414, "text": "Bootstrap uses Normalize to establish cross browser consistency." }, { "code": null, "e": 9656, "s": 9479, "text": "Normalize.css is a modern, HTML5-ready alternative to CSS resets. It is a small CSS file that provides better cross-browser consistency in the default styling of HTML elements." }, { "code": null, "e": 9791, "s": 9656, "text": "To add some emphasis to a paragraph, add class = \"lead\". This will give you larger font size, lighter weight, and a taller line height" }, { "code": null, "e": 9864, "s": 9791, "text": "Bootstrap supports ordered lists, unordered lists, and definition lists." }, { "code": null, "e": 9978, "s": 9864, "text": "Ordered lists − An ordered list is a list that falls in some sort of sequential order and is prefaced by numbers." }, { "code": null, "e": 10092, "s": 9978, "text": "Ordered lists − An ordered list is a list that falls in some sort of sequential order and is prefaced by numbers." }, { "code": null, "e": 10408, "s": 10092, "text": "Unordered lists − An unordered list is a list that doesn't have any particular order and is traditionally styled with bullets. If you do not want the bullets to appear then you can remove the styling by using the class .list-unstyled. You can also place all list items on a single line using the class .list-inline." }, { "code": null, "e": 10724, "s": 10408, "text": "Unordered lists − An unordered list is a list that doesn't have any particular order and is traditionally styled with bullets. If you do not want the bullets to appear then you can remove the styling by using the class .list-unstyled. You can also place all list items on a single line using the class .list-inline." }, { "code": null, "e": 11086, "s": 10724, "text": "Definition lists − In this type of list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal." }, { "code": null, "e": 11356, "s": 11086, "text": "Definition lists − In this type of list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>." }, { "code": null, "e": 11562, "s": 11356, "text": "Glyphicons are icon fonts which you can use in your web projects. Glyphicons Halflings are not free and require licensing, however their creator has made them available for Bootstrap projects free of cost." }, { "code": null, "e": 11704, "s": 11562, "text": "To use the icons, simply use the following code just about anywhere in your code. Leave a space between the icon and text for proper padding." }, { "code": null, "e": 11755, "s": 11704, "text": "<span class = \"glyphicon glyphicon-search\"></span>" }, { "code": null, "e": 11849, "s": 11755, "text": "The transition plugin provides simple transition effects such as Sliding or fading in modals." }, { "code": null, "e": 12110, "s": 11849, "text": "A modal is a child window that is layered over its parent window. Typically, the purpose is to display content from a separate source that can have some interaction without leaving the parent window. Child windows can provide information, interaction, or more." }, { "code": null, "e": 12164, "s": 12110, "text": "You can toggle the dropdown plugin's hidden content −" }, { "code": null, "e": 12273, "s": 12164, "text": "Via data attributes − Add data-toggle = \"dropdown\" to a link or button to toggle a dropdown as shown below −" }, { "code": null, "e": 12382, "s": 12273, "text": "Via data attributes − Add data-toggle = \"dropdown\" to a link or button to toggle a dropdown as shown below −" }, { "code": null, "e": 12567, "s": 12382, "text": "<div class = \"dropdown\">\n <a data-toggle = \"dropdown\" href = \"#\">Dropdown trigger</a>\n <ul class = \"dropdown-menu\" role = \"menu\" aria-labelledby = \"dLabel\">\n ...\n </ul>\n</div>" }, { "code": null, "e": 12713, "s": 12567, "text": "If you need to keep links intact (which is useful if the browser is not enabling JavaScript), use the data-target attribute instead of href=\"#\" −" }, { "code": null, "e": 12859, "s": 12713, "text": "If you need to keep links intact (which is useful if the browser is not enabling JavaScript), use the data-target attribute instead of href=\"#\" −" }, { "code": null, "e": 13155, "s": 12859, "text": "<div class = \"dropdown\">\n <a id = \"dLabel\" role = \"button\" data-toggle = \"dropdown\" data-target = \"#\" href = \"/page.html\">\n Dropdown \n \n <span class = \"caret\"></span>\n </a>\n \n <ul class = \"dropdown-menu\" role = \"menu\" aria-labelledby = \"dLabel\">\n ...\n </ul>\n\t\n</div>" }, { "code": null, "e": 13243, "s": 13155, "text": "Via JavaScript − To call the dropdown toggle via JavaScript, use the following method −" }, { "code": null, "e": 13331, "s": 13243, "text": "Via JavaScript − To call the dropdown toggle via JavaScript, use the following method −" }, { "code": null, "e": 13364, "s": 13331, "text": "$('.dropdown-toggle').dropdown()" }, { "code": null, "e": 13600, "s": 13364, "text": "The Bootstrap carousel is a flexible, responsive way to add a slider to your site. In addition to being responsive, the content is flexible enough to allow images, iframes, videos, or just about any type of content that you might want." }, { "code": null, "e": 13755, "s": 13600, "text": "Button groups allow multiple buttons to be stacked together on a single line. This is useful when you want to place items like alignment buttons together." }, { "code": null, "e": 13862, "s": 13755, "text": ".btn-group class is used for a basic button group. Wrap a series of buttons with class .btn in .btn-group." }, { "code": null, "e": 13990, "s": 13862, "text": ".btn-toolbar helps to combine sets of <div class = \"btn-group\"> into a <div class = \"btn-toolbar\"> for more complex components." }, { "code": null, "e": 14106, "s": 13990, "text": ".btn-group-lg, .btn-group-sm, .btn-group-xs classes can be applied to button group instead of resizing each button." }, { "code": null, "e": 14206, "s": 14106, "text": ".btn-group-vertical class make a set of buttons appear vertically stacked rather than horizontally." }, { "code": null, "e": 14343, "s": 14206, "text": "Input groups are extended Form Controls. Using input groups you can easily prepend and append text or buttons to the text-based inputs." }, { "code": null, "e": 14596, "s": 14343, "text": "By adding prepended and appended content to an input field, you can add common elements to the user's input. For example, you can add the dollar symbol, the @ for a Twitter username, or anything else that might be common for your application interface." }, { "code": null, "e": 14647, "s": 14596, "text": "To prepend or append elements to a .form-control −" }, { "code": null, "e": 14690, "s": 14647, "text": "Wrap it in a <div> with class .input-group" }, { "code": null, "e": 14733, "s": 14690, "text": "Wrap it in a <div> with class .input-group" }, { "code": null, "e": 14846, "s": 14733, "text": "As a next step, within that same <div> , place your extra content inside a <span> with class .input-group-addon." }, { "code": null, "e": 14959, "s": 14846, "text": "As a next step, within that same <div> , place your extra content inside a <span> with class .input-group-addon." }, { "code": null, "e": 15025, "s": 14959, "text": "Now place this <span> either before or after the <input> element." }, { "code": null, "e": 15091, "s": 15025, "text": "Now place this <span> either before or after the <input> element." }, { "code": null, "e": 15128, "s": 15091, "text": "To create a tabbed navigation menu −" }, { "code": null, "e": 15191, "s": 15128, "text": "Start with a basic unordered list with the base class of .nav." }, { "code": null, "e": 15212, "s": 15191, "text": "Add class .nav-tabs." }, { "code": null, "e": 15248, "s": 15212, "text": "To create a pills navigation menu −" }, { "code": null, "e": 15311, "s": 15248, "text": "Start with a basic unordered list with the base class of .nav." }, { "code": null, "e": 15333, "s": 15311, "text": "Add class .nav-pills." }, { "code": null, "e": 15439, "s": 15333, "text": "You can stack the pills vertically using the class .nav-stacked along with the classes: .nav, .nav-pills." }, { "code": null, "e": 15783, "s": 15439, "text": "The navbar is one of the prominent features of Bootstrap sites. Navbars are responsive 'meta' components that serve as navigation headers for your application or site. Navbars collapse in mobile views and become horizontal as the available viewport width increases. At its core, the navbar includes styling for site names and basic navigation." }, { "code": null, "e": 15812, "s": 15783, "text": "To create a default navbar −" }, { "code": null, "e": 15871, "s": 15812, "text": "Add the classes .navbar, .navbar-default to the <nav> tag." }, { "code": null, "e": 15930, "s": 15871, "text": "Add the classes .navbar, .navbar-default to the <nav> tag." }, { "code": null, "e": 16004, "s": 15930, "text": "Add role = \"navigation\" to the above element, to help with accessibility." }, { "code": null, "e": 16078, "s": 16004, "text": "Add role = \"navigation\" to the above element, to help with accessibility." }, { "code": null, "e": 16230, "s": 16078, "text": "Add a header class .navbar-header to the <div> element. Include an <a> element with class navbar-brand. This will give the text a slightly larger size." }, { "code": null, "e": 16382, "s": 16230, "text": "Add a header class .navbar-header to the <div> element. Include an <a> element with class navbar-brand. This will give the text a slightly larger size." }, { "code": null, "e": 16478, "s": 16382, "text": "To add links to the navbar, simply add an unordered list with the classes of .nav, .navbar-nav." }, { "code": null, "e": 16574, "s": 16478, "text": "To add links to the navbar, simply add an unordered list with the classes of .nav, .navbar-nav." }, { "code": null, "e": 16814, "s": 16574, "text": "Breadcrumbs are a great way to show hierarchy-based information for a site. In the case of blogs, breadcrumbs can show the dates of publishing, categories, or tags. They indicate the current page's location within a navigational hierarchy." }, { "code": null, "e": 16962, "s": 16814, "text": "A breadcrumb in Bootstrap is simply an unordered list with a class of .breadcrumb. The separator is automatically added by CSS (bootstrap.min.css)." }, { "code": null, "e": 17022, "s": 16962, "text": ".pagination class is uesed to add the pagination on a page." }, { "code": null, "e": 17129, "s": 17022, "text": "You can customize links by using .disabled for unclickable links and .active to indicate the current page." }, { "code": null, "e": 17246, "s": 17129, "text": "Bootstrap labels are great for offering counts, tips, or other markup for pages. Use class .label to display labels." }, { "code": null, "e": 17476, "s": 17246, "text": "Badges are similar to labels; the primary difference is that the corners are more rounded. Badges are mainly used to highlight new or unread items. To use badges just add <span class = \"badge\"> to links, Bootstrap navs, and more." }, { "code": null, "e": 17629, "s": 17476, "text": "As the name suggest this component can optionally increase the size of headings and add a lot of margin for landing page content. To use the Jumbotron −" }, { "code": null, "e": 17684, "s": 17629, "text": "Create a container <div> with the class of .jumbotron." }, { "code": null, "e": 17751, "s": 17684, "text": "In addition to a larger <h1>, the font-weight is reduced to 200px." }, { "code": null, "e": 18064, "s": 17751, "text": "The page header is a nice little feature to add appropriate spacing around the headings on a page. This is particularly helpful on a web page where you may have several post titles and need a way to add distinction to each of them. To use a page header, wrap your heading in a <div> with a class of .page-header." }, { "code": null, "e": 18103, "s": 18064, "text": "To create thumbnails using Bootstrap −" }, { "code": null, "e": 18164, "s": 18103, "text": "Add an <a> tag with the class of .thumbnail around an image." }, { "code": null, "e": 18216, "s": 18164, "text": "This adds four pixels of padding and a gray border." }, { "code": null, "e": 18263, "s": 18216, "text": "On hover, an animated glow outlines the image." }, { "code": null, "e": 18389, "s": 18263, "text": "it's possible to add any kind of HTML content like headings, paragraphs, or buttons into thumbnails. Follow the steps below −" }, { "code": null, "e": 18451, "s": 18389, "text": "Change the <a> tag that has a class of .thumbnail to a <div>." }, { "code": null, "e": 18513, "s": 18451, "text": "Change the <a> tag that has a class of .thumbnail to a <div>." }, { "code": null, "e": 18650, "s": 18513, "text": "Inside of that <div>, you can add anything you need. As this is a <div>, we can use the default span-based naming convention for sizing." }, { "code": null, "e": 18787, "s": 18650, "text": "Inside of that <div>, you can add anything you need. As this is a <div>, we can use the default span-based naming convention for sizing." }, { "code": null, "e": 18906, "s": 18787, "text": "If you want to group multiple images, place them in an unordered list, and each list item will be floated to the left." }, { "code": null, "e": 19025, "s": 18906, "text": "If you want to group multiple images, place them in an unordered list, and each list item will be floated to the left." }, { "code": null, "e": 19155, "s": 19025, "text": "Bootstrap Alerts provide a way to style messages to the user. They provide contextual feedback messages for typical user actions." }, { "code": null, "e": 19200, "s": 19155, "text": "You can add an optional close icon to alert." }, { "code": null, "e": 19390, "s": 19200, "text": "You can add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)." }, { "code": null, "e": 19419, "s": 19390, "text": "To build a dismissal alert −" }, { "code": null, "e": 19601, "s": 19419, "text": "Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)." }, { "code": null, "e": 19783, "s": 19601, "text": "Add a basic alert by creating a wrapper <div> and adding a class of .alert and one of the four contextual classes (e.g., .alert-success, .alert-info, .alert-warning, .alert-danger)." }, { "code": null, "e": 19846, "s": 19783, "text": "Also add optional .alert-dismissable to the above <div> class." }, { "code": null, "e": 19909, "s": 19846, "text": "Also add optional .alert-dismissable to the above <div> class." }, { "code": null, "e": 19929, "s": 19909, "text": "Add a close button." }, { "code": null, "e": 19949, "s": 19929, "text": "Add a close button." }, { "code": null, "e": 20022, "s": 19949, "text": "Use the <button> element with the data-dismiss = \"alert\" data attribute." }, { "code": null, "e": 20095, "s": 20022, "text": "Use the <button> element with the data-dismiss = \"alert\" data attribute." }, { "code": null, "e": 20128, "s": 20095, "text": "To create a basic progress bar −" }, { "code": null, "e": 20167, "s": 20128, "text": "Add a <div> with a class of .progress." }, { "code": null, "e": 20206, "s": 20167, "text": "Add a <div> with a class of .progress." }, { "code": null, "e": 20286, "s": 20206, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar." }, { "code": null, "e": 20366, "s": 20286, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar." }, { "code": null, "e": 20506, "s": 20366, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 20646, "s": 20506, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 20695, "s": 20646, "text": "To create a progress bar with different styles −" }, { "code": null, "e": 20734, "s": 20695, "text": "Add a <div> with a class of .progress." }, { "code": null, "e": 20773, "s": 20734, "text": "Add a <div> with a class of .progress." }, { "code": null, "e": 20926, "s": 20773, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger." }, { "code": null, "e": 21079, "s": 20926, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger." }, { "code": null, "e": 21219, "s": 21079, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 21359, "s": 21219, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 21394, "s": 21359, "text": "To create a striped progress bar −" }, { "code": null, "e": 21455, "s": 21394, "text": "Add a <div> with a class of .progress and .progress-striped." }, { "code": null, "e": 21516, "s": 21455, "text": "Add a <div> with a class of .progress and .progress-striped." }, { "code": null, "e": 21669, "s": 21516, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger." }, { "code": null, "e": 21822, "s": 21669, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger." }, { "code": null, "e": 21962, "s": 21822, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 22102, "s": 21962, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 22139, "s": 22102, "text": "To create an animated progress bar −" }, { "code": null, "e": 22245, "s": 22139, "text": "Add a <div> with a class of .progress and .progress-striped. Also add class .active to .progress-striped." }, { "code": null, "e": 22351, "s": 22245, "text": "Add a <div> with a class of .progress and .progress-striped. Also add class .active to .progress-striped." }, { "code": null, "e": 22431, "s": 22351, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar." }, { "code": null, "e": 22511, "s": 22431, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar." }, { "code": null, "e": 22651, "s": 22511, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 22791, "s": 22651, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 22906, "s": 22791, "text": "You can even stack multiple progress bars. Place the multiple progress bars into the same .progress to stack them." }, { "code": null, "e": 23210, "s": 22906, "text": "These are abstract object styles for building various types of components (like blog comments, Tweets, etc.) that feature a left-aligned or right-aligned image alongside the textual content. The goal of the media object is to make the code for developing these blocks of information drastically shorter." }, { "code": null, "e": 23333, "s": 23210, "text": "The goal of media objects (light markup, easy extendability) is achieved by applying classes to some of the simple markup." }, { "code": null, "e": 23443, "s": 23333, "text": "This class allows to float a media object (images, video, and audio) to the left or right of a content block." }, { "code": null, "e": 23581, "s": 23443, "text": "If you are preparing a list where the items will be part of an unordered list, use a class. useful for comment threads or articles lists." }, { "code": null, "e": 23770, "s": 23581, "text": "Panel components are used when you want to put your DOM component in a box. To get a basic panel, just add class .panel to the <div> element. Also add class .panel-default to this element." }, { "code": null, "e": 23811, "s": 23770, "text": "here are two ways to add panel heading −" }, { "code": null, "e": 23885, "s": 23811, "text": "Use .panel-heading class to easily add a heading container to your panel." }, { "code": null, "e": 23959, "s": 23885, "text": "Use .panel-heading class to easily add a heading container to your panel." }, { "code": null, "e": 24032, "s": 23959, "text": "Use any <h1>-<h6> with a .panel-title class to add a pre-styled heading." }, { "code": null, "e": 24105, "s": 24032, "text": "Use any <h1>-<h6> with a .panel-title class to add a pre-styled heading." }, { "code": null, "e": 24217, "s": 24105, "text": "You can add footers to panels, by wrapping buttons or secondary text in a <div> containing class .panel-footer." }, { "code": null, "e": 24383, "s": 24217, "text": "Use contextual state classes such as, panel-primary, panel-success, panel-info, panel-warning, panel-danger, to make a panel more meaningful to a particular context." }, { "code": null, "e": 24702, "s": 24383, "text": "Yes! To get a non-bordered table within a panel, use the class .table within the panel. Suppose there is a <div> containing .panel-body, we add an extra border to the top of the table for separation. If there is no <div> containing .panel-body, then the component moves from panel header to table without interruption." }, { "code": null, "e": 24908, "s": 24702, "text": "Yes! You can include list groups within any panel. Create a panel by adding class .panel to the <div> element. Also add class .panel-default to this element. Now within this panel include your list groups." }, { "code": null, "e": 25140, "s": 24908, "text": "A well is a container in <div> that causes the content to appear sunken or an inset effect on the page. To create a well, simply wrap the content that you would like to appear in the well with a <div> containing the class of .well." }, { "code": null, "e": 25369, "s": 25140, "text": "The Scrollspy (auto updating nav) plugin allows you to target sections of the page based on the scroll position. In its basic implementation, as you scroll, you can add .active classes to the navbar based on the scroll position." }, { "code": null, "e": 25705, "s": 25369, "text": "The affix plugin allows a <div> to become affixed to a location on the page. You can also toggle it's pinning on and off using this plugin. A common example of this are social icons. They will start in a location, but as the page hits a certain mark, the <div> will be locked in place and will stop scrolling with the rest of the page." }, { "code": null, "e": 25992, "s": 25705, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 26322, "s": 25992, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 26355, "s": 26322, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 26369, "s": 26355, "text": " Anadi Sharma" }, { "code": null, "e": 26404, "s": 26369, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 26421, "s": 26404, "text": " Frahaan Hussain" }, { "code": null, "e": 26458, "s": 26421, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 26486, "s": 26458, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 26519, "s": 26486, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 26531, "s": 26519, "text": " Azaz Patel" }, { "code": null, "e": 26566, "s": 26531, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 26583, "s": 26566, "text": " Muhammad Ismail" }, { "code": null, "e": 26616, "s": 26583, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 26636, "s": 26616, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 26643, "s": 26636, "text": " Print" }, { "code": null, "e": 26654, "s": 26643, "text": " Add Notes" } ]
How to convert a PDF to byte array in Java?
You can read data from a PDF file using the read() method of the FileInputStream class this method requires a byte array as a parameter. import java.io.File; import java.io.FileInputStream; import java.io.ByteArrayOutputStream; public class PdfToByteArray { public static void main(String args[]) throws Exception { File file = new File("sample.pdf"); FileInputStream fis = new FileInputStream(file); byte [] data = new byte[(int)file.length()]; fis.read(data); ByteArrayOutputStream bos = new ByteArrayOutputStream(); data = bos.toByteArray(); } }
[ { "code": null, "e": 1199, "s": 1062, "text": "You can read data from a PDF file using the read() method of the FileInputStream class this method requires a byte array as a parameter." }, { "code": null, "e": 1654, "s": 1199, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.ByteArrayOutputStream;\n\npublic class PdfToByteArray {\n public static void main(String args[]) throws Exception {\n File file = new File(\"sample.pdf\");\n FileInputStream fis = new FileInputStream(file);\n byte [] data = new byte[(int)file.length()];\n fis.read(data);\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n data = bos.toByteArray();\n }\n}" } ]
Enabling JavaScript in Browsers
All the modern browsers come with built-in support for JavaScript. Frequently, you may need to enable or disable this support manually. This chapter explains the procedure of enabling and disabling JavaScript support in your browsers: Internet Explorer, Firefox, chrome, and Opera. Here are simple steps to turn on or turn off JavaScript in your Internet Explorer − Follow Tools → Internet Options from the menu. Follow Tools → Internet Options from the menu. Select Security tab from the dialog box. Select Security tab from the dialog box. Click the Custom Level button. Click the Custom Level button. Scroll down till you find Scripting option. Scroll down till you find Scripting option. Select Enable radio button under Active scripting. Select Enable radio button under Active scripting. Finally click OK and come out Finally click OK and come out To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting. Here are the steps to turn on or turn off JavaScript in Firefox − Open a new tab → type about: config in the address bar. Open a new tab → type about: config in the address bar. Then you will find the warning dialog. Select I’ll be careful, I promise! Then you will find the warning dialog. Select I’ll be careful, I promise! Then you will find the list of configure options in the browser. Then you will find the list of configure options in the browser. In the search bar, type javascript.enabled. In the search bar, type javascript.enabled. There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle. There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle. If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it gets enabled upon clicking toggle. Here are the steps to turn on or turn off JavaScript in Chrome − Click the Chrome menu at the top right hand corner of your browser. Click the Chrome menu at the top right hand corner of your browser. Select Settings. Select Settings. Click Show advanced settings at the end of the page. Click Show advanced settings at the end of the page. Under the Privacy section, click the Content settings button. Under the Privacy section, click the Content settings button. In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to run JavaScript (recommended)". In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to run JavaScript (recommended)". Here are the steps to turn on or turn off JavaScript in Opera − Follow Tools → Preferences from the menu. Follow Tools → Preferences from the menu. Select Advanced option from the dialog box. Select Advanced option from the dialog box. Select Content from the listed items. Select Content from the listed items. Select Enable JavaScript checkbox. Select Enable JavaScript checkbox. Finally click OK and come out. Finally click OK and come out. To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox. If you have to do something important using JavaScript, then you can display a warning message to the user using <noscript> tags. You can add a noscript block immediately after the script block as follows − <html> <body> <script language = "javascript" type = "text/javascript"> <!-- document.write("Hello World!") //--> </script> <noscript> Sorry...JavaScript is needed to go ahead. </noscript> </body> </html> Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the message from </noscript> will be displayed on the screen. 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2748, "s": 2466, "text": "All the modern browsers come with built-in support for JavaScript. Frequently, you may need to enable or disable this support manually. This chapter explains the procedure of enabling and disabling JavaScript support in your browsers: Internet Explorer, Firefox, chrome, and Opera." }, { "code": null, "e": 2832, "s": 2748, "text": "Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −" }, { "code": null, "e": 2879, "s": 2832, "text": "Follow Tools → Internet Options from the menu." }, { "code": null, "e": 2926, "s": 2879, "text": "Follow Tools → Internet Options from the menu." }, { "code": null, "e": 2967, "s": 2926, "text": "Select Security tab from the dialog box." }, { "code": null, "e": 3008, "s": 2967, "text": "Select Security tab from the dialog box." }, { "code": null, "e": 3039, "s": 3008, "text": "Click the Custom Level button." }, { "code": null, "e": 3070, "s": 3039, "text": "Click the Custom Level button." }, { "code": null, "e": 3114, "s": 3070, "text": "Scroll down till you find Scripting option." }, { "code": null, "e": 3158, "s": 3114, "text": "Scroll down till you find Scripting option." }, { "code": null, "e": 3209, "s": 3158, "text": "Select Enable radio button under Active scripting." }, { "code": null, "e": 3260, "s": 3209, "text": "Select Enable radio button under Active scripting." }, { "code": null, "e": 3290, "s": 3260, "text": "Finally click OK and come out" }, { "code": null, "e": 3320, "s": 3290, "text": "Finally click OK and come out" }, { "code": null, "e": 3441, "s": 3320, "text": "To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting." }, { "code": null, "e": 3507, "s": 3441, "text": "Here are the steps to turn on or turn off JavaScript in Firefox −" }, { "code": null, "e": 3563, "s": 3507, "text": "Open a new tab → type about: config in the address bar." }, { "code": null, "e": 3619, "s": 3563, "text": "Open a new tab → type about: config in the address bar." }, { "code": null, "e": 3693, "s": 3619, "text": "Then you will find the warning dialog. Select I’ll be careful, I promise!" }, { "code": null, "e": 3767, "s": 3693, "text": "Then you will find the warning dialog. Select I’ll be careful, I promise!" }, { "code": null, "e": 3832, "s": 3767, "text": "Then you will find the list of configure options in the browser." }, { "code": null, "e": 3897, "s": 3832, "text": "Then you will find the list of configure options in the browser." }, { "code": null, "e": 3941, "s": 3897, "text": "In the search bar, type javascript.enabled." }, { "code": null, "e": 3985, "s": 3941, "text": "In the search bar, type javascript.enabled." }, { "code": null, "e": 4111, "s": 3985, "text": "There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle." }, { "code": null, "e": 4237, "s": 4111, "text": "There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle." }, { "code": null, "e": 4376, "s": 4237, "text": "If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it gets enabled upon clicking toggle." }, { "code": null, "e": 4441, "s": 4376, "text": "Here are the steps to turn on or turn off JavaScript in Chrome −" }, { "code": null, "e": 4509, "s": 4441, "text": "Click the Chrome menu at the top right hand corner of your browser." }, { "code": null, "e": 4577, "s": 4509, "text": "Click the Chrome menu at the top right hand corner of your browser." }, { "code": null, "e": 4594, "s": 4577, "text": "Select Settings." }, { "code": null, "e": 4611, "s": 4594, "text": "Select Settings." }, { "code": null, "e": 4664, "s": 4611, "text": "Click Show advanced settings at the end of the page." }, { "code": null, "e": 4717, "s": 4664, "text": "Click Show advanced settings at the end of the page." }, { "code": null, "e": 4779, "s": 4717, "text": "Under the Privacy section, click the Content settings button." }, { "code": null, "e": 4841, "s": 4779, "text": "Under the Privacy section, click the Content settings button." }, { "code": null, "e": 4973, "s": 4841, "text": "In the \"Javascript\" section, select \"Do not allow any site to run JavaScript\" or \"Allow all sites to run JavaScript (recommended)\"." }, { "code": null, "e": 5105, "s": 4973, "text": "In the \"Javascript\" section, select \"Do not allow any site to run JavaScript\" or \"Allow all sites to run JavaScript (recommended)\"." }, { "code": null, "e": 5169, "s": 5105, "text": "Here are the steps to turn on or turn off JavaScript in Opera −" }, { "code": null, "e": 5211, "s": 5169, "text": "Follow Tools → Preferences from the menu." }, { "code": null, "e": 5253, "s": 5211, "text": "Follow Tools → Preferences from the menu." }, { "code": null, "e": 5297, "s": 5253, "text": "Select Advanced option from the dialog box." }, { "code": null, "e": 5341, "s": 5297, "text": "Select Advanced option from the dialog box." }, { "code": null, "e": 5380, "s": 5341, "text": "Select Content from the listed items." }, { "code": null, "e": 5419, "s": 5380, "text": "Select Content from the listed items." }, { "code": null, "e": 5454, "s": 5419, "text": "Select Enable JavaScript checkbox." }, { "code": null, "e": 5489, "s": 5454, "text": "Select Enable JavaScript checkbox." }, { "code": null, "e": 5520, "s": 5489, "text": "Finally click OK and come out." }, { "code": null, "e": 5551, "s": 5520, "text": "Finally click OK and come out." }, { "code": null, "e": 5650, "s": 5551, "text": "To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox." }, { "code": null, "e": 5780, "s": 5650, "text": "If you have to do something important using JavaScript, then you can display a warning message to the user using <noscript> tags." }, { "code": null, "e": 5857, "s": 5780, "text": "You can add a noscript block immediately after the script block as follows −" }, { "code": null, "e": 6144, "s": 5857, "text": "<html>\n <body>\n <script language = \"javascript\" type = \"text/javascript\">\n <!--\n document.write(\"Hello World!\")\n //-->\n </script>\n \n <noscript>\n Sorry...JavaScript is needed to go ahead.\n </noscript> \n </body>\n</html>" }, { "code": null, "e": 6296, "s": 6144, "text": "Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the message from </noscript> will be displayed on the screen." }, { "code": null, "e": 6331, "s": 6296, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6345, "s": 6331, "text": " Anadi Sharma" }, { "code": null, "e": 6379, "s": 6345, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 6393, "s": 6379, "text": " Lets Kode It" }, { "code": null, "e": 6428, "s": 6393, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6445, "s": 6428, "text": " Frahaan Hussain" }, { "code": null, "e": 6480, "s": 6445, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6497, "s": 6480, "text": " Frahaan Hussain" }, { "code": null, "e": 6530, "s": 6497, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 6558, "s": 6530, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6592, "s": 6558, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 6620, "s": 6592, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6627, "s": 6620, "text": " Print" }, { "code": null, "e": 6638, "s": 6627, "text": " Add Notes" } ]
Using Update statement with TINYINT in MySQL?
Let us first create a table. We have set one of the columns with type TINYINT − mysql> create table DemoTable -> ( -> EmployeeId int, -> isMarried tinyint -> ); Query OK, 0 rows affected (6.84 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(101,true); Query OK, 1 row affected (1.94 sec) mysql> insert into DemoTable values(102,false); Query OK, 1 row affected (0.76 sec) mysql> insert into DemoTable values(103,true); Query OK, 1 row affected (1.14 sec) mysql> insert into DemoTable values(104,true); Query OK, 1 row affected (1.22 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +------------+----------+ | EmployeeId | isMarried| +------------+----------+ | 101 | 1 | | 102 | 0 | | 103 | 1 | | 104 | 1 | +------------+----------+ 4 rows in set (0.00 sec) Here is the query to implement UPDATE statement with TINYINT − mysql> update DemoTable -> set isMarried=false -> where EmployeeId=103; Query OK, 1 row affected (1.24 sec) Rows matched: 1 Changed: 1 Warnings: 0 Let us check the table records once again − mysql> select *from DemoTable; This will produce the following output − +------------+----------+ | EmployeeId | isMaried | +------------+----------+ | 101 | 1 | | 102 | 0 | | 103 | 0 | | 104 | 1 | +------------+----------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1142, "s": 1062, "text": "Let us first create a table. We have set one of the columns with type TINYINT −" }, { "code": null, "e": 1272, "s": 1142, "text": "mysql> create table DemoTable\n -> (\n -> EmployeeId int,\n -> isMarried tinyint\n -> );\nQuery OK, 0 rows affected (6.84 sec)" }, { "code": null, "e": 1328, "s": 1272, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1661, "s": 1328, "text": "mysql> insert into DemoTable values(101,true);\nQuery OK, 1 row affected (1.94 sec)\nmysql> insert into DemoTable values(102,false);\nQuery OK, 1 row affected (0.76 sec)\nmysql> insert into DemoTable values(103,true);\nQuery OK, 1 row affected (1.14 sec)\nmysql> insert into DemoTable values(104,true);\nQuery OK, 1 row affected (1.22 sec)" }, { "code": null, "e": 1721, "s": 1661, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1752, "s": 1721, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1793, "s": 1752, "text": "This will produce the following output −" }, { "code": null, "e": 2026, "s": 1793, "text": "+------------+----------+\n| EmployeeId | isMarried|\n+------------+----------+\n| 101 | 1 |\n| 102 | 0 |\n| 103 | 1 |\n| 104 | 1 |\n+------------+----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2089, "s": 2026, "text": "Here is the query to implement UPDATE statement with TINYINT −" }, { "code": null, "e": 2242, "s": 2089, "text": "mysql> update DemoTable\n -> set isMarried=false\n -> where EmployeeId=103;\nQuery OK, 1 row affected (1.24 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2286, "s": 2242, "text": "Let us check the table records once again −" }, { "code": null, "e": 2317, "s": 2286, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2358, "s": 2317, "text": "This will produce the following output −" }, { "code": null, "e": 2591, "s": 2358, "text": "+------------+----------+\n| EmployeeId | isMaried |\n+------------+----------+\n| 101 | 1 |\n| 102 | 0 |\n| 103 | 0 |\n| 104 | 1 |\n+------------+----------+\n4 rows in set (0.00 sec)" } ]
IDE | GeeksforGeeks | A computer science portal for geeks
Please enter your email address or userHandle. 1234567https://www.trybooking.com/events/landing?eid=857380https://zenodo.org/communities/-zh-917717-deified/https://zenodo.org/communities/-zh-917717-deified/about/https://zenodo.org/communities/zh-917717-deified-tw/about/https://tw-film-hd-quality.blogspot.com/2022/01/2021-deified-4k-1080p.htmlhttp://cpp.sh/5gexghttps://www.peeranswer.com/question/61d7e3fd5dde529f067064b5ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX https://ide.geeksforgeeks.org/BHOQ5q9SIV prog.c:1:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘:’ token
[ { "code": null, "e": 164, "s": 117, "text": "Please enter your email address or userHandle." }, { "code": null, "e": 1053, "s": 164, "text": "1234567https://www.trybooking.com/events/landing?eid=857380https://zenodo.org/communities/-zh-917717-deified/https://zenodo.org/communities/-zh-917717-deified/about/https://zenodo.org/communities/zh-917717-deified-tw/about/https://tw-film-hd-quality.blogspot.com/2022/01/2021-deified-4k-1080p.htmlhttp://cpp.sh/5gexghttps://www.peeranswer.com/question/61d7e3fd5dde529f067064b5ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" }, { "code": null, "e": 1094, "s": 1053, "text": "https://ide.geeksforgeeks.org/BHOQ5q9SIV" } ]
Check if the Hashtable contains a specific value in C#
To check if the Hashtable contains a specific value, the code is as follows − Live Demo using System; using System.Collections; public class Demo { public static void Main(){ Hashtable hash = new Hashtable(); hash.Add("1", "A"); hash.Add("2", "B"); hash.Add("3", "C"); hash.Add("4", "D"); hash.Add("5","E"); hash.Add("6", "F"); hash.Add("7", "G"); hash.Add("8","H"); hash.Add("9", "I"); hash.Add("10", "J"); Console.WriteLine("Hashtable Key and Value pairs..."); foreach(DictionaryEntry entry in hash){ Console.WriteLine("{0} and {1} ", entry.Key, entry.Value); } Console.WriteLine("Is Hashtable having fixed size? = "+hash.IsFixedSize); Console.WriteLine("If Hashtable read-only? = "+hash.IsReadOnly); Console.WriteLine("The Hashtable consists of the value? = "+hash.ContainsValue("H")); } } This will produce the following output − Hashtable Key and Value pairs... 10 and J 1 and A 2 and B 3 and C 4 and D 5 and E 6 and F 7 and G 8 and H 9 and I Is Hashtable having fixed size? = False If Hashtable read-only? = False The Hashtable consists of the value? = True Let us see another example − Live Demo using System; using System.Collections; public class Demo { public static void Main(){ Hashtable hash = new Hashtable(); hash.Add("One", "Katie"); hash.Add("Two", "John"); hash.Add("Three", "Barry"); hash.Add("Four", "Mark"); hash.Add("Five","Harry"); hash.Add("Six", "Nathan"); hash.Add("Seven", "Tom"); hash.Add("Eight","Andy"); hash.Add("Nine", "Illeana"); hash.Add("Ten", "Tim"); Console.WriteLine("Hashtable Key and Value pairs..."); foreach(DictionaryEntry entry in hash){ Console.WriteLine("{0} and {1} ", entry.Key, entry.Value); } Console.WriteLine("Is Hashtable having fixed size? = "+hash.IsFixedSize); Console.WriteLine("If Hashtable read-only? = "+hash.IsReadOnly); Console.WriteLine("The Hashtable consists of the key? = "+hash.ContainsKey("Seven")); Console.WriteLine("The Hashtable consists of the value? = "+hash.ContainsValue("Illeana")); } } This will produce the following output − Hashtable Key and Value pairs... One and Katie Ten and Tim Five and Harry Three and Barry Seven and Tom Two and John Four and Mark Eight and Andy Nine and Illeana Six and Nathan Is Hashtable having fixed size? = False If Hashtable read-only? = False The Hashtable consists of the key? = True The Hashtable consists of the value? = True
[ { "code": null, "e": 1140, "s": 1062, "text": "To check if the Hashtable contains a specific value, the code is as follows −" }, { "code": null, "e": 1151, "s": 1140, "text": " Live Demo" }, { "code": null, "e": 1973, "s": 1151, "text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main(){\n Hashtable hash = new Hashtable();\n hash.Add(\"1\", \"A\");\n hash.Add(\"2\", \"B\");\n hash.Add(\"3\", \"C\");\n hash.Add(\"4\", \"D\");\n hash.Add(\"5\",\"E\");\n hash.Add(\"6\", \"F\");\n hash.Add(\"7\", \"G\");\n hash.Add(\"8\",\"H\");\n hash.Add(\"9\", \"I\");\n hash.Add(\"10\", \"J\");\n Console.WriteLine(\"Hashtable Key and Value pairs...\");\n foreach(DictionaryEntry entry in hash){\n Console.WriteLine(\"{0} and {1} \", entry.Key, entry.Value);\n }\n Console.WriteLine(\"Is Hashtable having fixed size? = \"+hash.IsFixedSize);\n Console.WriteLine(\"If Hashtable read-only? = \"+hash.IsReadOnly);\n Console.WriteLine(\"The Hashtable consists of the value? = \"+hash.ContainsValue(\"H\"));\n }\n}" }, { "code": null, "e": 2014, "s": 1973, "text": "This will produce the following output −" }, { "code": null, "e": 2244, "s": 2014, "text": "Hashtable Key and Value pairs...\n10 and J\n1 and A\n2 and B\n3 and C\n4 and D\n5 and E\n6 and F\n7 and G\n8 and H\n9 and I\nIs Hashtable having fixed size? = False If Hashtable read-only? = False The Hashtable consists of the value? = True" }, { "code": null, "e": 2273, "s": 2244, "text": "Let us see another example −" }, { "code": null, "e": 2284, "s": 2273, "text": " Live Demo" }, { "code": null, "e": 3265, "s": 2284, "text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main(){\n Hashtable hash = new Hashtable();\n hash.Add(\"One\", \"Katie\");\n hash.Add(\"Two\", \"John\");\n hash.Add(\"Three\", \"Barry\");\n hash.Add(\"Four\", \"Mark\");\n hash.Add(\"Five\",\"Harry\");\n hash.Add(\"Six\", \"Nathan\");\n hash.Add(\"Seven\", \"Tom\");\n hash.Add(\"Eight\",\"Andy\");\n hash.Add(\"Nine\", \"Illeana\");\n hash.Add(\"Ten\", \"Tim\");\n Console.WriteLine(\"Hashtable Key and Value pairs...\");\n foreach(DictionaryEntry entry in hash){\n Console.WriteLine(\"{0} and {1} \", entry.Key, entry.Value);\n }\n Console.WriteLine(\"Is Hashtable having fixed size? = \"+hash.IsFixedSize);\n Console.WriteLine(\"If Hashtable read-only? = \"+hash.IsReadOnly);\n Console.WriteLine(\"The Hashtable consists of the key? = \"+hash.ContainsKey(\"Seven\"));\n Console.WriteLine(\"The Hashtable consists of the value? = \"+hash.ContainsValue(\"Illeana\"));\n }\n}" }, { "code": null, "e": 3306, "s": 3265, "text": "This will produce the following output −" }, { "code": null, "e": 3642, "s": 3306, "text": "Hashtable Key and Value pairs...\nOne and Katie\nTen and Tim\nFive and Harry\nThree and Barry\nSeven and Tom\nTwo and John\nFour and Mark\nEight and Andy\nNine and Illeana\nSix and Nathan\nIs Hashtable having fixed size? = False If Hashtable read-only? = False\nThe Hashtable consists of the key? = True\nThe Hashtable consists of the value? = True" } ]
Golang program that uses structs as map keys - GeeksforGeeks
10 May, 2020 A map in Golang is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. Syntax: map[Key_Type]Value_Type{} Example: var sample map[string]int Here the sample is a map that has a string as key and int type as the value. In maps, most of the data types can be used as a key like int, string, float64, rune, etc. Maps also allow structs to be used as keys. These structs should be compared with each other. A structure or struct in Golang is a user-defined type that allows to combine fields of different types into a single type. Example of a struct: type Student struct { name string rollno int class string city string } Let’s see how to implement a struct in a map: Example 1: // Golang program to show how to// use structs as map keyspackage main // importing required packagesimport "fmt" //declaring a structtype Address struct { Name string city string Pincode int} func main() { // Creating struct instances a2 := Address{Name: "Ram", city: "Delhi", Pincode: 2400} a1 := Address{"Pam", "Dehradun", 2200} a3 := Address{Name: "Sam", city: "Lucknow", Pincode: 1070} // Declaring a map var mp map[Address]int // Checking if the map is empty or not if mp == nil { fmt.Println("True") } else { fmt.Println("False") } // Declaring and initialising // using map literals sample := map[Address]int{a1: 1, a2: 2, a3: 3} fmt.Println(sample)} Output: True map[{Pam Dehradun 2200}:1 {Ram Delhi 2400}:2 {Sam Lucknow 1070}:3] Iterating over a map: You can also run a loop to access and operate each map key individually. Example 2: // Golang program to show how to// use structs as map keyspackage main // importing required packagesimport "fmt" // declaring a structtype Address struct { Name string city string Pincode int} func main() { // Creating struct instances a1 := Address{"Pam", "Mumbai", 2200} a2 := Address{Name: "Ram", city: "Delhi", Pincode: 2400} a3 := Address{Name: "Sam", city: "Lucknow", Pincode: 1070} // Declaring and initialising using map literals sample := map[Address]int{a1: 1, a2: 2, a3: 3} for str, val := range sample { fmt.Println(str, val) } // You can also access a struct // field while using a loop for str := range sample { fmt.Println(str.Name) }} Output: {Ram Delhi 2400} 2 {Sam Lucknow 1070} 3 {Pam Mumbai 2200} 1 Pam Ram Sam Adding key: value pairs in the map: Adding key:value pair in a map is done using the given syntax: map_name[struct_instance]=value If a key-value pair already exists in the map it will just update the old pair with the new. Example 3: // Adding key:value pair in a mappackage main // importing required packagesimport "fmt" // declaring a structtype Student struct { Name string rollno int course string} func main() { // Creating struct instances a1 := Student{"Asha", 1, "CSE"} a2 := Student{"Aishwarya", 1, "ECE"} a3 := Student{"Priya", 2, "MECH"} // Declaring and initialising // using map literals mp := map[Student]int{a1: 1, a2: 2} fmt.Println("Original map was", mp) mp[a3] = 3 mp[Student{"Ram", 3, "CSE"}] = 4 // Values have their zero values // Here initial value was 0 after // incrementing it became 1 mp[Student{"Tina", 44, "EEE"}]++ fmt.Println("After adding key:value "+ "pairs to the map, Updated map is:", mp)} Output: Original map was map[{Aishwarya 1 ECE}:2 {Asha 1 CSE}:1]After adding key:value pairs to the map, Updated map is: map[{Aishwarya 1 ECE}:2 {Asha 1 CSE}:1 {Priya 2 MECH}:3 {Ram 3 CSE}:4 {Tina 44 EEE}:1] Deleting a struct key from the map: You can delete a struct key from the map using the delete() function. It is an inbuilt function and does not return any value and does not do anything if the key does not present in the given map. The syntax for the same is as follows: delete(map_name, struct_key) Example 4: // Deleting key: value pair in a mappackage main // importing required packagesimport "fmt" // declaring a structtype Student struct { Name string rollno int course string} func main() { // Creating struct instances a1 := Student{"Asha", 1, "CSE"} a2 := Student{"Aishwarya", 1, "ECE"} a3 := Student{"Priya", 2, "MECH"} a4 := Student{"Ram", 3, "CSE"} // Declaring and initialising using map literals mp := map[Student]int{a1: 1, a2: 2, a3: 3, a4: 4} delete(mp, a4) fmt.Println("The remaining map after deletion:") for str, i := range mp { fmt.Println(str, "=", i) } } Output: The remaining map after deletion: {Asha 1 CSE} = 1 {Aishwarya 1 ECE} = 2 {Priya 2 MECH} = 3 Checking the existence of a key: value pair: You can check whether a struct is present in the map or not. Given below is the syntax to check the existence of a struct_key: value pair in the map: // This gives the value and check result// If the check result is True, it means the key is present// If the check result is False, it means the key is missing and in that case value takes a zero valuevalue, check_variable_name:= map_name[key] or // Without value using the blank identifier// It will only give check result_, check_variable_name:= map_name[key] Example 6: // Golang program to check if a// struct key is presentpackage main // importing required packagesimport "fmt" // declaring a structtype Student struct { Name string rollno int course string} func main() { // Creating struct instances a1 := Student{"Asha", 1, "CSE"} a2 := Student{"Aishwarya", 1, "ECE"} a3 := Student{"Priya", 2, "MECH"} a4 := Student{"Ram", 3, "CSE"} // Declaring and initialising // using map literals mp := map[Student]string{a1: "First", a2: "Second", a3: "Third", a4: "Fourth"} value, check := mp[a4] fmt.Println("Is the key present:", check) fmt.Println("Value of the key:", value) _, check2 := mp[a2] fmt.Println("Is the key present:", check2) } Output: Is the key present: true Value of the key: Fourth Is the key present: true Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments strings.Replace() Function in Golang With Examples Time Formatting in Golang fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? How to convert a string in lower case in Golang? Different Ways to Find the Type of Variable in Golang Inheritance in GoLang How to compare times in Golang? Interfaces in Golang How to Trim a String in Golang?
[ { "code": null, "e": 23901, "s": 23873, "text": "\n10 May, 2020" }, { "code": null, "e": 24087, "s": 23901, "text": "A map in Golang is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys." }, { "code": null, "e": 24095, "s": 24087, "text": "Syntax:" }, { "code": null, "e": 24121, "s": 24095, "text": "map[Key_Type]Value_Type{}" }, { "code": null, "e": 24156, "s": 24121, "text": "Example: var sample map[string]int" }, { "code": null, "e": 24233, "s": 24156, "text": "Here the sample is a map that has a string as key and int type as the value." }, { "code": null, "e": 24542, "s": 24233, "text": "In maps, most of the data types can be used as a key like int, string, float64, rune, etc. Maps also allow structs to be used as keys. These structs should be compared with each other. A structure or struct in Golang is a user-defined type that allows to combine fields of different types into a single type." }, { "code": null, "e": 24563, "s": 24542, "text": "Example of a struct:" }, { "code": null, "e": 24661, "s": 24563, "text": "type Student struct {\n name string \n rollno int\n class string\n city string\n}\n" }, { "code": null, "e": 24707, "s": 24661, "text": "Let’s see how to implement a struct in a map:" }, { "code": null, "e": 24718, "s": 24707, "text": "Example 1:" }, { "code": "// Golang program to show how to// use structs as map keyspackage main // importing required packagesimport \"fmt\" //declaring a structtype Address struct { Name string city string Pincode int} func main() { // Creating struct instances a2 := Address{Name: \"Ram\", city: \"Delhi\", Pincode: 2400} a1 := Address{\"Pam\", \"Dehradun\", 2200} a3 := Address{Name: \"Sam\", city: \"Lucknow\", Pincode: 1070} // Declaring a map var mp map[Address]int // Checking if the map is empty or not if mp == nil { fmt.Println(\"True\") } else { fmt.Println(\"False\") } // Declaring and initialising // using map literals sample := map[Address]int{a1: 1, a2: 2, a3: 3} fmt.Println(sample)}", "e": 25461, "s": 24718, "text": null }, { "code": null, "e": 25469, "s": 25461, "text": "Output:" }, { "code": null, "e": 25542, "s": 25469, "text": "True\nmap[{Pam Dehradun 2200}:1 {Ram Delhi 2400}:2 {Sam Lucknow 1070}:3]\n" }, { "code": null, "e": 25637, "s": 25542, "text": "Iterating over a map: You can also run a loop to access and operate each map key individually." }, { "code": null, "e": 25648, "s": 25637, "text": "Example 2:" }, { "code": "// Golang program to show how to// use structs as map keyspackage main // importing required packagesimport \"fmt\" // declaring a structtype Address struct { Name string city string Pincode int} func main() { // Creating struct instances a1 := Address{\"Pam\", \"Mumbai\", 2200} a2 := Address{Name: \"Ram\", city: \"Delhi\", Pincode: 2400} a3 := Address{Name: \"Sam\", city: \"Lucknow\", Pincode: 1070} // Declaring and initialising using map literals sample := map[Address]int{a1: 1, a2: 2, a3: 3} for str, val := range sample { fmt.Println(str, val) } // You can also access a struct // field while using a loop for str := range sample { fmt.Println(str.Name) }}", "e": 26372, "s": 25648, "text": null }, { "code": null, "e": 26380, "s": 26372, "text": "Output:" }, { "code": null, "e": 26453, "s": 26380, "text": "{Ram Delhi 2400} 2\n{Sam Lucknow 1070} 3\n{Pam Mumbai 2200} 1\nPam\nRam\nSam\n" }, { "code": null, "e": 26552, "s": 26453, "text": "Adding key: value pairs in the map: Adding key:value pair in a map is done using the given syntax:" }, { "code": null, "e": 26585, "s": 26552, "text": "map_name[struct_instance]=value " }, { "code": null, "e": 26678, "s": 26585, "text": "If a key-value pair already exists in the map it will just update the old pair with the new." }, { "code": null, "e": 26689, "s": 26678, "text": "Example 3:" }, { "code": "// Adding key:value pair in a mappackage main // importing required packagesimport \"fmt\" // declaring a structtype Student struct { Name string rollno int course string} func main() { // Creating struct instances a1 := Student{\"Asha\", 1, \"CSE\"} a2 := Student{\"Aishwarya\", 1, \"ECE\"} a3 := Student{\"Priya\", 2, \"MECH\"} // Declaring and initialising // using map literals mp := map[Student]int{a1: 1, a2: 2} fmt.Println(\"Original map was\", mp) mp[a3] = 3 mp[Student{\"Ram\", 3, \"CSE\"}] = 4 // Values have their zero values // Here initial value was 0 after // incrementing it became 1 mp[Student{\"Tina\", 44, \"EEE\"}]++ fmt.Println(\"After adding key:value \"+ \"pairs to the map, Updated map is:\", mp)}", "e": 27454, "s": 26689, "text": null }, { "code": null, "e": 27462, "s": 27454, "text": "Output:" }, { "code": null, "e": 27662, "s": 27462, "text": "Original map was map[{Aishwarya 1 ECE}:2 {Asha 1 CSE}:1]After adding key:value pairs to the map, Updated map is: map[{Aishwarya 1 ECE}:2 {Asha 1 CSE}:1 {Priya 2 MECH}:3 {Ram 3 CSE}:4 {Tina 44 EEE}:1]" }, { "code": null, "e": 27934, "s": 27662, "text": "Deleting a struct key from the map: You can delete a struct key from the map using the delete() function. It is an inbuilt function and does not return any value and does not do anything if the key does not present in the given map. The syntax for the same is as follows:" }, { "code": null, "e": 27963, "s": 27934, "text": "delete(map_name, struct_key)" }, { "code": null, "e": 27974, "s": 27963, "text": "Example 4:" }, { "code": "// Deleting key: value pair in a mappackage main // importing required packagesimport \"fmt\" // declaring a structtype Student struct { Name string rollno int course string} func main() { // Creating struct instances a1 := Student{\"Asha\", 1, \"CSE\"} a2 := Student{\"Aishwarya\", 1, \"ECE\"} a3 := Student{\"Priya\", 2, \"MECH\"} a4 := Student{\"Ram\", 3, \"CSE\"} // Declaring and initialising using map literals mp := map[Student]int{a1: 1, a2: 2, a3: 3, a4: 4} delete(mp, a4) fmt.Println(\"The remaining map after deletion:\") for str, i := range mp { fmt.Println(str, \"=\", i) } }", "e": 28600, "s": 27974, "text": null }, { "code": null, "e": 28608, "s": 28600, "text": "Output:" }, { "code": null, "e": 28701, "s": 28608, "text": "The remaining map after deletion:\n{Asha 1 CSE} = 1\n{Aishwarya 1 ECE} = 2\n{Priya 2 MECH} = 3\n" }, { "code": null, "e": 28896, "s": 28701, "text": "Checking the existence of a key: value pair: You can check whether a struct is present in the map or not. Given below is the syntax to check the existence of a struct_key: value pair in the map:" }, { "code": null, "e": 29140, "s": 28896, "text": "// This gives the value and check result// If the check result is True, it means the key is present// If the check result is False, it means the key is missing and in that case value takes a zero valuevalue, check_variable_name:= map_name[key]" }, { "code": null, "e": 29143, "s": 29140, "text": "or" }, { "code": null, "e": 29258, "s": 29143, "text": "// Without value using the blank identifier// It will only give check result_, check_variable_name:= map_name[key]" }, { "code": null, "e": 29269, "s": 29258, "text": "Example 6:" }, { "code": "// Golang program to check if a// struct key is presentpackage main // importing required packagesimport \"fmt\" // declaring a structtype Student struct { Name string rollno int course string} func main() { // Creating struct instances a1 := Student{\"Asha\", 1, \"CSE\"} a2 := Student{\"Aishwarya\", 1, \"ECE\"} a3 := Student{\"Priya\", 2, \"MECH\"} a4 := Student{\"Ram\", 3, \"CSE\"} // Declaring and initialising // using map literals mp := map[Student]string{a1: \"First\", a2: \"Second\", a3: \"Third\", a4: \"Fourth\"} value, check := mp[a4] fmt.Println(\"Is the key present:\", check) fmt.Println(\"Value of the key:\", value) _, check2 := mp[a2] fmt.Println(\"Is the key present:\", check2) }", "e": 30004, "s": 29269, "text": null }, { "code": null, "e": 30012, "s": 30004, "text": "Output:" }, { "code": null, "e": 30088, "s": 30012, "text": "Is the key present: true\nValue of the key: Fourth\nIs the key present: true\n" }, { "code": null, "e": 30103, "s": 30088, "text": "Golang-Program" }, { "code": null, "e": 30110, "s": 30103, "text": "Picked" }, { "code": null, "e": 30122, "s": 30110, "text": "Go Language" }, { "code": null, "e": 30220, "s": 30122, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30229, "s": 30220, "text": "Comments" }, { "code": null, "e": 30242, "s": 30229, "text": "Old Comments" }, { "code": null, "e": 30293, "s": 30242, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 30319, "s": 30293, "text": "Time Formatting in Golang" }, { "code": null, "e": 30366, "s": 30319, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 30399, "s": 30366, "text": "How to Split a String in Golang?" }, { "code": null, "e": 30448, "s": 30399, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 30502, "s": 30448, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 30524, "s": 30502, "text": "Inheritance in GoLang" }, { "code": null, "e": 30556, "s": 30524, "text": "How to compare times in Golang?" }, { "code": null, "e": 30577, "s": 30556, "text": "Interfaces in Golang" } ]
Biopython - Sequence File Formats - GeeksforGeeks
22 Oct, 2020 Bio.SeqIO module of Biopython provides a wide range of simple uniform interfaces to input and output the desired file formats. This file formats can only deal with the sequences as a SeqRecord object. Lowercase strings are used while specifying the file format. The same formats are also supported by the Bio.AlignIO module. The list of the file formats is given below : Below implementation explains about how to parse two of the most popular sequence file formats, i.e. FASTA and GenBank. It is the most basic file format to store sequence data. Originally FASTA was a software package created during early evolution of Bioinformatics for sequence alignment of proteins and DNA, mostly used for searching similarities. Below is a simple example of parsing FASTA file format: Example: To get the input file used click here. Python3 # Import librariesfrom Bio.SeqIO import parse # file path/locationfile = open('is_orchid.fasta') # Parsing the FASTA filefor record in parse(file, "fasta"): print(record.id) Output: Richer sequence format for genes which includes various annotations. Parsing the GenBank format is as simple as changing the format option in Biopython parse method. Below is a simple example of parsing GenBank file format: Example: To get the input file used click here. Python3 # Import librariesfrom Bio import SeqIOfrom Bio.SeqIO import parse # Parsing Sequenceseq_record = next(parse(open('is_orchid.gbk'), 'genbank')) # Sequence IDprint("\nSequence ID :", seq_record.id) # Sequence Nameprint("\nSequence Name :", seq_record.name) # Sequenceprint("\nSequence :", seq_record.seq) # Sequence Descriptionprint("\nSequence ID :", seq_record.description) # Sequence Annotationsprint("\nSequence Annotations :", seq_record.annotations) Output: Python-BioPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n22 Oct, 2020" }, { "code": null, "e": 24663, "s": 24292, "text": "Bio.SeqIO module of Biopython provides a wide range of simple uniform interfaces to input and output the desired file formats. This file formats can only deal with the sequences as a SeqRecord object. Lowercase strings are used while specifying the file format. The same formats are also supported by the Bio.AlignIO module. The list of the file formats is given below :" }, { "code": null, "e": 24783, "s": 24663, "text": "Below implementation explains about how to parse two of the most popular sequence file formats, i.e. FASTA and GenBank." }, { "code": null, "e": 25069, "s": 24783, "text": "It is the most basic file format to store sequence data. Originally FASTA was a software package created during early evolution of Bioinformatics for sequence alignment of proteins and DNA, mostly used for searching similarities. Below is a simple example of parsing FASTA file format:" }, { "code": null, "e": 25078, "s": 25069, "text": "Example:" }, { "code": null, "e": 25117, "s": 25078, "text": "To get the input file used click here." }, { "code": null, "e": 25125, "s": 25117, "text": "Python3" }, { "code": "# Import librariesfrom Bio.SeqIO import parse # file path/locationfile = open('is_orchid.fasta') # Parsing the FASTA filefor record in parse(file, \"fasta\"): print(record.id)", "e": 25306, "s": 25125, "text": null }, { "code": null, "e": 25314, "s": 25306, "text": "Output:" }, { "code": null, "e": 25538, "s": 25314, "text": "Richer sequence format for genes which includes various annotations. Parsing the GenBank format is as simple as changing the format option in Biopython parse method. Below is a simple example of parsing GenBank file format:" }, { "code": null, "e": 25547, "s": 25538, "text": "Example:" }, { "code": null, "e": 25586, "s": 25547, "text": "To get the input file used click here." }, { "code": null, "e": 25594, "s": 25586, "text": "Python3" }, { "code": "# Import librariesfrom Bio import SeqIOfrom Bio.SeqIO import parse # Parsing Sequenceseq_record = next(parse(open('is_orchid.gbk'), 'genbank')) # Sequence IDprint(\"\\nSequence ID :\", seq_record.id) # Sequence Nameprint(\"\\nSequence Name :\", seq_record.name) # Sequenceprint(\"\\nSequence :\", seq_record.seq) # Sequence Descriptionprint(\"\\nSequence ID :\", seq_record.description) # Sequence Annotationsprint(\"\\nSequence Annotations :\", seq_record.annotations)", "e": 26056, "s": 25594, "text": null }, { "code": null, "e": 26064, "s": 26056, "text": "Output:" }, { "code": null, "e": 26081, "s": 26064, "text": "Python-BioPython" }, { "code": null, "e": 26088, "s": 26081, "text": "Python" }, { "code": null, "e": 26186, "s": 26088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26218, "s": 26186, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26274, "s": 26218, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26316, "s": 26274, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26358, "s": 26316, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26380, "s": 26358, "text": "Defaultdict in Python" }, { "code": null, "e": 26419, "s": 26380, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26450, "s": 26419, "text": "Python | os.path.join() method" }, { "code": null, "e": 26505, "s": 26450, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26534, "s": 26505, "text": "Create a directory in Python" } ]
Fine-Tuning the Algorithmic Strategy Using a Particle Swarm Optimization | by Sergey Malchevskiy | Towards Data Science
Today we talk about a technique that allows searching a good set of parameters for a limited time, also we will consider one trading strategy as a bonus. Have a good read! Gentle Introduction to Particle Swarm OptimizationTrading Strategy AlgorithmLet’s Code It!ExperimentFurther ImprovementsSummary Gentle Introduction to Particle Swarm Optimization Trading Strategy Algorithm Let’s Code It! Experiment Further Improvements Summary The main goal of the optimization for our task is to define the sub-optimal parameters of the trading strategy that maximize or minimize the objective function (usually it uses the minimization). The objective function could be simple like the return of the algorithm that we should maximize or the drawdown that we should minimize. In this experiment, we use a more sophisticated and complex function that tries to compose a few factors. I describe this function in one next part. A lot of researchers described the PSO approach in their works. My task is to collect in one place the main algorithmic scheme and principles behind the method. Also, I give links to get more information and dive into it depending on your interests. From Wikipedia: In computational science, particle swarm optimization (PSO) is a computational method that optimizes a problem by iteratively trying to improve a candidate solution with regard to a given measure of quality. It solves a problem by having a population of candidate solutions, here dubbed particles, and moving these particles around in the search-space according to simple mathematical formulae over the particle’s position and velocity. Each particle’s movement is influenced by its local best known position, but is also guided toward the best known positions in the search-space, which are updated as better positions are found by other particles. This is expected to move the swarm toward the best solutions. PSO is a metaheuristic as it makes few or no assumptions about the problem being optimized and can search very large spaces of candidate solutions. However, metaheuristics such as PSO do not guarantee an optimal solution is ever found. Also, PSO does not use the gradient of the problem being optimized, which means PSO does not require that the optimization problem be differentiable as is required by classic optimization methods such as gradient descent and quasi-newton methods. It sounds great, we can use the objective function that could be non-differentiable. This is a very convenient point because our function usually is complex and consists of different parts. Also, the algorithm can work with no assumptions in large spaces. The scheme of the algorithm looks like this The math description you can get in this source article. The algorithm is iterative that tries to converge step by step, this picture shows the animation of the process. Generally, the pseudo-code independent of a programming language with basic operations is the next. The good explanation of the algorithm with hands-on implementation by Tarlan Ahadli you can find here. Also, you can watch this great video If you want to dive into different modifications of this approach, I would recommend this, this, and this. The main idea of the strategy is to try to catch the moment when price breakthrough the trend in a reverse direction. After that, we open the position and try to make the money. The trend line is based on two pivot points. For the upside trend line (green lower line), the next down pivot point is higher than the previous one, and the next up pivot point is lower than the previous one for the downside trend (red upper line). A down pivot point is the low price of the bar with the lowest price around several bars (2 bars minimum for each side), an up pivot point has a reversal logic. The enter in the long position occurs when price intersects the downside trend line and closes upper than this line. A reversal logic for the short position. The exit point of the position is a take profit (green label) or stop loss (red label). In this case, the fixed levels are used for TP and SL. The alternative event for the exit is occurring of the reversal pattern. After we got the description of the strategy we can start writing the code. As a backtesting system is used Backtrader. This is an open-source feature-rich framework for the backtesting and trading. Yes, in Python. This project I separated into 5 files, where 4 files consisting of a class, and one file is a script that contains the main experiment and runs the others. The code of main.py contains the logic of the experiment here. This script contains three important parts: objective function definition, running the PSO on train dataset, and running the strategy with the best parameters on a few datasets for the evaluation (train, test, full). As a PSO library is used pyswarm. In this script, we create the object of BacktestTrendBreakerPL class. This class is responsible for data reading, running the strategy, calculating the metrics, and results in visualization. The code of BacktestTrendBreakerPL.py class is The output_settings object that we passed from the main script is responsible for verbosity. The interesting part is stability_of_timeseries function. This function is a heart of research that impact on optimization process directly. The main goal is a quality estimation of the trading strategy with the passed set of the parameters. Mathematically, it determines as an R-squared of a linear fit to the cumulative log returns. The sign of the function depending on profitability. When the value is close to 1.0 it means the great result and line is growing up with small drawdowns, the bad result when this value is close to -1.0. This script contains FinamHLOC class from DataFeedFormat.py, where located the code for the data structure of source CSV-file. The next interesting thing is an object of TrendBreakerPL class from TrendBreakerPLStrategy.py. The main functionality of this class is position management. The first one is to enter the position when the signal occurs. The second one is to close the position when the price is reached the Take profit or Stop loss, or the reversal pattern has occurred. The additional functionality is printing the order status. This script uses the signals based on indicator data that defined in PivotPointLine class in PivotPointLineIndicator.py. The basic functionality is calculating the pivot points, trend lines and signal when close price intersects and closing upper\lower trend line depending on the direction. I think this code is not optimal, it takes a lot of time in a general pipeline of the backtesting. When I was developing this solution I met with problems with the latest version of Pyfolio library that I use for visualization and some metrics. I fixed a few lines of code how it was suggested here. Also, I changed a few lines of code in the plotting.py of Pyfolio like this because I need a DataFrame object The experiment is conducted on Sberbank data. Sberbank is the largest bank in Russia, Eastern, and Central Europe. I downloaded hourly data from Finam. The period starts from 6th of January 2014 to 21th of February 2020. Then this period was divided on train period (6th of January 2014 — 29th of December 2017); test period (3th of January 2018 — 21th of February 2020). The set of optimization parameters includes: pivot_window_len - window length (the number of bars) by each side for determing the pivot point. Range is [2, 120];history_bars_as_multiple_pwl - history window length as a multiplication factor for pivot_window_len. Range is [10, 100];fixed_tp - value for the fixed level of take profit. Range is [0.01, 0.2];fixed_sl_as_multiple_tp - value for the fixed level of stop loss as a multiplication factor for fixed_tp. Range is [0.1, 1.5].I used a multiplication factor instead of a simple value because it is easier to control and logically suitable in an optimization process. E.g., take profit and stop loss will be closer to each other. The experiment was launched on 40 iterations with swarm size is 20. The other paramters of swarm optimization are default (omega=0.5, phip=0.5, phig=0.5). The best set of parameters on train data is: pivot_window_len = 9history_bars_as_multiple_pwl = 49fixed_tp = 0.06034064 (6.034%)fixed_sl_as_multiple_tp = 0.14778282. It means stop loss is 0.892%As a result the objective function is -0.9712, then stability is 0.9712. This is very good result because it's very close to 1.0. Let’s look at the capital curve of our experiment It looks pretty good. On the train period, we have the same level of return with lower drawdown and more stable curve. The algo curve on the test period demonstrates strong positive dynamics, much better than the benchmark (buy & hold). The final curve strongly better than the benchmark. The metrics of the algorithm are Train:Return: 106.45%Stability: 0.971Maximum Drawdown: 14.37%Test:Return: 63.17%Stability: 0.7934Maximum Drawdown: 11.58%Full Period:Return: 296.3%Stability: 0.9738Maximum Drawdown: 14.37% The next picture demonstrates more effectively the drawdown periods The good point is that the drawdown level is stable during the train and test periods. Even on the test period is lower. Let’s look at Top-5 drawdowns Train: Net drawdown in % Peak date Valley date Recovery date Duration1 14.365 2017-06-15 2017-12-27 NaT NaN2 13.2355 2015-05-20 2015-07-07 2015-11-17 1303 12.8431 2014-10-06 2014-12-02 2014-12-16 514 10.1103 2015-01-27 2015-02-12 2015-03-16 355 8.6618 2014-04-01 2014-04-22 2014-06-16 55Test: Net drawdown in % Peak date Valley date Recovery date Duration1 11.5807 2019-02-08 2019-03-18 2019-04-23 522 10.8415 2019-07-23 2019-12-02 NaT NaN3 9.28844 2018-05-03 2018-06-25 2018-07-27 624 8.26704 2018-10-30 2018-12-03 2019-01-18 595 7.07621 2018-04-03 2018-04-09 2018-04-09 5Full Period: Net drawdown in % Peak date Valley date Recovery date Duration1 14.365 2017-06-15 2017-12-27 2018-03-21 2002 13.2355 2015-05-20 2015-07-07 2015-11-17 1303 12.8431 2014-10-06 2014-12-02 2014-12-16 514 12.1112 2019-02-08 2019-03-18 2019-05-03 605 11.5791 2019-07-23 2019-12-02 NaT NaN As we see, the highest drawdown was on the train period. The next picture demonstrates the hourly returns. On the whole, the number of outliers is small. Let’s look at the quantile plot of the returns for the different timeframes The shapes are similar, this is a good indication. The monthly returns distribution is next, the mean is strongly higher than 0.0 and negative returns are compacted without outliers. The final summary of the experiment is that the PSO allows getting the pretty good quality for the limited time, and the sub-optimal parameters are working on the out-of-sample dataset with the same level of profitability and drawdown. I would recommend researching the next moments to get better results: Experiment with the PSO parameters. Also, you can try to use another approach for optimization instead of PSO, then you can compare each other.Volatility-based Take profit and Stop loss.Trailing stop instead of Take profit and Stop loss.Limited time in a position.Any pattern trigger to close a position (e.g., intersecting trend line while in a position).Different timeframes (e.g. 15 minutes or 1 day).Apply the Walk-Forward Analysis to research the stability and robustness of the result. Experiment with the PSO parameters. Also, you can try to use another approach for optimization instead of PSO, then you can compare each other. Volatility-based Take profit and Stop loss. Trailing stop instead of Take profit and Stop loss. Limited time in a position. Any pattern trigger to close a position (e.g., intersecting trend line while in a position). Different timeframes (e.g. 15 minutes or 1 day). Apply the Walk-Forward Analysis to research the stability and robustness of the result. 8. Create a portfolio based on several uncorrelated assets. 9. Add the stress-testing mechanism for strategy robustness verification. 10. Add more metrics for the cumulative Walk-Forward Period and portfolio curve, such as alpha, beta, Sortino ratio, and so on. These improvements requires a lot of computations, you should think about: Refactor the PivotPointLineIndicator.py because this is very slow implementation, or prepare the pre-calculated cache of the indicator for particular timeframes and parameters.Try to use GPU where it is possible.Use a multiprocessing mode in portfolio generating.Check other implementation of the PSO approach. Some libraries can do the computations on GPU and CPU multiprocessing mode. Refactor the PivotPointLineIndicator.py because this is very slow implementation, or prepare the pre-calculated cache of the indicator for particular timeframes and parameters. Try to use GPU where it is possible. Use a multiprocessing mode in portfolio generating. Check other implementation of the PSO approach. Some libraries can do the computations on GPU and CPU multiprocessing mode. Described the quick introduction to particle swarm optimization approach and its application to algorithmic trading.Formalized the patterns and logic of the trading strategy.Demonstrated the code with a description that you can get on GitHub. Also, pay the attention to packages_env_list.txt for installing the right versions of packages.Trained and tested the approach, and evaluated the experiment.Suggested further improvements. Described the quick introduction to particle swarm optimization approach and its application to algorithmic trading. Formalized the patterns and logic of the trading strategy. Demonstrated the code with a description that you can get on GitHub. Also, pay the attention to packages_env_list.txt for installing the right versions of packages. Trained and tested the approach, and evaluated the experiment. Suggested further improvements. In this case, the suggested approach presented a great result with a good performance and moderate drawdowns for this kind of strategy. All steps and the experiment are reproducible, you can get the code and play with your data. As a data source, you can try this service by Antoine Vulcain for free. Have a good investing! Best regards, Sergey Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 344, "s": 172, "text": "Today we talk about a technique that allows searching a good set of parameters for a limited time, also we will consider one trading strategy as a bonus. Have a good read!" }, { "code": null, "e": 472, "s": 344, "text": "Gentle Introduction to Particle Swarm OptimizationTrading Strategy AlgorithmLet’s Code It!ExperimentFurther ImprovementsSummary" }, { "code": null, "e": 523, "s": 472, "text": "Gentle Introduction to Particle Swarm Optimization" }, { "code": null, "e": 550, "s": 523, "text": "Trading Strategy Algorithm" }, { "code": null, "e": 565, "s": 550, "text": "Let’s Code It!" }, { "code": null, "e": 576, "s": 565, "text": "Experiment" }, { "code": null, "e": 597, "s": 576, "text": "Further Improvements" }, { "code": null, "e": 605, "s": 597, "text": "Summary" }, { "code": null, "e": 801, "s": 605, "text": "The main goal of the optimization for our task is to define the sub-optimal parameters of the trading strategy that maximize or minimize the objective function (usually it uses the minimization)." }, { "code": null, "e": 1087, "s": 801, "text": "The objective function could be simple like the return of the algorithm that we should maximize or the drawdown that we should minimize. In this experiment, we use a more sophisticated and complex function that tries to compose a few factors. I describe this function in one next part." }, { "code": null, "e": 1337, "s": 1087, "text": "A lot of researchers described the PSO approach in their works. My task is to collect in one place the main algorithmic scheme and principles behind the method. Also, I give links to get more information and dive into it depending on your interests." }, { "code": null, "e": 1353, "s": 1337, "text": "From Wikipedia:" }, { "code": null, "e": 2065, "s": 1353, "text": "In computational science, particle swarm optimization (PSO) is a computational method that optimizes a problem by iteratively trying to improve a candidate solution with regard to a given measure of quality. It solves a problem by having a population of candidate solutions, here dubbed particles, and moving these particles around in the search-space according to simple mathematical formulae over the particle’s position and velocity. Each particle’s movement is influenced by its local best known position, but is also guided toward the best known positions in the search-space, which are updated as better positions are found by other particles. This is expected to move the swarm toward the best solutions." }, { "code": null, "e": 2548, "s": 2065, "text": "PSO is a metaheuristic as it makes few or no assumptions about the problem being optimized and can search very large spaces of candidate solutions. However, metaheuristics such as PSO do not guarantee an optimal solution is ever found. Also, PSO does not use the gradient of the problem being optimized, which means PSO does not require that the optimization problem be differentiable as is required by classic optimization methods such as gradient descent and quasi-newton methods." }, { "code": null, "e": 2848, "s": 2548, "text": "It sounds great, we can use the objective function that could be non-differentiable. This is a very convenient point because our function usually is complex and consists of different parts. Also, the algorithm can work with no assumptions in large spaces. The scheme of the algorithm looks like this" }, { "code": null, "e": 3018, "s": 2848, "text": "The math description you can get in this source article. The algorithm is iterative that tries to converge step by step, this picture shows the animation of the process." }, { "code": null, "e": 3118, "s": 3018, "text": "Generally, the pseudo-code independent of a programming language with basic operations is the next." }, { "code": null, "e": 3258, "s": 3118, "text": "The good explanation of the algorithm with hands-on implementation by Tarlan Ahadli you can find here. Also, you can watch this great video" }, { "code": null, "e": 3365, "s": 3258, "text": "If you want to dive into different modifications of this approach, I would recommend this, this, and this." }, { "code": null, "e": 3543, "s": 3365, "text": "The main idea of the strategy is to try to catch the moment when price breakthrough the trend in a reverse direction. After that, we open the position and try to make the money." }, { "code": null, "e": 3793, "s": 3543, "text": "The trend line is based on two pivot points. For the upside trend line (green lower line), the next down pivot point is higher than the previous one, and the next up pivot point is lower than the previous one for the downside trend (red upper line)." }, { "code": null, "e": 3954, "s": 3793, "text": "A down pivot point is the low price of the bar with the lowest price around several bars (2 bars minimum for each side), an up pivot point has a reversal logic." }, { "code": null, "e": 4112, "s": 3954, "text": "The enter in the long position occurs when price intersects the downside trend line and closes upper than this line. A reversal logic for the short position." }, { "code": null, "e": 4328, "s": 4112, "text": "The exit point of the position is a take profit (green label) or stop loss (red label). In this case, the fixed levels are used for TP and SL. The alternative event for the exit is occurring of the reversal pattern." }, { "code": null, "e": 4543, "s": 4328, "text": "After we got the description of the strategy we can start writing the code. As a backtesting system is used Backtrader. This is an open-source feature-rich framework for the backtesting and trading. Yes, in Python." }, { "code": null, "e": 4699, "s": 4543, "text": "This project I separated into 5 files, where 4 files consisting of a class, and one file is a script that contains the main experiment and runs the others." }, { "code": null, "e": 4762, "s": 4699, "text": "The code of main.py contains the logic of the experiment here." }, { "code": null, "e": 5013, "s": 4762, "text": "This script contains three important parts: objective function definition, running the PSO on train dataset, and running the strategy with the best parameters on a few datasets for the evaluation (train, test, full). As a PSO library is used pyswarm." }, { "code": null, "e": 5251, "s": 5013, "text": "In this script, we create the object of BacktestTrendBreakerPL class. This class is responsible for data reading, running the strategy, calculating the metrics, and results in visualization. The code of BacktestTrendBreakerPL.py class is" }, { "code": null, "e": 5344, "s": 5251, "text": "The output_settings object that we passed from the main script is responsible for verbosity." }, { "code": null, "e": 5883, "s": 5344, "text": "The interesting part is stability_of_timeseries function. This function is a heart of research that impact on optimization process directly. The main goal is a quality estimation of the trading strategy with the passed set of the parameters. Mathematically, it determines as an R-squared of a linear fit to the cumulative log returns. The sign of the function depending on profitability. When the value is close to 1.0 it means the great result and line is growing up with small drawdowns, the bad result when this value is close to -1.0." }, { "code": null, "e": 6010, "s": 5883, "text": "This script contains FinamHLOC class from DataFeedFormat.py, where located the code for the data structure of source CSV-file." }, { "code": null, "e": 6106, "s": 6010, "text": "The next interesting thing is an object of TrendBreakerPL class from TrendBreakerPLStrategy.py." }, { "code": null, "e": 6364, "s": 6106, "text": "The main functionality of this class is position management. The first one is to enter the position when the signal occurs. The second one is to close the position when the price is reached the Take profit or Stop loss, or the reversal pattern has occurred." }, { "code": null, "e": 6423, "s": 6364, "text": "The additional functionality is printing the order status." }, { "code": null, "e": 6715, "s": 6423, "text": "This script uses the signals based on indicator data that defined in PivotPointLine class in PivotPointLineIndicator.py. The basic functionality is calculating the pivot points, trend lines and signal when close price intersects and closing upper\\lower trend line depending on the direction." }, { "code": null, "e": 6814, "s": 6715, "text": "I think this code is not optimal, it takes a lot of time in a general pipeline of the backtesting." }, { "code": null, "e": 7015, "s": 6814, "text": "When I was developing this solution I met with problems with the latest version of Pyfolio library that I use for visualization and some metrics. I fixed a few lines of code how it was suggested here." }, { "code": null, "e": 7125, "s": 7015, "text": "Also, I changed a few lines of code in the plotting.py of Pyfolio like this because I need a DataFrame object" }, { "code": null, "e": 7240, "s": 7125, "text": "The experiment is conducted on Sberbank data. Sberbank is the largest bank in Russia, Eastern, and Central Europe." }, { "code": null, "e": 7378, "s": 7240, "text": "I downloaded hourly data from Finam. The period starts from 6th of January 2014 to 21th of February 2020. Then this period was divided on" }, { "code": null, "e": 7438, "s": 7378, "text": "train period (6th of January 2014 — 29th of December 2017);" }, { "code": null, "e": 7497, "s": 7438, "text": "test period (3th of January 2018 — 21th of February 2020)." }, { "code": null, "e": 7542, "s": 7497, "text": "The set of optimization parameters includes:" }, { "code": null, "e": 8181, "s": 7542, "text": "pivot_window_len - window length (the number of bars) by each side for determing the pivot point. Range is [2, 120];history_bars_as_multiple_pwl - history window length as a multiplication factor for pivot_window_len. Range is [10, 100];fixed_tp - value for the fixed level of take profit. Range is [0.01, 0.2];fixed_sl_as_multiple_tp - value for the fixed level of stop loss as a multiplication factor for fixed_tp. Range is [0.1, 1.5].I used a multiplication factor instead of a simple value because it is easier to control and logically suitable in an optimization process. E.g., take profit and stop loss will be closer to each other." }, { "code": null, "e": 8381, "s": 8181, "text": "The experiment was launched on 40 iterations with swarm size is 20. The other paramters of swarm optimization are default (omega=0.5, phip=0.5, phig=0.5). The best set of parameters on train data is:" }, { "code": null, "e": 8661, "s": 8381, "text": "pivot_window_len = 9history_bars_as_multiple_pwl = 49fixed_tp = 0.06034064 (6.034%)fixed_sl_as_multiple_tp = 0.14778282. It means stop loss is 0.892%As a result the objective function is -0.9712, then stability is 0.9712. This is very good result because it's very close to 1.0." }, { "code": null, "e": 8711, "s": 8661, "text": "Let’s look at the capital curve of our experiment" }, { "code": null, "e": 9033, "s": 8711, "text": "It looks pretty good. On the train period, we have the same level of return with lower drawdown and more stable curve. The algo curve on the test period demonstrates strong positive dynamics, much better than the benchmark (buy & hold). The final curve strongly better than the benchmark. The metrics of the algorithm are" }, { "code": null, "e": 9222, "s": 9033, "text": "Train:Return: 106.45%Stability: 0.971Maximum Drawdown: 14.37%Test:Return: 63.17%Stability: 0.7934Maximum Drawdown: 11.58%Full Period:Return: 296.3%Stability: 0.9738Maximum Drawdown: 14.37%" }, { "code": null, "e": 9290, "s": 9222, "text": "The next picture demonstrates more effectively the drawdown periods" }, { "code": null, "e": 9441, "s": 9290, "text": "The good point is that the drawdown level is stable during the train and test periods. Even on the test period is lower. Let’s look at Top-5 drawdowns" }, { "code": null, "e": 10635, "s": 9441, "text": "Train: Net drawdown in % Peak date Valley date Recovery date Duration1 14.365 2017-06-15 2017-12-27 NaT NaN2 13.2355 2015-05-20 2015-07-07 2015-11-17 1303 12.8431 2014-10-06 2014-12-02 2014-12-16 514 10.1103 2015-01-27 2015-02-12 2015-03-16 355 8.6618 2014-04-01 2014-04-22 2014-06-16 55Test: Net drawdown in % Peak date Valley date Recovery date Duration1 11.5807 2019-02-08 2019-03-18 2019-04-23 522 10.8415 2019-07-23 2019-12-02 NaT NaN3 9.28844 2018-05-03 2018-06-25 2018-07-27 624 8.26704 2018-10-30 2018-12-03 2019-01-18 595 7.07621 2018-04-03 2018-04-09 2018-04-09 5Full Period: Net drawdown in % Peak date Valley date Recovery date Duration1 14.365 2017-06-15 2017-12-27 2018-03-21 2002 13.2355 2015-05-20 2015-07-07 2015-11-17 1303 12.8431 2014-10-06 2014-12-02 2014-12-16 514 12.1112 2019-02-08 2019-03-18 2019-05-03 605 11.5791 2019-07-23 2019-12-02 NaT NaN" }, { "code": null, "e": 10692, "s": 10635, "text": "As we see, the highest drawdown was on the train period." }, { "code": null, "e": 10789, "s": 10692, "text": "The next picture demonstrates the hourly returns. On the whole, the number of outliers is small." }, { "code": null, "e": 10865, "s": 10789, "text": "Let’s look at the quantile plot of the returns for the different timeframes" }, { "code": null, "e": 11048, "s": 10865, "text": "The shapes are similar, this is a good indication. The monthly returns distribution is next, the mean is strongly higher than 0.0 and negative returns are compacted without outliers." }, { "code": null, "e": 11284, "s": 11048, "text": "The final summary of the experiment is that the PSO allows getting the pretty good quality for the limited time, and the sub-optimal parameters are working on the out-of-sample dataset with the same level of profitability and drawdown." }, { "code": null, "e": 11354, "s": 11284, "text": "I would recommend researching the next moments to get better results:" }, { "code": null, "e": 11846, "s": 11354, "text": "Experiment with the PSO parameters. Also, you can try to use another approach for optimization instead of PSO, then you can compare each other.Volatility-based Take profit and Stop loss.Trailing stop instead of Take profit and Stop loss.Limited time in a position.Any pattern trigger to close a position (e.g., intersecting trend line while in a position).Different timeframes (e.g. 15 minutes or 1 day).Apply the Walk-Forward Analysis to research the stability and robustness of the result." }, { "code": null, "e": 11990, "s": 11846, "text": "Experiment with the PSO parameters. Also, you can try to use another approach for optimization instead of PSO, then you can compare each other." }, { "code": null, "e": 12034, "s": 11990, "text": "Volatility-based Take profit and Stop loss." }, { "code": null, "e": 12086, "s": 12034, "text": "Trailing stop instead of Take profit and Stop loss." }, { "code": null, "e": 12114, "s": 12086, "text": "Limited time in a position." }, { "code": null, "e": 12207, "s": 12114, "text": "Any pattern trigger to close a position (e.g., intersecting trend line while in a position)." }, { "code": null, "e": 12256, "s": 12207, "text": "Different timeframes (e.g. 15 minutes or 1 day)." }, { "code": null, "e": 12344, "s": 12256, "text": "Apply the Walk-Forward Analysis to research the stability and robustness of the result." }, { "code": null, "e": 12404, "s": 12344, "text": "8. Create a portfolio based on several uncorrelated assets." }, { "code": null, "e": 12478, "s": 12404, "text": "9. Add the stress-testing mechanism for strategy robustness verification." }, { "code": null, "e": 12606, "s": 12478, "text": "10. Add more metrics for the cumulative Walk-Forward Period and portfolio curve, such as alpha, beta, Sortino ratio, and so on." }, { "code": null, "e": 12681, "s": 12606, "text": "These improvements requires a lot of computations, you should think about:" }, { "code": null, "e": 13068, "s": 12681, "text": "Refactor the PivotPointLineIndicator.py because this is very slow implementation, or prepare the pre-calculated cache of the indicator for particular timeframes and parameters.Try to use GPU where it is possible.Use a multiprocessing mode in portfolio generating.Check other implementation of the PSO approach. Some libraries can do the computations on GPU and CPU multiprocessing mode." }, { "code": null, "e": 13245, "s": 13068, "text": "Refactor the PivotPointLineIndicator.py because this is very slow implementation, or prepare the pre-calculated cache of the indicator for particular timeframes and parameters." }, { "code": null, "e": 13282, "s": 13245, "text": "Try to use GPU where it is possible." }, { "code": null, "e": 13334, "s": 13282, "text": "Use a multiprocessing mode in portfolio generating." }, { "code": null, "e": 13458, "s": 13334, "text": "Check other implementation of the PSO approach. Some libraries can do the computations on GPU and CPU multiprocessing mode." }, { "code": null, "e": 13890, "s": 13458, "text": "Described the quick introduction to particle swarm optimization approach and its application to algorithmic trading.Formalized the patterns and logic of the trading strategy.Demonstrated the code with a description that you can get on GitHub. Also, pay the attention to packages_env_list.txt for installing the right versions of packages.Trained and tested the approach, and evaluated the experiment.Suggested further improvements." }, { "code": null, "e": 14007, "s": 13890, "text": "Described the quick introduction to particle swarm optimization approach and its application to algorithmic trading." }, { "code": null, "e": 14066, "s": 14007, "text": "Formalized the patterns and logic of the trading strategy." }, { "code": null, "e": 14231, "s": 14066, "text": "Demonstrated the code with a description that you can get on GitHub. Also, pay the attention to packages_env_list.txt for installing the right versions of packages." }, { "code": null, "e": 14294, "s": 14231, "text": "Trained and tested the approach, and evaluated the experiment." }, { "code": null, "e": 14326, "s": 14294, "text": "Suggested further improvements." }, { "code": null, "e": 14462, "s": 14326, "text": "In this case, the suggested approach presented a great result with a good performance and moderate drawdowns for this kind of strategy." }, { "code": null, "e": 14627, "s": 14462, "text": "All steps and the experiment are reproducible, you can get the code and play with your data. As a data source, you can try this service by Antoine Vulcain for free." }, { "code": null, "e": 14650, "s": 14627, "text": "Have a good investing!" }, { "code": null, "e": 14664, "s": 14650, "text": "Best regards," }, { "code": null, "e": 14671, "s": 14664, "text": "Sergey" } ]
What is the difference between an inner and an outer join in SQL? | by Kate Marie Lewis | Towards Data Science
Joins in SQL are used to combine the contents of different tables. You can specify how you want the data from tables to be joined in many ways, one of which is the type of join. There are four main types of joins: inner join, full outer join, left outer join and right outer join. The major difference between inner and outer joins is that inner joins result in the intersection of two tables, whereas outer joins result in the union of two tables. In this story, I will describe the difference between an inner join, full outer join, left outer join and right outer join. I will then go through an example using characters from Harry Potter to demonstrate the differences. A Venn diagram is a helpful way to visualise the difference between an inner join and an outer join. Inner joins result in the overlapping part of the Venn diagram of two datasets, whilst for full outer joins the outer parts of the Venn diagram will also be returned. For an inner join, only the rows that both tables have in common are returned. However, for a full outer join, all rows from both tables are returned. Left and right outer joins are useful if you want to get all the values from one table but only the rows that match that table from the other table. So in a left outer join, all rows from the left table will be returned plus the rows that the right table had in common. In contrast, for a right outer join, all rows from the right table will be returned plus the rows that the left table had in common. To run the code in this example I used PostgreSQL 9.6 in SQL Fiddle. Feel free to use that if you would like to try out running the code without setting up a complicated environment. I have simplified the output of the tables in the examples to remove duplicate columns just to make it clearer and easier to understand, so don’t be alarmed if you try it out and it looks a little bit different. I used PostgreSQL rather than MySQL for this story because MySQL does not use full outer joins. Let’s assume that you are trying to join two tables of student grades from Hogwarts School of Witchcraft and Wizardry. These tables are called potions_class and charms_class. Each table has two columns containing the names of the students and grades. CREATE TABLE charms_class ( student_name varchar(255), charms_grade varchar(255));INSERT INTO charms_class (student_name, charms_grade)VALUES ('Harry', 'C'), ('Ron', 'D'), ('Hermione', 'A'), ('Luna', 'B'), ('Neville', 'B');CREATE TABLE potions_class ( student_name varchar(255), potions_grade varchar(255));INSERT INTO potions_class (student_name, potions_grade)VALUES ('Harry', 'A'), ('Ron', 'C'), ('Hermione', 'B'), ('Ginny', 'A'), ('Draco', 'D'); charms_class potions_class Imagine that a dragon threatens Hogwarts castle. Only the students who are enrolled in both potions class and charms class are allowed to go out with the teachers to defend the school. To find out which students are in both the charms class and the potions class and what their grades are in each class you would use an inner join on the tables charms_class and potions_class. select * from charms_class INNER JOIN potions_class on charms_class.student_name=potions_class.student_name; The resulting table would look like this: In this example of an inner join, only Harry, Ron and Hermione take both charms and potions and so their grades for both classes are returned in the results. Note that students who are only enrolled in one but not the other class did not appear in the results. Therefore only Harry, Ron and Hermione are allowed to face the dragon. The Ministry of Magic only hires graduates who have completed both charms class and potions class. However there are not enough students with the required pre-requisites to fill all the roles, so the Ministry of Magic wants a list of students to speak with who are already enrolled in one class. To find out which students are in either the charms class or the potions class, you would use a full outer join. Note that if the student is not enrolled in potions class the potions_grade value will be NULL, similarly if the student is not enrolled in charms class the charms_grade value will be NULL. So any student that has a NULL value in one of the grades columns will be the ones that the Ministry of Magic want to contact. select * from charms_class FULL OUTER JOIN potions_class on charms_class.student_name=potions_class.student_name; The resulting table would look like this: In this example of a full outer join, all the students are included in the resulting table. Only Harry, Ron and Hermione take both charms and potions and so their grades for both classes are returned in the results and there are no NULL values in their rows. Ginny and Draco only have grades for potions because they did not take charms, so they are assigned NULL values for their charms grade. Luna and Neville only have grades for charms because they did not take potions, so they are assigned NULL values for their potions grade. Therefore Ginny, Draco, Luna and Neville are all students who could take the extra class in order to be able to work at the Ministry of Magic after graduation. There has been a prank pulled in the headmaster’s office and all of Professor Dumbledore’s furniture is floating on the ceiling. Students who take charms class and got a C grade or higher are under suspicion. However, students who are enrolled in potions class could not have been the culprits because their class was on a field trip at the time of the prank. To find out which students are in charms class with a grade of C or higher and are not enrolled in potions class, we would join the charms_class table and the potions_class table using a left outer join. Note that if the student is not enrolled in potions class the potions_grade value will be NULL. select * from charms_class LEFT OUTER JOIN potions_class on charms_class.student_name=potions_class.student_name; The resulting table would look like this: Only Harry, Ron and Hermione take both charms and potions and so their grades for both classes are returned in the results and there are no NULL values in their rows. Luna and Neville only have grades for charms because they did not take potions, so they are assigned NULL values for their potions grade. Ginny and Draco did not take charms, so they are not included in this results table. Therefore the suspects for the prank in the headmaster’s office are Luna and Neville. They both got B grades for charms class and were not on the potions class field trip at the time of the incident. Professor Snape runs a potions club that meets at the same time as the charms class. Only students who are enrolled in potions class but not enrolled in charms class will be available to attend the club. To find out which students are in potions class and not in charms class you could use a right outer join. Note that if the student is not enrolled in charms class the charms_grade value will be NULL. select * from charms_class RIGHT OUTER JOIN potions_class on charms_class.student_name=potions_class.student_name; The resulting table would look like this: In this example of a right outer join, only Harry, Ron and Hermione take both charms and potions and so their grades for both classes are returned in the results and there are no NULL values in their rows. Ginny and Draco only have grades for potions because they did not take charms, so they are assigned NULL values for their charms grade. Luna and Neville did not take potions, so they are not included in this results table. Therefore only Ginny and Draco are available to be part of the potions club because they do not take charms class. The join that I have used most as a data scientist is left outer joins. For example, I used to work with health data and would often aggregate procedure numbers by location. In that case, I would put the location table on the left and do a left join. This is because there could be some locations where I didn’t have any procedures and if I did an inner join I would lose those locations. Inner joins are more useful when you only want complete datasets without the addition of NULL values that outer joins bring. I rarely use full outer joins, unless all the data from the two tables being joined needs to be retained. Full outer joins can end up producing very large results tables, especially if there is not very much overlap between the tables that you are joining. If there is a different SQL method that you would like explained please leave a comment below. In addition to data, my other passion is painting. You can find my wildlife art at www.katemarielewis.com
[ { "code": null, "e": 453, "s": 172, "text": "Joins in SQL are used to combine the contents of different tables. You can specify how you want the data from tables to be joined in many ways, one of which is the type of join. There are four main types of joins: inner join, full outer join, left outer join and right outer join." }, { "code": null, "e": 621, "s": 453, "text": "The major difference between inner and outer joins is that inner joins result in the intersection of two tables, whereas outer joins result in the union of two tables." }, { "code": null, "e": 846, "s": 621, "text": "In this story, I will describe the difference between an inner join, full outer join, left outer join and right outer join. I will then go through an example using characters from Harry Potter to demonstrate the differences." }, { "code": null, "e": 947, "s": 846, "text": "A Venn diagram is a helpful way to visualise the difference between an inner join and an outer join." }, { "code": null, "e": 1114, "s": 947, "text": "Inner joins result in the overlapping part of the Venn diagram of two datasets, whilst for full outer joins the outer parts of the Venn diagram will also be returned." }, { "code": null, "e": 1265, "s": 1114, "text": "For an inner join, only the rows that both tables have in common are returned. However, for a full outer join, all rows from both tables are returned." }, { "code": null, "e": 1414, "s": 1265, "text": "Left and right outer joins are useful if you want to get all the values from one table but only the rows that match that table from the other table." }, { "code": null, "e": 1668, "s": 1414, "text": "So in a left outer join, all rows from the left table will be returned plus the rows that the right table had in common. In contrast, for a right outer join, all rows from the right table will be returned plus the rows that the left table had in common." }, { "code": null, "e": 2159, "s": 1668, "text": "To run the code in this example I used PostgreSQL 9.6 in SQL Fiddle. Feel free to use that if you would like to try out running the code without setting up a complicated environment. I have simplified the output of the tables in the examples to remove duplicate columns just to make it clearer and easier to understand, so don’t be alarmed if you try it out and it looks a little bit different. I used PostgreSQL rather than MySQL for this story because MySQL does not use full outer joins." }, { "code": null, "e": 2410, "s": 2159, "text": "Let’s assume that you are trying to join two tables of student grades from Hogwarts School of Witchcraft and Wizardry. These tables are called potions_class and charms_class. Each table has two columns containing the names of the students and grades." }, { "code": null, "e": 2903, "s": 2410, "text": "CREATE TABLE charms_class ( student_name varchar(255), charms_grade varchar(255));INSERT INTO charms_class (student_name, charms_grade)VALUES ('Harry', 'C'), ('Ron', 'D'), ('Hermione', 'A'), ('Luna', 'B'), ('Neville', 'B');CREATE TABLE potions_class ( student_name varchar(255), potions_grade varchar(255));INSERT INTO potions_class (student_name, potions_grade)VALUES ('Harry', 'A'), ('Ron', 'C'), ('Hermione', 'B'), ('Ginny', 'A'), ('Draco', 'D');" }, { "code": null, "e": 2916, "s": 2903, "text": "charms_class" }, { "code": null, "e": 2930, "s": 2916, "text": "potions_class" }, { "code": null, "e": 3115, "s": 2930, "text": "Imagine that a dragon threatens Hogwarts castle. Only the students who are enrolled in both potions class and charms class are allowed to go out with the teachers to defend the school." }, { "code": null, "e": 3307, "s": 3115, "text": "To find out which students are in both the charms class and the potions class and what their grades are in each class you would use an inner join on the tables charms_class and potions_class." }, { "code": null, "e": 3416, "s": 3307, "text": "select * from charms_class INNER JOIN potions_class on charms_class.student_name=potions_class.student_name;" }, { "code": null, "e": 3458, "s": 3416, "text": "The resulting table would look like this:" }, { "code": null, "e": 3719, "s": 3458, "text": "In this example of an inner join, only Harry, Ron and Hermione take both charms and potions and so their grades for both classes are returned in the results. Note that students who are only enrolled in one but not the other class did not appear in the results." }, { "code": null, "e": 3790, "s": 3719, "text": "Therefore only Harry, Ron and Hermione are allowed to face the dragon." }, { "code": null, "e": 4086, "s": 3790, "text": "The Ministry of Magic only hires graduates who have completed both charms class and potions class. However there are not enough students with the required pre-requisites to fill all the roles, so the Ministry of Magic wants a list of students to speak with who are already enrolled in one class." }, { "code": null, "e": 4389, "s": 4086, "text": "To find out which students are in either the charms class or the potions class, you would use a full outer join. Note that if the student is not enrolled in potions class the potions_grade value will be NULL, similarly if the student is not enrolled in charms class the charms_grade value will be NULL." }, { "code": null, "e": 4516, "s": 4389, "text": "So any student that has a NULL value in one of the grades columns will be the ones that the Ministry of Magic want to contact." }, { "code": null, "e": 4630, "s": 4516, "text": "select * from charms_class FULL OUTER JOIN potions_class on charms_class.student_name=potions_class.student_name;" }, { "code": null, "e": 4672, "s": 4630, "text": "The resulting table would look like this:" }, { "code": null, "e": 4931, "s": 4672, "text": "In this example of a full outer join, all the students are included in the resulting table. Only Harry, Ron and Hermione take both charms and potions and so their grades for both classes are returned in the results and there are no NULL values in their rows." }, { "code": null, "e": 5205, "s": 4931, "text": "Ginny and Draco only have grades for potions because they did not take charms, so they are assigned NULL values for their charms grade. Luna and Neville only have grades for charms because they did not take potions, so they are assigned NULL values for their potions grade." }, { "code": null, "e": 5365, "s": 5205, "text": "Therefore Ginny, Draco, Luna and Neville are all students who could take the extra class in order to be able to work at the Ministry of Magic after graduation." }, { "code": null, "e": 5725, "s": 5365, "text": "There has been a prank pulled in the headmaster’s office and all of Professor Dumbledore’s furniture is floating on the ceiling. Students who take charms class and got a C grade or higher are under suspicion. However, students who are enrolled in potions class could not have been the culprits because their class was on a field trip at the time of the prank." }, { "code": null, "e": 6025, "s": 5725, "text": "To find out which students are in charms class with a grade of C or higher and are not enrolled in potions class, we would join the charms_class table and the potions_class table using a left outer join. Note that if the student is not enrolled in potions class the potions_grade value will be NULL." }, { "code": null, "e": 6139, "s": 6025, "text": "select * from charms_class LEFT OUTER JOIN potions_class on charms_class.student_name=potions_class.student_name;" }, { "code": null, "e": 6181, "s": 6139, "text": "The resulting table would look like this:" }, { "code": null, "e": 6348, "s": 6181, "text": "Only Harry, Ron and Hermione take both charms and potions and so their grades for both classes are returned in the results and there are no NULL values in their rows." }, { "code": null, "e": 6486, "s": 6348, "text": "Luna and Neville only have grades for charms because they did not take potions, so they are assigned NULL values for their potions grade." }, { "code": null, "e": 6571, "s": 6486, "text": "Ginny and Draco did not take charms, so they are not included in this results table." }, { "code": null, "e": 6771, "s": 6571, "text": "Therefore the suspects for the prank in the headmaster’s office are Luna and Neville. They both got B grades for charms class and were not on the potions class field trip at the time of the incident." }, { "code": null, "e": 6975, "s": 6771, "text": "Professor Snape runs a potions club that meets at the same time as the charms class. Only students who are enrolled in potions class but not enrolled in charms class will be available to attend the club." }, { "code": null, "e": 7175, "s": 6975, "text": "To find out which students are in potions class and not in charms class you could use a right outer join. Note that if the student is not enrolled in charms class the charms_grade value will be NULL." }, { "code": null, "e": 7290, "s": 7175, "text": "select * from charms_class RIGHT OUTER JOIN potions_class on charms_class.student_name=potions_class.student_name;" }, { "code": null, "e": 7332, "s": 7290, "text": "The resulting table would look like this:" }, { "code": null, "e": 7538, "s": 7332, "text": "In this example of a right outer join, only Harry, Ron and Hermione take both charms and potions and so their grades for both classes are returned in the results and there are no NULL values in their rows." }, { "code": null, "e": 7674, "s": 7538, "text": "Ginny and Draco only have grades for potions because they did not take charms, so they are assigned NULL values for their charms grade." }, { "code": null, "e": 7761, "s": 7674, "text": "Luna and Neville did not take potions, so they are not included in this results table." }, { "code": null, "e": 7876, "s": 7761, "text": "Therefore only Ginny and Draco are available to be part of the potions club because they do not take charms class." }, { "code": null, "e": 8647, "s": 7876, "text": "The join that I have used most as a data scientist is left outer joins. For example, I used to work with health data and would often aggregate procedure numbers by location. In that case, I would put the location table on the left and do a left join. This is because there could be some locations where I didn’t have any procedures and if I did an inner join I would lose those locations. Inner joins are more useful when you only want complete datasets without the addition of NULL values that outer joins bring. I rarely use full outer joins, unless all the data from the two tables being joined needs to be retained. Full outer joins can end up producing very large results tables, especially if there is not very much overlap between the tables that you are joining." }, { "code": null, "e": 8742, "s": 8647, "text": "If there is a different SQL method that you would like explained please leave a comment below." } ]
Calculating the area of a triangle using its three sides in JavaScript
We are required to write a JavaScript function that takes in the three sides of a triangle and uses Heron’s formula to calculate its area. Following is the code − Live Demo const s1 = 10; const s2 = 8; const s3 = 7; const findArea = (s1, s2, s3) => { const arr = []; const arguments = [s1, s2, s3]; for(let i = 0; i < arguments.length; i++){ arr.push(arguments[i]); }; let s = (arr[0] + arr[1] + arr[2]) / 2; return Math.sqrt(s * (s - arr[0]) * (s - arr[1]) * (s - arr[2])); }; console.log(findArea(s1, s2, s3)); 27.810744326608734
[ { "code": null, "e": 1201, "s": 1062, "text": "We are required to write a JavaScript function that takes in the three sides of a triangle and uses Heron’s formula to calculate its area." }, { "code": null, "e": 1225, "s": 1201, "text": "Following is the code −" }, { "code": null, "e": 1236, "s": 1225, "text": " Live Demo" }, { "code": null, "e": 1600, "s": 1236, "text": "const s1 = 10;\nconst s2 = 8;\nconst s3 = 7;\nconst findArea = (s1, s2, s3) => {\n const arr = [];\n const arguments = [s1, s2, s3];\n for(let i = 0; i < arguments.length; i++){\n arr.push(arguments[i]);\n };\n let s = (arr[0] + arr[1] + arr[2]) / 2;\n return Math.sqrt(s * (s - arr[0]) * (s - arr[1]) * (s - arr[2]));\n};\nconsole.log(findArea(s1, s2, s3));" }, { "code": null, "e": 1619, "s": 1600, "text": "27.810744326608734" } ]
Find shortest unique prefix for every word in a given list | Set 1 (Using Trie) - GeeksforGeeks
01 Dec, 2021 Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another. Examples: Input: arr[] = {"zebra", "dog", "duck", "dove"} Output: dog, dov, du, z Explanation: dog => dog dove => dov duck => du zebra => z Input: arr[] = {"geeksgeeks", "geeksquiz", "geeksforgeeks"}; Output: geeksf, geeksg, geeksq} A Simple Solution is to consider every prefix of every word (starting from the shortest to largest), and if a prefix is not prefix of any other string, then print it. An Efficient Solution is to use Trie. The idea is to maintain a count in every node. Below are steps.1) Construct a Trie of all words. Also maintain frequency of every node (Here frequency is number of times node is visited during insertion). Time complexity of this step is O(N) where N is total number of characters in all words. 2) Now, for every word, we find the character nearest to the root with frequency as 1. The prefix of the word is path from root to this character. To do this, we can traverse Trie starting from root. For every node being traversed, we check its frequency. If frequency is one, we print all characters from root to this node and don’t traverse down this node.Time complexity if this step also is O(N) where N is total number of characters in all words. root / \ (d, 3)/ \(z, 1) / \ Node1 Node2 / \ \ (o,2)/ \(u,1) \(e,1) / \ \ Node1.1 Node1.2 Node2.1 / \ \ \ (g,1)/ \ (t,1) \(c,1) \(b,1) / \ \ \ Leaf Leaf Node1.2.1 Node2.1.1 (dog) (dot) \ \ \(k, 1) \(r, 1) \ \ Leaf Node2.1.1.1 (duck) \ \(a,1) \ Leaf (zebra) Below is the implementation of above idea. C++ Java C# // C++ program to print all prefixes that// uniquely represent words.#include<bits/stdc++.h>using namespace std; #define MAX 256 // Maximum length of an input word#define MAX_WORD_LEN 500 // Trie Node.struct trieNode{ struct trieNode *child[MAX]; int freq; // To store frequency}; // Function to create a new trie node.struct trieNode *newTrieNode(void){ struct trieNode *newNode = new trieNode; newNode->freq = 1; for (int i = 0; i<MAX; i++) newNode->child[i] = NULL; return newNode;} // Method to insert a new string into Trievoid insert(struct trieNode *root, string str){ // Length of the URL int len = str.length(); struct trieNode *pCrawl = root; // Traversing over the length of given str. for (int level = 0; level<len; level++) { // Get index of child node from current character // in str. int index = str[level]; // Create a new child if not exist already if (!pCrawl->child[index]) pCrawl->child[index] = newTrieNode(); else (pCrawl->child[index]->freq)++; // Move to the child pCrawl = pCrawl->child[index]; }} // This function prints unique prefix for every word stored// in Trie. Prefixes one by one are stored in prefix[].// 'ind' is current index of prefix[]void findPrefixesUtil(struct trieNode *root, char prefix[], int ind){ // Corner case if (root == NULL) return; // Base case if (root->freq == 1) { prefix[ind] = '\0'; cout << prefix << " "; return; } for (int i=0; i<MAX; i++) { if (root->child[i] != NULL) { prefix[ind] = i; findPrefixesUtil(root->child[i], prefix, ind+1); } }} // Function to print all prefixes that uniquely// represent all words in arr[0..n-1]void findPrefixes(string arr[], int n){ // Construct a Trie of all words struct trieNode *root = newTrieNode(); root->freq = 0; for (int i = 0; i<n; i++) insert(root, arr[i]); // Create an array to store all prefixes char prefix[MAX_WORD_LEN]; // Print all prefixes using Trie Traversal findPrefixesUtil(root, prefix, 0);} // Driver function.int main(){ string arr[] = {"zebra", "dog", "duck", "dove"}; int n = sizeof(arr)/sizeof(arr[0]); findPrefixes(arr, n); return 0;} // Java program to print all prefixes that// uniquely represent words.public class Unique_Prefix_Trie { static final int MAX = 256; // Maximum length of an input word static final int MAX_WORD_LEN = 500; // Trie Node. static class TrieNode { TrieNode[] child = new TrieNode[MAX]; int freq; // To store frequency TrieNode() { freq =1; for (int i = 0; i < MAX; i++) child[i] = null; } } static TrieNode root; // Method to insert a new string into Trie static void insert(String str) { // Length of the URL int len = str.length(); TrieNode pCrawl = root; // Traversing over the length of given str. for (int level = 0; level<len; level++) { // Get index of child node from current character // in str. int index = str.charAt(level); // Create a new child if not exist already if (pCrawl.child[index] == null) pCrawl.child[index] = new TrieNode(); else (pCrawl.child[index].freq)++; // Move to the child pCrawl = pCrawl.child[index]; } } // This function prints unique prefix for every word stored // in Trie. Prefixes one by one are stored in prefix[]. // 'ind' is current index of prefix[] static void findPrefixesUtil(TrieNode root, char[] prefix, int ind) { // Corner case if (root == null) return; // Base case if (root.freq == 1) { prefix[ind] = '\0'; int i = 0; while(prefix[i] != '\0') System.out.print(prefix[i++]); System.out.print(" "); return; } for (int i=0; i<MAX; i++) { if (root.child[i] != null) { prefix[ind] = (char) i; findPrefixesUtil(root.child[i], prefix, ind+1); } } } // Function to print all prefixes that uniquely // represent all words in arr[0..n-1] static void findPrefixes(String arr[], int n) { // Construct a Trie of all words root = new TrieNode(); root.freq = 0; for (int i = 0; i<n; i++) insert(arr[i]); // Create an array to store all prefixes char[] prefix = new char[MAX_WORD_LEN]; // Print all prefixes using Trie Traversal findPrefixesUtil(root, prefix, 0); } // Driver function. public static void main(String args[]) { String arr[] = {"zebra", "dog", "duck", "dove"}; int n = arr.length; findPrefixes(arr, n); }}// This code is contributed by Sumit Ghosh // C# program to print all prefixes that// uniquely represent words.using System; public class Unique_Prefix_Trie{ static readonly int MAX = 256; // Maximum length of an input word static readonly int MAX_WORD_LEN = 500; // Trie Node. public class TrieNode { public TrieNode[] child = new TrieNode[MAX]; public int freq; // To store frequency public TrieNode() { freq = 1; for (int i = 0; i < MAX; i++) child[i] = null; } } static TrieNode root; // Method to insert a new string into Trie static void insert(String str) { // Length of the URL int len = str.Length; TrieNode pCrawl = root; // Traversing over the length of given str. for (int level = 0; level<len; level++) { // Get index of child node from // current character in str. int index = str[level]; // Create a new child if not exist already if (pCrawl.child[index] == null) pCrawl.child[index] = new TrieNode(); else (pCrawl.child[index].freq)++; // Move to the child pCrawl = pCrawl.child[index]; } } // This function prints unique prefix for every word stored // in Trie. Prefixes one by one are stored in prefix[]. // 'ind' is current index of prefix[] static void findPrefixesUtil(TrieNode root, char[] prefix, int ind) { // Corner case if (root == null) return; // Base case if (root.freq == 1) { prefix[ind] = '\0'; int i = 0; while(prefix[i] != '\0') Console.Write(prefix[i++]); Console.Write(" "); return; } for (int i = 0; i < MAX; i++) { if (root.child[i] != null) { prefix[ind] = (char) i; findPrefixesUtil(root.child[i], prefix, ind + 1); } } } // Function to print all prefixes that uniquely // represent all words in arr[0..n-1] static void findPrefixes(String []arr, int n) { // Construct a Trie of all words root = new TrieNode(); root.freq = 0; for (int i = 0; i < n; i++) insert(arr[i]); // Create an array to store all prefixes char[] prefix = new char[MAX_WORD_LEN]; // Print all prefixes using Trie Traversal findPrefixesUtil(root, prefix, 0); } // Driver code public static void Main() { String []arr = {"zebra", "dog", "duck", "dove"}; int n = arr.Length; findPrefixes(arr, n); }} /* This code contributed by PrinciRaj1992 */ Output: dog dov du z Thanks to Gaurav Ahirwar for suggesting above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 as5853535 manyaa Trie Advanced Data Structure Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Advantages of Trie Data Structure Cartesian Tree Proof that Dominant Set of a Graph is NP-Complete Ternary Search Tree Skip List | Set 2 (Insertion) Trie | (Delete) Leftist Tree / Leftist Heap Segment Tree | Set 2 (Range Minimum Query)
[ { "code": null, "e": 24406, "s": 24378, "text": "\n01 Dec, 2021" }, { "code": null, "e": 24562, "s": 24406, "text": "Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another. Examples: " }, { "code": null, "e": 24827, "s": 24562, "text": "Input: arr[] = {\"zebra\", \"dog\", \"duck\", \"dove\"}\nOutput: dog, dov, du, z\nExplanation: dog => dog\n dove => dov \n duck => du\n zebra => z\n\nInput: arr[] = {\"geeksgeeks\", \"geeksquiz\", \"geeksforgeeks\"};\nOutput: geeksf, geeksg, geeksq}" }, { "code": null, "e": 25782, "s": 24829, "text": "A Simple Solution is to consider every prefix of every word (starting from the shortest to largest), and if a prefix is not prefix of any other string, then print it. An Efficient Solution is to use Trie. The idea is to maintain a count in every node. Below are steps.1) Construct a Trie of all words. Also maintain frequency of every node (Here frequency is number of times node is visited during insertion). Time complexity of this step is O(N) where N is total number of characters in all words. 2) Now, for every word, we find the character nearest to the root with frequency as 1. The prefix of the word is path from root to this character. To do this, we can traverse Trie starting from root. For every node being traversed, we check its frequency. If frequency is one, we print all characters from root to this node and don’t traverse down this node.Time complexity if this step also is O(N) where N is total number of characters in all words. " }, { "code": null, "e": 26631, "s": 25782, "text": " root\n / \\\n (d, 3)/ \\(z, 1)\n / \\\n Node1 Node2\n / \\ \\\n (o,2)/ \\(u,1) \\(e,1)\n / \\ \\\n Node1.1 Node1.2 Node2.1\n / \\ \\ \\\n(g,1)/ \\ (t,1) \\(c,1) \\(b,1)\n / \\ \\ \\ \n Leaf Leaf Node1.2.1 Node2.1.1\n (dog) (dot) \\ \\\n \\(k, 1) \\(r, 1)\n \\ \\ \n Leaf Node2.1.1.1\n (duck) \\\n \\(a,1)\n \\\n Leaf\n (zebra)" }, { "code": null, "e": 26676, "s": 26631, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 26680, "s": 26676, "text": "C++" }, { "code": null, "e": 26685, "s": 26680, "text": "Java" }, { "code": null, "e": 26688, "s": 26685, "text": "C#" }, { "code": "// C++ program to print all prefixes that// uniquely represent words.#include<bits/stdc++.h>using namespace std; #define MAX 256 // Maximum length of an input word#define MAX_WORD_LEN 500 // Trie Node.struct trieNode{ struct trieNode *child[MAX]; int freq; // To store frequency}; // Function to create a new trie node.struct trieNode *newTrieNode(void){ struct trieNode *newNode = new trieNode; newNode->freq = 1; for (int i = 0; i<MAX; i++) newNode->child[i] = NULL; return newNode;} // Method to insert a new string into Trievoid insert(struct trieNode *root, string str){ // Length of the URL int len = str.length(); struct trieNode *pCrawl = root; // Traversing over the length of given str. for (int level = 0; level<len; level++) { // Get index of child node from current character // in str. int index = str[level]; // Create a new child if not exist already if (!pCrawl->child[index]) pCrawl->child[index] = newTrieNode(); else (pCrawl->child[index]->freq)++; // Move to the child pCrawl = pCrawl->child[index]; }} // This function prints unique prefix for every word stored// in Trie. Prefixes one by one are stored in prefix[].// 'ind' is current index of prefix[]void findPrefixesUtil(struct trieNode *root, char prefix[], int ind){ // Corner case if (root == NULL) return; // Base case if (root->freq == 1) { prefix[ind] = '\\0'; cout << prefix << \" \"; return; } for (int i=0; i<MAX; i++) { if (root->child[i] != NULL) { prefix[ind] = i; findPrefixesUtil(root->child[i], prefix, ind+1); } }} // Function to print all prefixes that uniquely// represent all words in arr[0..n-1]void findPrefixes(string arr[], int n){ // Construct a Trie of all words struct trieNode *root = newTrieNode(); root->freq = 0; for (int i = 0; i<n; i++) insert(root, arr[i]); // Create an array to store all prefixes char prefix[MAX_WORD_LEN]; // Print all prefixes using Trie Traversal findPrefixesUtil(root, prefix, 0);} // Driver function.int main(){ string arr[] = {\"zebra\", \"dog\", \"duck\", \"dove\"}; int n = sizeof(arr)/sizeof(arr[0]); findPrefixes(arr, n); return 0;}", "e": 29035, "s": 26688, "text": null }, { "code": "// Java program to print all prefixes that// uniquely represent words.public class Unique_Prefix_Trie { static final int MAX = 256; // Maximum length of an input word static final int MAX_WORD_LEN = 500; // Trie Node. static class TrieNode { TrieNode[] child = new TrieNode[MAX]; int freq; // To store frequency TrieNode() { freq =1; for (int i = 0; i < MAX; i++) child[i] = null; } } static TrieNode root; // Method to insert a new string into Trie static void insert(String str) { // Length of the URL int len = str.length(); TrieNode pCrawl = root; // Traversing over the length of given str. for (int level = 0; level<len; level++) { // Get index of child node from current character // in str. int index = str.charAt(level); // Create a new child if not exist already if (pCrawl.child[index] == null) pCrawl.child[index] = new TrieNode(); else (pCrawl.child[index].freq)++; // Move to the child pCrawl = pCrawl.child[index]; } } // This function prints unique prefix for every word stored // in Trie. Prefixes one by one are stored in prefix[]. // 'ind' is current index of prefix[] static void findPrefixesUtil(TrieNode root, char[] prefix, int ind) { // Corner case if (root == null) return; // Base case if (root.freq == 1) { prefix[ind] = '\\0'; int i = 0; while(prefix[i] != '\\0') System.out.print(prefix[i++]); System.out.print(\" \"); return; } for (int i=0; i<MAX; i++) { if (root.child[i] != null) { prefix[ind] = (char) i; findPrefixesUtil(root.child[i], prefix, ind+1); } } } // Function to print all prefixes that uniquely // represent all words in arr[0..n-1] static void findPrefixes(String arr[], int n) { // Construct a Trie of all words root = new TrieNode(); root.freq = 0; for (int i = 0; i<n; i++) insert(arr[i]); // Create an array to store all prefixes char[] prefix = new char[MAX_WORD_LEN]; // Print all prefixes using Trie Traversal findPrefixesUtil(root, prefix, 0); } // Driver function. public static void main(String args[]) { String arr[] = {\"zebra\", \"dog\", \"duck\", \"dove\"}; int n = arr.length; findPrefixes(arr, n); }}// This code is contributed by Sumit Ghosh", "e": 31835, "s": 29035, "text": null }, { "code": "// C# program to print all prefixes that// uniquely represent words.using System; public class Unique_Prefix_Trie{ static readonly int MAX = 256; // Maximum length of an input word static readonly int MAX_WORD_LEN = 500; // Trie Node. public class TrieNode { public TrieNode[] child = new TrieNode[MAX]; public int freq; // To store frequency public TrieNode() { freq = 1; for (int i = 0; i < MAX; i++) child[i] = null; } } static TrieNode root; // Method to insert a new string into Trie static void insert(String str) { // Length of the URL int len = str.Length; TrieNode pCrawl = root; // Traversing over the length of given str. for (int level = 0; level<len; level++) { // Get index of child node from // current character in str. int index = str[level]; // Create a new child if not exist already if (pCrawl.child[index] == null) pCrawl.child[index] = new TrieNode(); else (pCrawl.child[index].freq)++; // Move to the child pCrawl = pCrawl.child[index]; } } // This function prints unique prefix for every word stored // in Trie. Prefixes one by one are stored in prefix[]. // 'ind' is current index of prefix[] static void findPrefixesUtil(TrieNode root, char[] prefix, int ind) { // Corner case if (root == null) return; // Base case if (root.freq == 1) { prefix[ind] = '\\0'; int i = 0; while(prefix[i] != '\\0') Console.Write(prefix[i++]); Console.Write(\" \"); return; } for (int i = 0; i < MAX; i++) { if (root.child[i] != null) { prefix[ind] = (char) i; findPrefixesUtil(root.child[i], prefix, ind + 1); } } } // Function to print all prefixes that uniquely // represent all words in arr[0..n-1] static void findPrefixes(String []arr, int n) { // Construct a Trie of all words root = new TrieNode(); root.freq = 0; for (int i = 0; i < n; i++) insert(arr[i]); // Create an array to store all prefixes char[] prefix = new char[MAX_WORD_LEN]; // Print all prefixes using Trie Traversal findPrefixesUtil(root, prefix, 0); } // Driver code public static void Main() { String []arr = {\"zebra\", \"dog\", \"duck\", \"dove\"}; int n = arr.Length; findPrefixes(arr, n); }} /* This code contributed by PrinciRaj1992 */", "e": 34607, "s": 31835, "text": null }, { "code": null, "e": 34616, "s": 34607, "text": "Output: " }, { "code": null, "e": 34629, "s": 34616, "text": "dog dov du z" }, { "code": null, "e": 34810, "s": 34629, "text": "Thanks to Gaurav Ahirwar for suggesting above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34824, "s": 34810, "text": "princiraj1992" }, { "code": null, "e": 34834, "s": 34824, "text": "as5853535" }, { "code": null, "e": 34841, "s": 34834, "text": "manyaa" }, { "code": null, "e": 34846, "s": 34841, "text": "Trie" }, { "code": null, "e": 34870, "s": 34846, "text": "Advanced Data Structure" }, { "code": null, "e": 34875, "s": 34870, "text": "Trie" }, { "code": null, "e": 34973, "s": 34875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34982, "s": 34973, "text": "Comments" }, { "code": null, "e": 34995, "s": 34982, "text": "Old Comments" }, { "code": null, "e": 35037, "s": 34995, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 35083, "s": 35037, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 35117, "s": 35083, "text": "Advantages of Trie Data Structure" }, { "code": null, "e": 35132, "s": 35117, "text": "Cartesian Tree" }, { "code": null, "e": 35182, "s": 35132, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 35202, "s": 35182, "text": "Ternary Search Tree" }, { "code": null, "e": 35232, "s": 35202, "text": "Skip List | Set 2 (Insertion)" }, { "code": null, "e": 35248, "s": 35232, "text": "Trie | (Delete)" }, { "code": null, "e": 35276, "s": 35248, "text": "Leftist Tree / Leftist Heap" } ]
Minimum Cost to Connect Sticks in C++
Suppose we have some sticks with positive integer lengths. We can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. This will be performed until there is one stick remaining. We have to find the minimum cost of connecting all the given sticks into one stick in this way. So if the stack is [2,4,3], then the output will be 14. To solve this, we will follow these steps − Define a max heap priority queue pq insert all elements of s into pq ans := 0 while pq has more than one elementtemp := top of the queue, delete top from pqtemp := temp + top element of pq, and delete from pqans := ans + tempinsert temp into pq temp := top of the queue, delete top from pq temp := temp + top element of pq, and delete from pq ans := ans + temp insert temp into pq return ans Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int connectSticks(vector<int>& s) { priority_queue <int, vector<int>, greater<int> > pq; for(int i =0;i<s.size();i++)pq.push(s[i]); int ans = 0; while(pq.size()>1){ int temp = pq.top(); pq.pop(); temp += pq.top(); pq.pop(); ans+=temp; pq.push(temp); } return ans; } }; main(){ vector<int> v = {2,4,3}; Solution ob; cout <<ob.connectSticks(v); } [2,4,3] 14
[ { "code": null, "e": 1423, "s": 1062, "text": "Suppose we have some sticks with positive integer lengths. We can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. This will be performed until there is one stick remaining. We have to find the minimum cost of connecting all the given sticks into one stick in this way. So if the stack is [2,4,3], then the output will be 14." }, { "code": null, "e": 1467, "s": 1423, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1503, "s": 1467, "text": "Define a max heap priority queue pq" }, { "code": null, "e": 1536, "s": 1503, "text": "insert all elements of s into pq" }, { "code": null, "e": 1545, "s": 1536, "text": "ans := 0" }, { "code": null, "e": 1712, "s": 1545, "text": "while pq has more than one elementtemp := top of the queue, delete top from pqtemp := temp + top element of pq, and delete from pqans := ans + tempinsert temp into pq" }, { "code": null, "e": 1757, "s": 1712, "text": "temp := top of the queue, delete top from pq" }, { "code": null, "e": 1810, "s": 1757, "text": "temp := temp + top element of pq, and delete from pq" }, { "code": null, "e": 1828, "s": 1810, "text": "ans := ans + temp" }, { "code": null, "e": 1848, "s": 1828, "text": "insert temp into pq" }, { "code": null, "e": 1859, "s": 1848, "text": "return ans" }, { "code": null, "e": 1931, "s": 1859, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1942, "s": 1931, "text": " Live Demo" }, { "code": null, "e": 2463, "s": 1942, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int connectSticks(vector<int>& s) {\n priority_queue <int, vector<int>, greater<int> > pq;\n for(int i =0;i<s.size();i++)pq.push(s[i]);\n int ans = 0;\n while(pq.size()>1){\n int temp = pq.top();\n pq.pop();\n temp += pq.top();\n pq.pop();\n ans+=temp;\n pq.push(temp);\n }\n return ans;\n }\n};\nmain(){\n vector<int> v = {2,4,3};\n Solution ob;\n cout <<ob.connectSticks(v);\n}" }, { "code": null, "e": 2471, "s": 2463, "text": "[2,4,3]" }, { "code": null, "e": 2474, "s": 2471, "text": "14" } ]
Tryit Editor v3.7
Tryit: HTML nav element
[]
Implement a JavaScript when an element loses focus - GeeksforGeeks
24 Jun, 2019 Given a document, the task is to implement functionality when the element loses focus. We have 2 options, one is the onblur event and another is onfocusout event JavaScript. We’re going to discuss a few methods.First few methods to understand. onblur Event:This event happens when an element is going to lose focus.Syntax:In HTML:<element onblur="script"> In JavaScript:object.onblur = function(){script}; In JavaScript, with the addEventListener() method:object.addEventListener("blur", script); Syntax: In HTML:<element onblur="script"> <element onblur="script"> In JavaScript:object.onblur = function(){script}; object.onblur = function(){script}; In JavaScript, with the addEventListener() method:object.addEventListener("blur", script); object.addEventListener("blur", script); onfocusout Event:This method appends a node as the last child of a node.Syntax:In HTML:<element onfocusout="script"> In JavaScript:object.onfocusout = function(){script}; In JavaScript, with the addEventListener() method:object.addEventListener("focusout", script); Syntax: In HTML:<element onfocusout="script"> <element onfocusout="script"> In JavaScript:object.onfocusout = function(){script}; object.onfocusout = function(){script}; In JavaScript, with the addEventListener() method:object.addEventListener("focusout", script); object.addEventListener("focusout", script); Example 1: This example adds an onblur event to the <input> element and when it happens the specified code runs. <!DOCTYPE HTML><html> <head> <title> JavaScript | Run JavaScript when an element loses focus. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <input type="text" name="input" value="inputElement" onblur="gfg_Run();" /> <br> <br> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = 'First click inside of <input>'+ ' and then outside to perform event!'; el_up.innerHTML = today; function gfg_Run() { el_down.innerHTML = "Input element lost focus"; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example adds an onfocusout event to the <input> element and when it happens the specified code runs. <!DOCTYPE HTML><html> <head> <title> JavaScript | Run JavaScript when an element loses focus. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <input type="text" name="input" value="inputElement" onfocusout="gfg_Run();" /> <br> <br> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = 'First click inside of <input>'+ ' and then outside to perform event!'; el_up.innerHTML = today; function gfg_Run() { el_down.innerHTML = "Input element lost focus"; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to remove duplicate elements from JavaScript Array ? How to get selected value in dropdown list using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25220, "s": 25192, "text": "\n24 Jun, 2019" }, { "code": null, "e": 25464, "s": 25220, "text": "Given a document, the task is to implement functionality when the element loses focus. We have 2 options, one is the onblur event and another is onfocusout event JavaScript. We’re going to discuss a few methods.First few methods to understand." }, { "code": null, "e": 25718, "s": 25464, "text": "onblur Event:This event happens when an element is going to lose focus.Syntax:In HTML:<element onblur=\"script\">\nIn JavaScript:object.onblur = function(){script};\nIn JavaScript, with the addEventListener() method:object.addEventListener(\"blur\", script);\n" }, { "code": null, "e": 25726, "s": 25718, "text": "Syntax:" }, { "code": null, "e": 25761, "s": 25726, "text": "In HTML:<element onblur=\"script\">\n" }, { "code": null, "e": 25788, "s": 25761, "text": "<element onblur=\"script\">\n" }, { "code": null, "e": 25839, "s": 25788, "text": "In JavaScript:object.onblur = function(){script};\n" }, { "code": null, "e": 25876, "s": 25839, "text": "object.onblur = function(){script};\n" }, { "code": null, "e": 25968, "s": 25876, "text": "In JavaScript, with the addEventListener() method:object.addEventListener(\"blur\", script);\n" }, { "code": null, "e": 26010, "s": 25968, "text": "object.addEventListener(\"blur\", script);\n" }, { "code": null, "e": 26277, "s": 26010, "text": "onfocusout Event:This method appends a node as the last child of a node.Syntax:In HTML:<element onfocusout=\"script\">\nIn JavaScript:object.onfocusout = function(){script};\nIn JavaScript, with the addEventListener() method:object.addEventListener(\"focusout\", script);\n" }, { "code": null, "e": 26285, "s": 26277, "text": "Syntax:" }, { "code": null, "e": 26324, "s": 26285, "text": "In HTML:<element onfocusout=\"script\">\n" }, { "code": null, "e": 26355, "s": 26324, "text": "<element onfocusout=\"script\">\n" }, { "code": null, "e": 26410, "s": 26355, "text": "In JavaScript:object.onfocusout = function(){script};\n" }, { "code": null, "e": 26451, "s": 26410, "text": "object.onfocusout = function(){script};\n" }, { "code": null, "e": 26547, "s": 26451, "text": "In JavaScript, with the addEventListener() method:object.addEventListener(\"focusout\", script);\n" }, { "code": null, "e": 26593, "s": 26547, "text": "object.addEventListener(\"focusout\", script);\n" }, { "code": null, "e": 26706, "s": 26593, "text": "Example 1: This example adds an onblur event to the <input> element and when it happens the specified code runs." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Run JavaScript when an element loses focus. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <input type=\"text\" name=\"input\" value=\"inputElement\" onblur=\"gfg_Run();\" /> <br> <br> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = 'First click inside of <input>'+ ' and then outside to perform event!'; el_up.innerHTML = today; function gfg_Run() { el_down.innerHTML = \"Input element lost focus\"; } </script></body> </html>", "e": 27678, "s": 26706, "text": null }, { "code": null, "e": 27686, "s": 27678, "text": "Output:" }, { "code": null, "e": 27717, "s": 27686, "text": "Before clicking on the button:" }, { "code": null, "e": 27747, "s": 27717, "text": "After clicking on the button:" }, { "code": null, "e": 27864, "s": 27747, "text": "Example 2: This example adds an onfocusout event to the <input> element and when it happens the specified code runs." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Run JavaScript when an element loses focus. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <input type=\"text\" name=\"input\" value=\"inputElement\" onfocusout=\"gfg_Run();\" /> <br> <br> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = 'First click inside of <input>'+ ' and then outside to perform event!'; el_up.innerHTML = today; function gfg_Run() { el_down.innerHTML = \"Input element lost focus\"; } </script></body> </html>", "e": 28837, "s": 27864, "text": null }, { "code": null, "e": 28845, "s": 28837, "text": "Output:" }, { "code": null, "e": 28876, "s": 28845, "text": "Before clicking on the button:" }, { "code": null, "e": 28906, "s": 28876, "text": "After clicking on the button:" }, { "code": null, "e": 28922, "s": 28906, "text": "JavaScript-Misc" }, { "code": null, "e": 28933, "s": 28922, "text": "JavaScript" }, { "code": null, "e": 28950, "s": 28933, "text": "Web Technologies" }, { "code": null, "e": 29048, "s": 28950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29057, "s": 29048, "text": "Comments" }, { "code": null, "e": 29070, "s": 29057, "text": "Old Comments" }, { "code": null, "e": 29131, "s": 29070, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29172, "s": 29131, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29226, "s": 29172, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29283, "s": 29226, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 29345, "s": 29283, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 29387, "s": 29345, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29420, "s": 29387, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29482, "s": 29420, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29525, "s": 29482, "text": "How to fetch data from an API in ReactJS ?" } ]
How to round down to 2 decimals a float using Python?
Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2. If third digit after decimal point is greater than 5, last digit is increased by 1. >>> round(1.4756,2) 1.48 >>> round(1.3333,2) 1.33
[ { "code": null, "e": 1370, "s": 1062, "text": "Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2. If third digit after decimal point is greater than 5, last digit is increased by 1." }, { "code": null, "e": 1420, "s": 1370, "text": ">>> round(1.4756,2)\n1.48\n>>> round(1.3333,2)\n1.33" } ]
How to use ButtonGroup Component in ReactJS? - GeeksforGeeks
22 Jan, 2021 The ButtonGroup component can be used to group related buttons. Material UI for React has this component available for us and it is very easy to integrate. We can use ButtonGroup 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 Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React, { useState } from 'react';import Button from '@material-ui/core/Button';import ButtonGroup from '@material-ui/core/ButtonGroup'; const App = () => { const [message, setMessage] = useState('') return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to use GroupButton Component in ReactJS?</h3> <ButtonGroup color="primary" aria-label="outlined primary button group"> <Button onClick={()=> { setMessage('You just clicked First Button') }} >First Button</Button> <Button onClick={()=> { setMessage('You just clicked Second Button') }} >Second Button</Button> <Button onClick={()=> { setMessage('You just clicked Third Button') }} >Third Button</Button> </ButtonGroup> <h3>{message}</h3> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to remove duplicate elements from JavaScript Array ? How to get selected value in dropdown list using JavaScript ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ?
[ { "code": null, "e": 25232, "s": 25204, "text": "\n22 Jan, 2021" }, { "code": null, "e": 25462, "s": 25232, "text": "The ButtonGroup component can be used to group related buttons. Material UI for React has this component available for us and it is very easy to integrate. We can use ButtonGroup Component in ReactJS using the following approach:" }, { "code": null, "e": 25512, "s": 25462, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25576, "s": 25512, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25608, "s": 25576, "text": "npx create-react-app foldername" }, { "code": null, "e": 25708, "s": 25608, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25722, "s": 25708, "text": "cd foldername" }, { "code": null, "e": 25831, "s": 25722, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 25861, "s": 25831, "text": "npm install @material-ui/core" }, { "code": null, "e": 25913, "s": 25861, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25931, "s": 25913, "text": "Project Structure" }, { "code": null, "e": 26060, "s": 25931, "text": "App.js: 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": 26071, "s": 26060, "text": "Javascript" }, { "code": "import React, { useState } from 'react';import Button from '@material-ui/core/Button';import ButtonGroup from '@material-ui/core/ButtonGroup'; const App = () => { const [message, setMessage] = useState('') return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to use GroupButton Component in ReactJS?</h3> <ButtonGroup color=\"primary\" aria-label=\"outlined primary button group\"> <Button onClick={()=> { setMessage('You just clicked First Button') }} >First Button</Button> <Button onClick={()=> { setMessage('You just clicked Second Button') }} >Second Button</Button> <Button onClick={()=> { setMessage('You just clicked Third Button') }} >Third Button</Button> </ButtonGroup> <h3>{message}</h3> </div> );} export default App;", "e": 27042, "s": 26071, "text": null }, { "code": null, "e": 27155, "s": 27042, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27165, "s": 27155, "text": "npm start" }, { "code": null, "e": 27264, "s": 27165, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27275, "s": 27264, "text": "JavaScript" }, { "code": null, "e": 27283, "s": 27275, "text": "ReactJS" }, { "code": null, "e": 27300, "s": 27283, "text": "Web Technologies" }, { "code": null, "e": 27398, "s": 27300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27407, "s": 27398, "text": "Comments" }, { "code": null, "e": 27420, "s": 27407, "text": "Old Comments" }, { "code": null, "e": 27481, "s": 27420, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27522, "s": 27481, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27576, "s": 27522, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27633, "s": 27576, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27695, "s": 27633, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27738, "s": 27695, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27783, "s": 27738, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27848, "s": 27783, "text": "How to pass data from child component to its parent in ReactJS ?" } ]
{{ form.as_ul }} - Render Django Forms as list - GeeksforGeeks
13 Feb, 2020 Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article, Form is rendered as list in the template. Illustration of {{ form.as_ul }} using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Let’s create a sample Django Form to render it and show as an example. In geeks > forms.py, enter following code from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = "Enter 6 digit roll number" ) password = forms.CharField(widget = forms.PasswordInput()) Now we need a View to render this form into a template. Let’s create a view, from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, "home.html", context) Finally, we will create the template where we need the form to be placed. In templates > home.html, <form action = "" method = "post"> {% csrf_token %} <ul> {{ form.as_ul }} </ul> <input type="submit" value="Submit"></form> Here {{ form.as_ul }} will render them as list cells wrapped in <li> tags. Let’s check whether this is working acordingly or not. Open http://localhost:8000/ Let’s check the source code whether the form is rendered as a list or not. By rendering as a list it is meant that all input fields will be enclosed in <li> tags.Here is the demonstration, {{ form.as_table }} will render them as table cells wrapped in <tr> tags {{ form.as_p }} will render them wrapped in <p> tags NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists How To Convert Python Dictionary To JSON? Convert integer to string in Python
[ { "code": null, "e": 25747, "s": 25719, "text": "\n13 Feb, 2020" }, { "code": null, "e": 26140, "s": 25747, "text": "Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article, Form is rendered as list in the template." }, { "code": null, "e": 26257, "s": 26140, "text": "Illustration of {{ form.as_ul }} using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 26344, "s": 26257, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 26395, "s": 26344, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 26428, "s": 26395, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26541, "s": 26428, "text": "Let’s create a sample Django Form to render it and show as an example. In geeks > forms.py, enter following code" }, { "code": "from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = \"Enter 6 digit roll number\" ) password = forms.CharField(widget = forms.PasswordInput())", "e": 26898, "s": 26541, "text": null }, { "code": null, "e": 26975, "s": 26898, "text": "Now we need a View to render this form into a template. Let’s create a view," }, { "code": "from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, \"home.html\", context)", "e": 27185, "s": 26975, "text": null }, { "code": null, "e": 27285, "s": 27185, "text": "Finally, we will create the template where we need the form to be placed. In templates > home.html," }, { "code": "<form action = \"\" method = \"post\"> {% csrf_token %} <ul> {{ form.as_ul }} </ul> <input type=\"submit\" value=\"Submit\"></form>", "e": 27428, "s": 27285, "text": null }, { "code": null, "e": 27586, "s": 27428, "text": "Here {{ form.as_ul }} will render them as list cells wrapped in <li> tags. Let’s check whether this is working acordingly or not. Open http://localhost:8000/" }, { "code": null, "e": 27775, "s": 27586, "text": "Let’s check the source code whether the form is rendered as a list or not. By rendering as a list it is meant that all input fields will be enclosed in <li> tags.Here is the demonstration," }, { "code": null, "e": 27848, "s": 27775, "text": "{{ form.as_table }} will render them as table cells wrapped in <tr> tags" }, { "code": null, "e": 27901, "s": 27848, "text": "{{ form.as_p }} will render them wrapped in <p> tags" }, { "code": null, "e": 27913, "s": 27901, "text": "NaveenArora" }, { "code": null, "e": 27926, "s": 27913, "text": "Django-forms" }, { "code": null, "e": 27940, "s": 27926, "text": "Python Django" }, { "code": null, "e": 27947, "s": 27940, "text": "Python" }, { "code": null, "e": 28045, "s": 27947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28063, "s": 28045, "text": "Python Dictionary" }, { "code": null, "e": 28095, "s": 28063, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28117, "s": 28095, "text": "Enumerate() in Python" }, { "code": null, "e": 28159, "s": 28117, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28185, "s": 28159, "text": "Python String | replace()" }, { "code": null, "e": 28229, "s": 28185, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28258, "s": 28229, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28295, "s": 28258, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28337, "s": 28295, "text": "How To Convert Python Dictionary To JSON?" } ]
How to call a function using the OptionMenu widget in Tkinter?
Let's take an example and see how to call a function using OptionMenu widget in Tkinter. In the example, we will use a StringVar object and call its get() method. A StringVar object in Tkinter can help manage the value of a widget. We will create an OptionMenu widget and fill it with a list of strings. When the user selects an option, it will invoke a function which in turn will print the selected option as a label. Import the tkinter library and create an instance of tkinter frame. Import the tkinter library and create an instance of tkinter frame. Set the size of the frame using geometry method. Set the size of the frame using geometry method. Create a set of strings and save it in a variable, data. Create a set of strings and save it in a variable, data. Next, use the StringVar() constructor to create a StringVar object. It helps to manage the value of a widget, which is an OptionMenu in this case. Next, use the StringVar() constructor to create a StringVar object. It helps to manage the value of a widget, which is an OptionMenu in this case. Create a list of strings "options" and an OptionMenu. Set the values of the OptionMenu by passing the StringVar object and "options". Create a list of strings "options" and an OptionMenu. Set the values of the OptionMenu by passing the StringVar object and "options". Create a label to display the selected option from the OptionMenu. Create a label to display the selected option from the OptionMenu. Create a user-defined function "OptionMenu_Select" to print the selected item from the OptionMenu in the label. Create a user-defined function "OptionMenu_Select" to print the selected item from the OptionMenu in the label. Use the parameter command=OptionMenu_Select to invoke the user-defined function when the user selects an option. Use the parameter command=OptionMenu_Select to invoke the user-defined function when the user selects an option. Finally, run the mainloop of the application window. Finally, run the mainloop of the application window. # Import the tkinter library from tkinter import * # Create an instance of tkinter frame root = Tk() root.geometry("700x300") # Create the option and Check Button Event def OptionMenu_Select(event): label_city.config(text="You have selected: " + var.get()) # Create the variables var = StringVar(); var.set("Select a City") options = ["Mumbai", "Chennai", "Bhubaneswar", "Pune", "Patna", "Bhopal", "Surat", "Hyderabad", "New Delhi", "Lucknow"] OptionMenu(root, var, *(options), command=OptionMenu_Select).pack(pady=50) label_city=Label(root, font="Calibri,12,bold") label_city.pack(padx=20, pady=20) root.mainloop() It will produce the following output − When the user selects an option, it will display the selected option as a label −
[ { "code": null, "e": 1294, "s": 1062, "text": "Let's take an example and see how to call a function using OptionMenu widget in Tkinter. In the example, we will use a StringVar object and call its get() method. A StringVar object in Tkinter can help manage the value of a widget." }, { "code": null, "e": 1482, "s": 1294, "text": "We will create an OptionMenu widget and fill it with a list of strings. When the user selects an option, it will invoke a function which in turn will print the selected option as a label." }, { "code": null, "e": 1550, "s": 1482, "text": "Import the tkinter library and create an instance of tkinter frame." }, { "code": null, "e": 1618, "s": 1550, "text": "Import the tkinter library and create an instance of tkinter frame." }, { "code": null, "e": 1667, "s": 1618, "text": "Set the size of the frame using geometry method." }, { "code": null, "e": 1716, "s": 1667, "text": "Set the size of the frame using geometry method." }, { "code": null, "e": 1773, "s": 1716, "text": "Create a set of strings and save it in a variable, data." }, { "code": null, "e": 1830, "s": 1773, "text": "Create a set of strings and save it in a variable, data." }, { "code": null, "e": 1977, "s": 1830, "text": "Next, use the StringVar() constructor to create a StringVar object. It helps to manage the value of a widget, which is an OptionMenu in this case." }, { "code": null, "e": 2124, "s": 1977, "text": "Next, use the StringVar() constructor to create a StringVar object. It helps to manage the value of a widget, which is an OptionMenu in this case." }, { "code": null, "e": 2258, "s": 2124, "text": "Create a list of strings \"options\" and an OptionMenu. Set the values of the OptionMenu by passing the StringVar object and \"options\"." }, { "code": null, "e": 2392, "s": 2258, "text": "Create a list of strings \"options\" and an OptionMenu. Set the values of the OptionMenu by passing the StringVar object and \"options\"." }, { "code": null, "e": 2459, "s": 2392, "text": "Create a label to display the selected option from the OptionMenu." }, { "code": null, "e": 2526, "s": 2459, "text": "Create a label to display the selected option from the OptionMenu." }, { "code": null, "e": 2638, "s": 2526, "text": "Create a user-defined function \"OptionMenu_Select\" to print the selected item from the OptionMenu in the label." }, { "code": null, "e": 2750, "s": 2638, "text": "Create a user-defined function \"OptionMenu_Select\" to print the selected item from the OptionMenu in the label." }, { "code": null, "e": 2863, "s": 2750, "text": "Use the parameter command=OptionMenu_Select to invoke the user-defined function when the user selects an option." }, { "code": null, "e": 2976, "s": 2863, "text": "Use the parameter command=OptionMenu_Select to invoke the user-defined function when the user selects an option." }, { "code": null, "e": 3029, "s": 2976, "text": "Finally, run the mainloop of the application window." }, { "code": null, "e": 3082, "s": 3029, "text": "Finally, run the mainloop of the application window." }, { "code": null, "e": 3704, "s": 3082, "text": "# Import the tkinter library\nfrom tkinter import *\n\n# Create an instance of tkinter frame\nroot = Tk()\nroot.geometry(\"700x300\")\n\n# Create the option and Check Button Event\ndef OptionMenu_Select(event):\nlabel_city.config(text=\"You have selected: \" + var.get())\n\n# Create the variables\nvar = StringVar();\nvar.set(\"Select a City\")\n\noptions = [\"Mumbai\", \"Chennai\", \"Bhubaneswar\", \"Pune\", \"Patna\", \"Bhopal\", \"Surat\", \"Hyderabad\", \"New Delhi\", \"Lucknow\"]\nOptionMenu(root, var, *(options), command=OptionMenu_Select).pack(pady=50)\n\nlabel_city=Label(root, font=\"Calibri,12,bold\")\nlabel_city.pack(padx=20, pady=20)\n\nroot.mainloop()" }, { "code": null, "e": 3743, "s": 3704, "text": "It will produce the following output −" }, { "code": null, "e": 3825, "s": 3743, "text": "When the user selects an option, it will display the selected option\nas a label −" } ]
Explain Java command line arguments.
You can pass n number of arguments from the command line while executing the program, separating them with spaces. java ClassName 10 20 30 . . . . . The main method accepts/reads the values you have passed into an array of the type String. public class public static void main(String[] args){ } These arguments are known as command line arguments. After writing a Java program we will compile it using the command javac and run it using the command javas. Consider the following code − public class Sample{ public static void main(String[] args){ int a = 20; int b = 30; int c = a+b; System.out.println("Sum of the two numbers is "+c); } } We would compile and run it from command line as shown below − Here, we are hard coding (fixing to a specific value) the values of a and b which is not recommendable. To handle this, you can accept parameters from user using classes from I/O package or Scanner. Another way is to use command line arguments. In the following example we are rewriting the above program, by accepting the (two integer) values from the command line. And, we are extracting these two from the String array in the main method and converting them to integer − public class Sample { public static void main(String[] args){ int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = a+b; System.out.println("Sum of the two numbers is "+c); } } You can compile and, run the program by passing the values at execution line through command prompt as shown below:
[ { "code": null, "e": 1177, "s": 1062, "text": "You can pass n number of arguments from the command line while executing the program, separating them with spaces." }, { "code": null, "e": 1211, "s": 1177, "text": "java ClassName 10 20 30 . . . . ." }, { "code": null, "e": 1302, "s": 1211, "text": "The main method accepts/reads the values you have passed into an array of the type String." }, { "code": null, "e": 1360, "s": 1302, "text": "public class\n public static void main(String[] args){\n}" }, { "code": null, "e": 1413, "s": 1360, "text": "These arguments are known as command line arguments." }, { "code": null, "e": 1551, "s": 1413, "text": "After writing a Java program we will compile it using the command javac and run it using the command javas. Consider the following code −" }, { "code": null, "e": 1735, "s": 1551, "text": "public class Sample{\n public static void main(String[] args){\n int a = 20;\n int b = 30;\n int c = a+b;\n System.out.println(\"Sum of the two numbers is \"+c);\n }\n}" }, { "code": null, "e": 1798, "s": 1735, "text": "We would compile and run it from command line as shown below −" }, { "code": null, "e": 1997, "s": 1798, "text": "Here, we are hard coding (fixing to a specific value) the values of a and b which is not recommendable. To handle this, you can accept parameters from user using classes from I/O package or Scanner." }, { "code": null, "e": 2043, "s": 1997, "text": "Another way is to use command line arguments." }, { "code": null, "e": 2272, "s": 2043, "text": "In the following example we are rewriting the above program, by accepting the (two integer) values from the command line. And, we are extracting these two from the String array in the main method and converting them to integer −" }, { "code": null, "e": 2503, "s": 2272, "text": "public class Sample {\n public static void main(String[] args){\n int a = Integer.parseInt(args[0]);\n int b = Integer.parseInt(args[1]);\n int c = a+b;\n System.out.println(\"Sum of the two numbers is \"+c);\n }\n}" }, { "code": null, "e": 2619, "s": 2503, "text": "You can compile and, run the program by passing the values at execution line through command prompt as shown below:" } ]
Find maximum values & position in columns and rows of a Dataframe in Pandas - GeeksforGeeks
16 Feb, 2022 In this article, we are going to discuss how to find maximum value and its index position in columns and rows of a Dataframe. DataFrame.max() Pandas dataframe.max() method finds the maximum of the values in the object and returns it. If the input is a series, the method will return a scalar which will be the maximum of the values in the series. If the input is a dataframe, then the method will return a series with a maximum of values over the specified axis in the dataframe. The index axis is the default axis taken by this method. Syntax : DataFrame.max(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)Parameters : axis : {index (0), columns (1)} skipna : Exclude NA/null values when computing the result level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.Returns : max : Series or DataFrame (if level specified) Let’s take an example of how to use this function. Let’s suppose we have a Dataframe Python3 import numpy as npimport pandas as pd# List of Tuplesmatrix = [(10, 56, 17), (np.NaN, 23, 11), (49, 36, 55), (75, np.NaN, 34), (89, 21, 44) ]# Create a DataFrameabc = pd.DataFrame(matrix, index = list('abcde'), columns = list('xyz')) # outputabc Output: How to find the Maximum values of every column? To find the maximum value of each column, call the max() method on the Dataframe object without taking any argument. Python3 # find the maximum of each columnmaxValues = abc.max() print(maxValues) Output : We can see that it returned a series of maximum values where the index is column name and values are the maxima from each column. How to find the maximum values of every row? To find the maximum value of each row, call the max() method on the Dataframe object with an argument axis = 1. Python3 # find the maximum values of each rowmaxValues = abc.max(axis = 1)print(maxValues) Output : We can see that it returned a series of maximum values where the index is row name and values are the maxima from each row. We can see that in the above examples NaN values are skipped while finding the maximum values in any axis. We can include NaN values as well if we want. How to find maximum values of every column without skipping NaN? Python3 # find maximum value of each# column without skipping NaNmaxValues = abc.max(skipna = False) print(maxValues) Output : By putting skipna=False we can include NaN values also. If any NaN value exists it will be considered as the maximum value. How to find maximum values of a single column or selected columns? To get the maximum value of a single column see the following example Python3 # find maximum value of a# single column 'x'maxClm = df['x'].max() print("Maximum value in column 'x': " )print(maxClm) Output : We have another way to find the maximum value of a column : Python3 # find maximum value of a# single column 'x'maxClm = df.max()['x'] The result will be the same as above. Output: A list of columns can also be passed instead of a single column to find the maximum values of specified columns Python3 # find maximum values of a list of columnsmaxValues = df[['x', 'z']].max() print("Maximum value in column 'x' & 'z': ")print(maxValues) Output : How to get a position of maximum values of every column? DataFrame.idxmax(): Pandas dataframe.idxmax() method returns index of first occurrence of maximum over requested axis. While finding the index of the maximum value across any index, all NA/null values are excluded. Syntax: DataFrame.idxmax(axis=0, skipna=True)Parameters : axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NAReturns : idxmax : Series Let’s take some examples to understand how to use it : How to get row index label of Maximum value in every column Python3 # find the index position of maximum# values in every columnmaxValueIndex = df.idxmax() print("Maximum values of columns are at row index position :")print(maxValueIndex) Output : It returns a series containing the column names as index and row as index labels where the maximum value exists in that column. How to find Column names of Maximum value in every row? Python3 # find the column name of maximum# values in every rowmaxValueIndex = df.idxmax(axis = 1) print("Max values of row are at following columns :")print(maxValueIndex) Output : It returns a series containing the rows index labels as index and column names as values where the maximum value exists in that row. surinderdawra388 reenadevi98412200 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 24969, "s": 24941, "text": "\n16 Feb, 2022" }, { "code": null, "e": 25095, "s": 24969, "text": "In this article, we are going to discuss how to find maximum value and its index position in columns and rows of a Dataframe." }, { "code": null, "e": 25111, "s": 25095, "text": "DataFrame.max()" }, { "code": null, "e": 25507, "s": 25111, "text": "Pandas dataframe.max() method finds the maximum of the values in the object and returns it. If the input is a series, the method will return a scalar which will be the maximum of the values in the series. If the input is a dataframe, then the method will return a series with a maximum of values over the specified axis in the dataframe. The index axis is the default axis taken by this method. " }, { "code": null, "e": 26018, "s": 25507, "text": "Syntax : DataFrame.max(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)Parameters : axis : {index (0), columns (1)} skipna : Exclude NA/null values when computing the result level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.Returns : max : Series or DataFrame (if level specified) " }, { "code": null, "e": 26104, "s": 26018, "text": "Let’s take an example of how to use this function. Let’s suppose we have a Dataframe " }, { "code": null, "e": 26112, "s": 26104, "text": "Python3" }, { "code": "import numpy as npimport pandas as pd# List of Tuplesmatrix = [(10, 56, 17), (np.NaN, 23, 11), (49, 36, 55), (75, np.NaN, 34), (89, 21, 44) ]# Create a DataFrameabc = pd.DataFrame(matrix, index = list('abcde'), columns = list('xyz')) # outputabc", "e": 26403, "s": 26112, "text": null }, { "code": null, "e": 26413, "s": 26403, "text": "Output: " }, { "code": null, "e": 26463, "s": 26415, "text": "How to find the Maximum values of every column?" }, { "code": null, "e": 26581, "s": 26463, "text": "To find the maximum value of each column, call the max() method on the Dataframe object without taking any argument. " }, { "code": null, "e": 26589, "s": 26581, "text": "Python3" }, { "code": "# find the maximum of each columnmaxValues = abc.max() print(maxValues)", "e": 26661, "s": 26589, "text": null }, { "code": null, "e": 26672, "s": 26661, "text": "Output : " }, { "code": null, "e": 26802, "s": 26672, "text": "We can see that it returned a series of maximum values where the index is column name and values are the maxima from each column." }, { "code": null, "e": 26847, "s": 26802, "text": "How to find the maximum values of every row?" }, { "code": null, "e": 26961, "s": 26847, "text": "To find the maximum value of each row, call the max() method on the Dataframe object with an argument axis = 1. " }, { "code": null, "e": 26969, "s": 26961, "text": "Python3" }, { "code": "# find the maximum values of each rowmaxValues = abc.max(axis = 1)print(maxValues)", "e": 27052, "s": 26969, "text": null }, { "code": null, "e": 27063, "s": 27052, "text": "Output : " }, { "code": null, "e": 27340, "s": 27063, "text": "We can see that it returned a series of maximum values where the index is row name and values are the maxima from each row. We can see that in the above examples NaN values are skipped while finding the maximum values in any axis. We can include NaN values as well if we want." }, { "code": null, "e": 27405, "s": 27340, "text": "How to find maximum values of every column without skipping NaN?" }, { "code": null, "e": 27413, "s": 27405, "text": "Python3" }, { "code": "# find maximum value of each# column without skipping NaNmaxValues = abc.max(skipna = False) print(maxValues)", "e": 27523, "s": 27413, "text": null }, { "code": null, "e": 27534, "s": 27523, "text": "Output : " }, { "code": null, "e": 27658, "s": 27534, "text": "By putting skipna=False we can include NaN values also. If any NaN value exists it will be considered as the maximum value." }, { "code": null, "e": 27725, "s": 27658, "text": "How to find maximum values of a single column or selected columns?" }, { "code": null, "e": 27796, "s": 27725, "text": "To get the maximum value of a single column see the following example " }, { "code": null, "e": 27804, "s": 27796, "text": "Python3" }, { "code": "# find maximum value of a# single column 'x'maxClm = df['x'].max() print(\"Maximum value in column 'x': \" )print(maxClm)", "e": 27924, "s": 27804, "text": null }, { "code": null, "e": 27935, "s": 27924, "text": "Output : " }, { "code": null, "e": 27996, "s": 27935, "text": "We have another way to find the maximum value of a column : " }, { "code": null, "e": 28004, "s": 27996, "text": "Python3" }, { "code": "# find maximum value of a# single column 'x'maxClm = df.max()['x']", "e": 28071, "s": 28004, "text": null }, { "code": null, "e": 28119, "s": 28071, "text": "The result will be the same as above. Output: " }, { "code": null, "e": 28232, "s": 28119, "text": "A list of columns can also be passed instead of a single column to find the maximum values of specified columns " }, { "code": null, "e": 28240, "s": 28232, "text": "Python3" }, { "code": "# find maximum values of a list of columnsmaxValues = df[['x', 'z']].max() print(\"Maximum value in column 'x' & 'z': \")print(maxValues)", "e": 28376, "s": 28240, "text": null }, { "code": null, "e": 28387, "s": 28376, "text": "Output : " }, { "code": null, "e": 28446, "s": 28389, "text": "How to get a position of maximum values of every column?" }, { "code": null, "e": 28662, "s": 28446, "text": "DataFrame.idxmax(): Pandas dataframe.idxmax() method returns index of first occurrence of maximum over requested axis. While finding the index of the maximum value across any index, all NA/null values are excluded. " }, { "code": null, "e": 28898, "s": 28662, "text": "Syntax: DataFrame.idxmax(axis=0, skipna=True)Parameters : axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NAReturns : idxmax : Series " }, { "code": null, "e": 28953, "s": 28898, "text": "Let’s take some examples to understand how to use it :" }, { "code": null, "e": 29015, "s": 28953, "text": "How to get row index label of Maximum value in every column " }, { "code": null, "e": 29023, "s": 29015, "text": "Python3" }, { "code": "# find the index position of maximum# values in every columnmaxValueIndex = df.idxmax() print(\"Maximum values of columns are at row index position :\")print(maxValueIndex)", "e": 29194, "s": 29023, "text": null }, { "code": null, "e": 29205, "s": 29194, "text": "Output : " }, { "code": null, "e": 29333, "s": 29205, "text": "It returns a series containing the column names as index and row as index labels where the maximum value exists in that column." }, { "code": null, "e": 29389, "s": 29333, "text": "How to find Column names of Maximum value in every row?" }, { "code": null, "e": 29397, "s": 29389, "text": "Python3" }, { "code": "# find the column name of maximum# values in every rowmaxValueIndex = df.idxmax(axis = 1) print(\"Max values of row are at following columns :\")print(maxValueIndex)", "e": 29561, "s": 29397, "text": null }, { "code": null, "e": 29571, "s": 29561, "text": "Output : " }, { "code": null, "e": 29705, "s": 29571, "text": "It returns a series containing the rows index labels as index and column names as values where the maximum value exists in that row. " }, { "code": null, "e": 29722, "s": 29705, "text": "surinderdawra388" }, { "code": null, "e": 29740, "s": 29722, "text": "reenadevi98412200" }, { "code": null, "e": 29764, "s": 29740, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29778, "s": 29764, "text": "Python-pandas" }, { "code": null, "e": 29785, "s": 29778, "text": "Python" }, { "code": null, "e": 29883, "s": 29785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29892, "s": 29883, "text": "Comments" }, { "code": null, "e": 29905, "s": 29892, "text": "Old Comments" }, { "code": null, "e": 29923, "s": 29905, "text": "Python Dictionary" }, { "code": null, "e": 29958, "s": 29923, "text": "Read a file line by line in Python" }, { "code": null, "e": 29980, "s": 29958, "text": "Enumerate() in Python" }, { "code": null, "e": 30012, "s": 29980, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30042, "s": 30012, "text": "Iterate over a list in Python" }, { "code": null, "e": 30084, "s": 30042, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30110, "s": 30084, "text": "Python String | replace()" }, { "code": null, "e": 30147, "s": 30110, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30191, "s": 30147, "text": "Reading and Writing to text files in Python" } ]
Java Regex - MatchResult Interface
The java.util.regex.MatchResult interface represents the result of a match operation. This interface contains query methods used to determine the results of a match against a regular expression. The match boundaries, groups and group boundaries can be seen but not modified through a MatchResult. Following is the declaration for java.util.regex.MatchResult interface − public interface MatchResult Returns the offset after the last character matched. Returns the offset after the last character of the subsequence captured by the given group during this match. Returns the input subsequence matched by the previous match. Returns the input subsequence captured by the given group during the previous match operation. Returns the number of capturing groups in this match result's pattern. Returns the start index of the match. Returns the start index of the subsequence captured by the given group during this match. Print Add Notes Bookmark this page
[ { "code": null, "e": 2421, "s": 2124, "text": "The java.util.regex.MatchResult interface represents the result of a match operation. This interface contains query methods used to determine the results of a match against a regular expression. The match boundaries, groups and group boundaries can be seen but not modified through a MatchResult." }, { "code": null, "e": 2494, "s": 2421, "text": "Following is the declaration for java.util.regex.MatchResult interface −" }, { "code": null, "e": 2524, "s": 2494, "text": "public interface MatchResult\n" }, { "code": null, "e": 2577, "s": 2524, "text": "Returns the offset after the last character matched." }, { "code": null, "e": 2687, "s": 2577, "text": "Returns the offset after the last character of the subsequence captured by the given group during this match." }, { "code": null, "e": 2748, "s": 2687, "text": "Returns the input subsequence matched by the previous match." }, { "code": null, "e": 2843, "s": 2748, "text": "Returns the input subsequence captured by the given group during the previous match operation." }, { "code": null, "e": 2914, "s": 2843, "text": "Returns the number of capturing groups in this match result's pattern." }, { "code": null, "e": 2952, "s": 2914, "text": "Returns the start index of the match." }, { "code": null, "e": 3042, "s": 2952, "text": "Returns the start index of the subsequence captured by the given group during this match." }, { "code": null, "e": 3049, "s": 3042, "text": " Print" }, { "code": null, "e": 3060, "s": 3049, "text": " Add Notes" } ]
Distributed Deep Learning Training with Horovod on Kubernetes | by Yifeng Jiang | Towards Data Science
You may have noticed that even a powerful machine like the Nvidia DGX is not fast enough to train a deep learning model quick enough. Not mentioning the long wait time just to copy data into the DGX. Datasets are getting larger, GPUs are disaggregated from storage, workers with GPUs need to coordinate for model checkpointing and log saving. Your system may grow beyond a single server, team wants to share both GPU hardware and data easily. Enter distributed training with Horovod on Kubernetes. In this blog, I will walk through the setups to train a deep learning model in multi-worker distributed environment with Horovod on Kubernetes. Horovod is a distributed deep learning training framework for TensorFlow, Keras, PyTorch, and Apache MXNet. Open sourced by Uber, Horovod has proved that with little code change it scales a single-GPU training to run across many GPUs in parallel. As an example, I will train a movie review sentiment model using Horovod with TensorFlow and Keras. Although Keras itself supports distributed training natively, I found it a little more complex and less stable comparing to Horovod. Often time, customers ask me how to allocate and manage the schedule of GPUs to team members in such an environment. This becomes more important in a multi-server environment. I have heard solutions like time table in Excel (awful, but still surprisingly common), Python scripts, Kubernetes and commercial softwares. I will use Kubernetes because it supports a nice interface to run many application containers, including deep learning, on top of a cluster. A fast shared storage/filesystem is critical to simplify distributed training. It is the glue that holds together the different stages of your machine learning workflows, and it enables teams to share both GPU hardware and data. I will use FlashBlade S3 for hosting the dataset, and FlashBlade NFS for checkpointing and storing TensorBoard logs. The below is the architecture of this setup: In a multi-worker Horovod setup, a single primary and multiple worker nodes coordinates to train the model in parallel. It uses MPI and SSH to exchange and update model parameters. One way to run Horovid on Kubernetes is to use kubeflow and its mpi-job library, I found it is overkilled to introduce Kubeflow just for this purpose. Kubeflow itself is a big project. For now, let’s keep it simple. We need to install MTP and SSH first. Horovod provides an official Docker file for this. I have customised it to fit my needs. While MPI and SSH setup can be put into the Docker image, we do need to configure passwordless SSH authentication for the Horovod pods. Not a hard requirement but to make the example more concise, I use a Kubernetes persistent volume (PV) to store my SSH configuration and mount it on all containers at /root/.ssh. apiVersion: v1kind: PersistentVolumeClaimmetadata: name: horovod-ssh-sharedspec: accessModes: - ReadWriteMany resources: requests: storage: 1Gi storageClassName: pure-file Note the PV is a pure-file class (backed by FlashBlade NFS) with ReadWriteMany access mode. The same way, I also create another PV called tf-shared for checkpointing and TensorBoard logs. I mount these PVs to all the containers: volumeMounts: - name: horovod-ssh-vol mountPath: /root/.ssh - name: tf-shared-vol mountPath: /tf/models I use Kubernetes Init Container to run a init-ssh.sh script to generate the SSH passwordless authentication configuration before the Horovod primary container starts. initContainers:- name: init-sshimage: uprush/horovod-cpu:latestvolumeMounts: - name: horovod-ssh-vol mountPath: /root/.sshcommand: ['/bin/bash', '/root/init-ssh.sh'] The content of the init-ssh.sh is something like this: if [ -f /root/.ssh/authorized_keys ]then echo "SSH already configured."else ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys chmod 700 /root/.ssh chmod 600 /root/.ssh/authorized_keysfi I then declare two Kubernetes Deployments: one for the primary, another for workers. While the primary does nothing, the workers start a SSH server in the pod. - name: horovod-cpu image: "uprush/horovod-cpu:latest" command: [ "sh", "-c", "/usr/sbin/sshd -p 2222; sleep infinity" ] With these, root user on the primary pod can SSH to the workers without password. Horovod setup is ready. My dataset is stored in FlashBlade S3 as TensorFlow record files. I want my TensorFlow script to directly access it instead of downloading to local directory. So I added several environment variables using Kubernetes Secret to the deployments: env:- name: AWS_ACCESS_KEY_ID valueFrom: secretKeyRef: name: tf-s3 key: access-key- name: AWS_SECRET_ACCESS_KEY valueFrom: secretKeyRef: name: tf-s3 key: secret-key- name: S3_ENDPOINT value: 192.168.170.11- name: S3_USE_HTTPS value: "0" Later in my TensorFlow script, I will use these variables for S3 authentication: endpoint_url = f"http://{os.environ['S3_ENDPOINT']}"kwargs = {'endpoint_url':endpoint_url}s3 = s3fs.S3FileSystem(anon=False, client_kwargs=kwargs)# List all training tfrecord filestraining_files_list = s3.ls("s3://datasets/aclImdb/train/")training_files = [f"s3://{f}" for f in training_files_list]# Now let's create tf datasetstraining_ds = tf.data.TFRecordDataset(training_files, num_parallel_reads=AUTO) FlashBlade S3 is very fast, a minimum deploy can go up to 7GB/s read throughput at around 3ms latency consistently. This should be good enough for many DL training workloads. To let Kubernetes schedule the pod based on GPU resource requests, we need to install the Nvidia k8s device plugin. It is required to use nvidia-docker2 package instead of regular docker as default runtime. Follow the README on how to prepare your GPU nodes. The device plugin installation is straightforward using helm. In my lab, I only install the plugin on nodes with Tesla GPUs on them. So I added Node Label to my GPU nodes. kubectl label nodes fb-ubuntu01 nvidia.com/gpu.family=teslahelm install \ --version=0.6.0 \ --generate-name \ --set compatWithCPUManager=true \ --set nodeSelector."nvidia\.com/gpu\.family"=tesla \ nvdp/nvidia-device-plugin The plugin will be installed as a DaemonSet in kube-system namespace. If everything went well, the GPU nodes should now have GPU capacity: kubectl describe node fb-ubuntu01Capacity: cpu: 32 ephemeral-storage: 292889880Ki hugepages-1Gi: 0 hugepages-2Mi: 0 memory: 264092356Ki nvidia.com/gpu: 1 pods: 110 We can then request GPU resource for Horovod pods: resources: limits: nvidia.com/gpu: 2 # requesting 2 GPUs Next I use a pre-train script to prepare the environment for training. The script uses Kubernetes CLI to select Horovod pods and then do the followings: Generate a pip-install.sh script to install Python dependencies on all pods. Generate a horovod-run.sh script to start the Horovod job. Copy source code and generated scripts from my workstation to the shared PV of the Horovod primary pod. After running the pre-train.sh script, my primary pod will have these files in the shared PV: root@horovod-primary-84fcd7bdfd-2j8tc:/tf/models/examples# lshorovod-run.sh imdb-sentiment.py pip-install.sh pre-train.sh requirements.txt Here is an example of a generated horovod-run.sh: mkdir -p /tf/models/aclImdb/checkpointsAWS_LOG_LEVEL=3 horovodrun -np 3 \ -H localhost:1,10-244-1-129.default.pod:1,10-244-0-145.default.pod:1 \ -p 2222 \ python imdb-sentiment.py This script runs the training job on three pods in parallel, with each pod using 1 CPU. Here we don’t use GPUs because the model is very small. Because everything is automated, each time I change the training code in my VSCode (I use the Remote extension to write code on the server over SSH), I run the following to start the training job: Run the pre-train.sh script to regenerate and copy source code.Enter to Horovod primary pod.Run pip-install.sh to install dependencies on all pods.Run horovod-run.sh to start Horovod training job. Run the pre-train.sh script to regenerate and copy source code. Enter to Horovod primary pod. Run pip-install.sh to install dependencies on all pods. Run horovod-run.sh to start Horovod training job. So far this workflow works well for me. The modifications to the training script required to use Horovod with TensorFlow is well documented here. My example code is an end-to-end runnable script to train a movie review sentiment model. It is similar to single-node training except: The code runs on all Horovod pods in parallel. Each pod only processes parts of the total number of training and validation batches, so shard the dataset (use tf.data.Dataset.shard()) and set steps_per_epoch and validation_steps properly when calling model.fit. Some tasks, such as saving checkpoints, TensorBoard logs and the model, should be taken care to only run on the primary pod (hvd.rank() = 0) to prevent other workers from corrupting them. Because the pods can run on any server (GPU nodes only if requesting GPU resource) in the Kubernetes cluster, we should save checkpoints, TensorBoard logs and the model in a persistent volume (FlashBlade NFS in my example) or object storage (e.g., FlashBlade S3). I will skip the details of the training code here. Please refer to my example code. The below is a running output: If I look at my Kubernetes monitoring UI, I can see all the Horovod pods’ CPU usage jumps up. This indicates the training job was running on all the pods in parallel. Distributed training is the future of deep learning. Using Horovod and Kubernetes, we demonstrated the steps to quickly spin up a dynamic distributed deep learning training environment. This enables deep learning engineers and researchers to easily share, schedule and fully leverage the expensive GPUs and the data. A shared storage like FlashBlade plays an important role in this setup. FlashBlade makes it possible to share the resource and data. It relieves me from saving/aggregating checkpoints, TensorBoard logs and the models. Horovod with Kubernetes and FlashBlade just makes my deep learning life much easier. No more time table in Excel!
[ { "code": null, "e": 615, "s": 172, "text": "You may have noticed that even a powerful machine like the Nvidia DGX is not fast enough to train a deep learning model quick enough. Not mentioning the long wait time just to copy data into the DGX. Datasets are getting larger, GPUs are disaggregated from storage, workers with GPUs need to coordinate for model checkpointing and log saving. Your system may grow beyond a single server, team wants to share both GPU hardware and data easily." }, { "code": null, "e": 814, "s": 615, "text": "Enter distributed training with Horovod on Kubernetes. In this blog, I will walk through the setups to train a deep learning model in multi-worker distributed environment with Horovod on Kubernetes." }, { "code": null, "e": 1061, "s": 814, "text": "Horovod is a distributed deep learning training framework for TensorFlow, Keras, PyTorch, and Apache MXNet. Open sourced by Uber, Horovod has proved that with little code change it scales a single-GPU training to run across many GPUs in parallel." }, { "code": null, "e": 1294, "s": 1061, "text": "As an example, I will train a movie review sentiment model using Horovod with TensorFlow and Keras. Although Keras itself supports distributed training natively, I found it a little more complex and less stable comparing to Horovod." }, { "code": null, "e": 1752, "s": 1294, "text": "Often time, customers ask me how to allocate and manage the schedule of GPUs to team members in such an environment. This becomes more important in a multi-server environment. I have heard solutions like time table in Excel (awful, but still surprisingly common), Python scripts, Kubernetes and commercial softwares. I will use Kubernetes because it supports a nice interface to run many application containers, including deep learning, on top of a cluster." }, { "code": null, "e": 2098, "s": 1752, "text": "A fast shared storage/filesystem is critical to simplify distributed training. It is the glue that holds together the different stages of your machine learning workflows, and it enables teams to share both GPU hardware and data. I will use FlashBlade S3 for hosting the dataset, and FlashBlade NFS for checkpointing and storing TensorBoard logs." }, { "code": null, "e": 2143, "s": 2098, "text": "The below is the architecture of this setup:" }, { "code": null, "e": 2540, "s": 2143, "text": "In a multi-worker Horovod setup, a single primary and multiple worker nodes coordinates to train the model in parallel. It uses MPI and SSH to exchange and update model parameters. One way to run Horovid on Kubernetes is to use kubeflow and its mpi-job library, I found it is overkilled to introduce Kubeflow just for this purpose. Kubeflow itself is a big project. For now, let’s keep it simple." }, { "code": null, "e": 2982, "s": 2540, "text": "We need to install MTP and SSH first. Horovod provides an official Docker file for this. I have customised it to fit my needs. While MPI and SSH setup can be put into the Docker image, we do need to configure passwordless SSH authentication for the Horovod pods. Not a hard requirement but to make the example more concise, I use a Kubernetes persistent volume (PV) to store my SSH configuration and mount it on all containers at /root/.ssh." }, { "code": null, "e": 3169, "s": 2982, "text": "apiVersion: v1kind: PersistentVolumeClaimmetadata: name: horovod-ssh-sharedspec: accessModes: - ReadWriteMany resources: requests: storage: 1Gi storageClassName: pure-file" }, { "code": null, "e": 3398, "s": 3169, "text": "Note the PV is a pure-file class (backed by FlashBlade NFS) with ReadWriteMany access mode. The same way, I also create another PV called tf-shared for checkpointing and TensorBoard logs. I mount these PVs to all the containers:" }, { "code": null, "e": 3510, "s": 3398, "text": "volumeMounts: - name: horovod-ssh-vol mountPath: /root/.ssh - name: tf-shared-vol mountPath: /tf/models" }, { "code": null, "e": 3677, "s": 3510, "text": "I use Kubernetes Init Container to run a init-ssh.sh script to generate the SSH passwordless authentication configuration before the Horovod primary container starts." }, { "code": null, "e": 3847, "s": 3677, "text": "initContainers:- name: init-sshimage: uprush/horovod-cpu:latestvolumeMounts: - name: horovod-ssh-vol mountPath: /root/.sshcommand: ['/bin/bash', '/root/init-ssh.sh']" }, { "code": null, "e": 3902, "s": 3847, "text": "The content of the init-ssh.sh is something like this:" }, { "code": null, "e": 4158, "s": 3902, "text": "if [ -f /root/.ssh/authorized_keys ]then echo \"SSH already configured.\"else ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys chmod 700 /root/.ssh chmod 600 /root/.ssh/authorized_keysfi" }, { "code": null, "e": 4318, "s": 4158, "text": "I then declare two Kubernetes Deployments: one for the primary, another for workers. While the primary does nothing, the workers start a SSH server in the pod." }, { "code": null, "e": 4445, "s": 4318, "text": "- name: horovod-cpu image: \"uprush/horovod-cpu:latest\" command: [ \"sh\", \"-c\", \"/usr/sbin/sshd -p 2222; sleep infinity\" ]" }, { "code": null, "e": 4551, "s": 4445, "text": "With these, root user on the primary pod can SSH to the workers without password. Horovod setup is ready." }, { "code": null, "e": 4795, "s": 4551, "text": "My dataset is stored in FlashBlade S3 as TensorFlow record files. I want my TensorFlow script to directly access it instead of downloading to local directory. So I added several environment variables using Kubernetes Secret to the deployments:" }, { "code": null, "e": 5062, "s": 4795, "text": "env:- name: AWS_ACCESS_KEY_ID valueFrom: secretKeyRef: name: tf-s3 key: access-key- name: AWS_SECRET_ACCESS_KEY valueFrom: secretKeyRef: name: tf-s3 key: secret-key- name: S3_ENDPOINT value: 192.168.170.11- name: S3_USE_HTTPS value: \"0\"" }, { "code": null, "e": 5143, "s": 5062, "text": "Later in my TensorFlow script, I will use these variables for S3 authentication:" }, { "code": null, "e": 5550, "s": 5143, "text": "endpoint_url = f\"http://{os.environ['S3_ENDPOINT']}\"kwargs = {'endpoint_url':endpoint_url}s3 = s3fs.S3FileSystem(anon=False, client_kwargs=kwargs)# List all training tfrecord filestraining_files_list = s3.ls(\"s3://datasets/aclImdb/train/\")training_files = [f\"s3://{f}\" for f in training_files_list]# Now let's create tf datasetstraining_ds = tf.data.TFRecordDataset(training_files, num_parallel_reads=AUTO)" }, { "code": null, "e": 5725, "s": 5550, "text": "FlashBlade S3 is very fast, a minimum deploy can go up to 7GB/s read throughput at around 3ms latency consistently. This should be good enough for many DL training workloads." }, { "code": null, "e": 6156, "s": 5725, "text": "To let Kubernetes schedule the pod based on GPU resource requests, we need to install the Nvidia k8s device plugin. It is required to use nvidia-docker2 package instead of regular docker as default runtime. Follow the README on how to prepare your GPU nodes. The device plugin installation is straightforward using helm. In my lab, I only install the plugin on nodes with Tesla GPUs on them. So I added Node Label to my GPU nodes." }, { "code": null, "e": 6394, "s": 6156, "text": "kubectl label nodes fb-ubuntu01 nvidia.com/gpu.family=teslahelm install \\ --version=0.6.0 \\ --generate-name \\ --set compatWithCPUManager=true \\ --set nodeSelector.\"nvidia\\.com/gpu\\.family\"=tesla \\ nvdp/nvidia-device-plugin" }, { "code": null, "e": 6533, "s": 6394, "text": "The plugin will be installed as a DaemonSet in kube-system namespace. If everything went well, the GPU nodes should now have GPU capacity:" }, { "code": null, "e": 6760, "s": 6533, "text": "kubectl describe node fb-ubuntu01Capacity: cpu: 32 ephemeral-storage: 292889880Ki hugepages-1Gi: 0 hugepages-2Mi: 0 memory: 264092356Ki nvidia.com/gpu: 1 pods: 110" }, { "code": null, "e": 6811, "s": 6760, "text": "We can then request GPU resource for Horovod pods:" }, { "code": null, "e": 6872, "s": 6811, "text": "resources: limits: nvidia.com/gpu: 2 # requesting 2 GPUs" }, { "code": null, "e": 7025, "s": 6872, "text": "Next I use a pre-train script to prepare the environment for training. The script uses Kubernetes CLI to select Horovod pods and then do the followings:" }, { "code": null, "e": 7102, "s": 7025, "text": "Generate a pip-install.sh script to install Python dependencies on all pods." }, { "code": null, "e": 7161, "s": 7102, "text": "Generate a horovod-run.sh script to start the Horovod job." }, { "code": null, "e": 7265, "s": 7161, "text": "Copy source code and generated scripts from my workstation to the shared PV of the Horovod primary pod." }, { "code": null, "e": 7359, "s": 7265, "text": "After running the pre-train.sh script, my primary pod will have these files in the shared PV:" }, { "code": null, "e": 7502, "s": 7359, "text": "root@horovod-primary-84fcd7bdfd-2j8tc:/tf/models/examples# lshorovod-run.sh imdb-sentiment.py pip-install.sh pre-train.sh requirements.txt" }, { "code": null, "e": 7552, "s": 7502, "text": "Here is an example of a generated horovod-run.sh:" }, { "code": null, "e": 7732, "s": 7552, "text": "mkdir -p /tf/models/aclImdb/checkpointsAWS_LOG_LEVEL=3 horovodrun -np 3 \\ -H localhost:1,10-244-1-129.default.pod:1,10-244-0-145.default.pod:1 \\ -p 2222 \\ python imdb-sentiment.py" }, { "code": null, "e": 7876, "s": 7732, "text": "This script runs the training job on three pods in parallel, with each pod using 1 CPU. Here we don’t use GPUs because the model is very small." }, { "code": null, "e": 8073, "s": 7876, "text": "Because everything is automated, each time I change the training code in my VSCode (I use the Remote extension to write code on the server over SSH), I run the following to start the training job:" }, { "code": null, "e": 8270, "s": 8073, "text": "Run the pre-train.sh script to regenerate and copy source code.Enter to Horovod primary pod.Run pip-install.sh to install dependencies on all pods.Run horovod-run.sh to start Horovod training job." }, { "code": null, "e": 8334, "s": 8270, "text": "Run the pre-train.sh script to regenerate and copy source code." }, { "code": null, "e": 8364, "s": 8334, "text": "Enter to Horovod primary pod." }, { "code": null, "e": 8420, "s": 8364, "text": "Run pip-install.sh to install dependencies on all pods." }, { "code": null, "e": 8470, "s": 8420, "text": "Run horovod-run.sh to start Horovod training job." }, { "code": null, "e": 8510, "s": 8470, "text": "So far this workflow works well for me." }, { "code": null, "e": 8616, "s": 8510, "text": "The modifications to the training script required to use Horovod with TensorFlow is well documented here." }, { "code": null, "e": 8752, "s": 8616, "text": "My example code is an end-to-end runnable script to train a movie review sentiment model. It is similar to single-node training except:" }, { "code": null, "e": 8799, "s": 8752, "text": "The code runs on all Horovod pods in parallel." }, { "code": null, "e": 9014, "s": 8799, "text": "Each pod only processes parts of the total number of training and validation batches, so shard the dataset (use tf.data.Dataset.shard()) and set steps_per_epoch and validation_steps properly when calling model.fit." }, { "code": null, "e": 9202, "s": 9014, "text": "Some tasks, such as saving checkpoints, TensorBoard logs and the model, should be taken care to only run on the primary pod (hvd.rank() = 0) to prevent other workers from corrupting them." }, { "code": null, "e": 9466, "s": 9202, "text": "Because the pods can run on any server (GPU nodes only if requesting GPU resource) in the Kubernetes cluster, we should save checkpoints, TensorBoard logs and the model in a persistent volume (FlashBlade NFS in my example) or object storage (e.g., FlashBlade S3)." }, { "code": null, "e": 9550, "s": 9466, "text": "I will skip the details of the training code here. Please refer to my example code." }, { "code": null, "e": 9581, "s": 9550, "text": "The below is a running output:" }, { "code": null, "e": 9748, "s": 9581, "text": "If I look at my Kubernetes monitoring UI, I can see all the Horovod pods’ CPU usage jumps up. This indicates the training job was running on all the pods in parallel." }, { "code": null, "e": 10065, "s": 9748, "text": "Distributed training is the future of deep learning. Using Horovod and Kubernetes, we demonstrated the steps to quickly spin up a dynamic distributed deep learning training environment. This enables deep learning engineers and researchers to easily share, schedule and fully leverage the expensive GPUs and the data." }, { "code": null, "e": 10368, "s": 10065, "text": "A shared storage like FlashBlade plays an important role in this setup. FlashBlade makes it possible to share the resource and data. It relieves me from saving/aggregating checkpoints, TensorBoard logs and the models. Horovod with Kubernetes and FlashBlade just makes my deep learning life much easier." } ]
Frog Position After T Seconds in C++
Suppose we have one undirected tree consisting of n vertices. The vertices are numbered from 1 to n. Now a frog starts jumping from the vertex 1. The frog can jump from its current vertex to another non-visited vertex if they are adjacent, in one second. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices it jumps randomly to one of them where the probability is same, otherwise, when the frog can not jump to any non-visited vertex it jumps forever on the same vertex. The tree is given as an array of edges. We have to find the probability that after t seconds the frog is on the vertex target. So, if the input is like n is 7, t is 2, target is 4 and the tree is like − then the output will be 0.1666, as from the graph. The frog starts at vertex 1, jumping with 0.3333 probability to the vertex 2 after second 1 and then jumping with 0.5 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 0.3333 * 0.5 = 1.6665. To solve this, we will follow these steps − ret := 1 ret := 1 Define one set visited Define one set visited Define a function dfs(), this will take node, start, a list of edges g, time, t, one stack st, Define a function dfs(), this will take node, start, a list of edges g, time, t, one stack st, if node is member of visited, then −return false if node is member of visited, then − return false return false insert node into visited insert node into visited if node is same as 1, then −tt := time, ok := truereturn true if node is same as 1, then − tt := time, ok := true tt := time, ok := true return true return true for initialize i := 0, when i < size of g[node], update (increase i by 1), do −insert g[node, i] into stif dfs(g[node, i], start, g, time + 1, t, st) is true, then −return truedelete element from st for initialize i := 0, when i < size of g[node], update (increase i by 1), do − insert g[node, i] into st insert g[node, i] into st if dfs(g[node, i], start, g, time + 1, t, st) is true, then −return true if dfs(g[node, i], start, g, time + 1, t, st) is true, then − return true return true delete element from st delete element from st return false return false From the main method do the following − From the main method do the following − ret := 1 ret := 1 ok := false ok := false Define an array of lists graph of size n + 1 Define an array of lists graph of size n + 1 Define an array of lists graph2 of size n + 1 Define an array of lists graph2 of size n + 1 for initialize i := 0, when i < size of edges, update (increase i by 1), do −insert edges[i, 1] at the end of graph[edges[i, 0]]insert edges[i, 0] at the end of graph[edges[i, 1]] for initialize i := 0, when i < size of edges, update (increase i by 1), do − insert edges[i, 1] at the end of graph[edges[i, 0]] insert edges[i, 1] at the end of graph[edges[i, 0]] insert edges[i, 0] at the end of graph[edges[i, 1]] insert edges[i, 0] at the end of graph[edges[i, 1]] Define one stack st Define one stack st dfs(target, target, graph, 0, t, st) dfs(target, target, graph, 0, t, st) while (not st is empty), do −node := top element of stsz := size of graph[node]if node is not equal to 1, then −(decrease sz by 1)ret := ret * (1.0 / sz)delete element from st while (not st is empty), do − node := top element of st node := top element of st sz := size of graph[node] sz := size of graph[node] if node is not equal to 1, then −(decrease sz by 1) if node is not equal to 1, then − (decrease sz by 1) (decrease sz by 1) ret := ret * (1.0 / sz) ret := ret * (1.0 / sz) delete element from st delete element from st if tt > t, then −return 0 if tt > t, then − return 0 return 0 if tt is same as t, then −return ret if tt is same as t, then − return ret return ret if tt < t and target is same as 1 and size of graph[target] >= 1, then −return 0 if tt < t and target is same as 1 and size of graph[target] >= 1, then − return 0 return 0 return (if tt < t and size of graph[target] > 1, then 0, otherwise ret) return (if tt < t and size of graph[target] > 1, then 0, otherwise ret) Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: double ret = 1; bool ok; set<int> visited; int tt; bool dfs(int node, int start, vector<int> g[], int time, int t, stack<int>& st){ if (visited.count(node)) return false; visited.insert(node); if (node == 1) { tt = time; ok = true; return true; } for (int i = 0; i < g[node].size(); i++) { st.push(g[node][i]); if (dfs(g[node][i], start, g, time + 1, t, st)) return true; ; st.pop(); } return false; } double frogPosition(int n, vector<vector<int> >& edges, int t, int target){ ret = 1; ok = false; vector<int> graph[n + 1]; vector<int> graph2[n + 1]; for (int i = 0; i < edges.size(); i++) { graph[edges[i][0]].push_back(edges[i][1]); graph[edges[i][1]].push_back(edges[i][0]); } stack<int> st; dfs(target, target, graph, 0, t, st); while (!st.empty()) { int node = st.top(); double sz = (double)graph[node].size(); if (node != 1) sz--; ret *= (1.0 / sz); st.pop(); } if (tt > t) return 0; if (tt == t) return ret; if (tt < t && target == 1 && graph[target].size() >= 1) return 0; return tt < t && graph[target].size() > 1 ? 0 : ret; } }; main(){ Solution ob; vector<vector<int>> v = {{1,2},{1,3},{1,7},{2,4},{2,6},{3,5}}; cout << (ob.frogPosition(7,v,2,4)); } 7, {{1,2},{1,3},{1,7},{2,4},{2,6},{3,5}}, 2, 4 0.166667
[ { "code": null, "e": 1444, "s": 1062, "text": "Suppose we have one undirected tree consisting of n vertices. The vertices are numbered from 1 to n. Now a frog starts jumping from the vertex 1. The frog can jump from its current vertex to another non-visited vertex if they are adjacent, in one second. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices it jumps randomly to one of them" }, { "code": null, "e": 1576, "s": 1444, "text": "where the probability is same, otherwise, when the frog can not jump to any non-visited vertex it jumps forever on the same vertex." }, { "code": null, "e": 1703, "s": 1576, "text": "The tree is given as an array of edges. We have to find the probability that after t seconds the frog is on the vertex target." }, { "code": null, "e": 1779, "s": 1703, "text": "So, if the input is like n is 7, t is 2, target is 4 and the tree is like −" }, { "code": null, "e": 2083, "s": 1779, "text": "then the output will be 0.1666, as from the graph. The frog starts at vertex 1, jumping with 0.3333 probability to the vertex 2 after second 1 and then jumping with 0.5 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 0.3333 * 0.5 = 1.6665." }, { "code": null, "e": 2127, "s": 2083, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2136, "s": 2127, "text": "ret := 1" }, { "code": null, "e": 2145, "s": 2136, "text": "ret := 1" }, { "code": null, "e": 2168, "s": 2145, "text": "Define one set visited" }, { "code": null, "e": 2191, "s": 2168, "text": "Define one set visited" }, { "code": null, "e": 2286, "s": 2191, "text": "Define a function dfs(), this will take node, start, a list of edges g, time, t, one stack st," }, { "code": null, "e": 2381, "s": 2286, "text": "Define a function dfs(), this will take node, start, a list of edges g, time, t, one stack st," }, { "code": null, "e": 2430, "s": 2381, "text": "if node is member of visited, then −return false" }, { "code": null, "e": 2467, "s": 2430, "text": "if node is member of visited, then −" }, { "code": null, "e": 2480, "s": 2467, "text": "return false" }, { "code": null, "e": 2493, "s": 2480, "text": "return false" }, { "code": null, "e": 2518, "s": 2493, "text": "insert node into visited" }, { "code": null, "e": 2543, "s": 2518, "text": "insert node into visited" }, { "code": null, "e": 2605, "s": 2543, "text": "if node is same as 1, then −tt := time, ok := truereturn true" }, { "code": null, "e": 2634, "s": 2605, "text": "if node is same as 1, then −" }, { "code": null, "e": 2657, "s": 2634, "text": "tt := time, ok := true" }, { "code": null, "e": 2680, "s": 2657, "text": "tt := time, ok := true" }, { "code": null, "e": 2692, "s": 2680, "text": "return true" }, { "code": null, "e": 2704, "s": 2692, "text": "return true" }, { "code": null, "e": 2903, "s": 2704, "text": "for initialize i := 0, when i < size of g[node], update (increase i by 1), do −insert g[node, i] into stif dfs(g[node, i], start, g, time + 1, t, st) is true, then −return truedelete element from st" }, { "code": null, "e": 2983, "s": 2903, "text": "for initialize i := 0, when i < size of g[node], update (increase i by 1), do −" }, { "code": null, "e": 3009, "s": 2983, "text": "insert g[node, i] into st" }, { "code": null, "e": 3035, "s": 3009, "text": "insert g[node, i] into st" }, { "code": null, "e": 3108, "s": 3035, "text": "if dfs(g[node, i], start, g, time + 1, t, st) is true, then −return true" }, { "code": null, "e": 3170, "s": 3108, "text": "if dfs(g[node, i], start, g, time + 1, t, st) is true, then −" }, { "code": null, "e": 3182, "s": 3170, "text": "return true" }, { "code": null, "e": 3194, "s": 3182, "text": "return true" }, { "code": null, "e": 3217, "s": 3194, "text": "delete element from st" }, { "code": null, "e": 3240, "s": 3217, "text": "delete element from st" }, { "code": null, "e": 3253, "s": 3240, "text": "return false" }, { "code": null, "e": 3266, "s": 3253, "text": "return false" }, { "code": null, "e": 3306, "s": 3266, "text": "From the main method do the following −" }, { "code": null, "e": 3346, "s": 3306, "text": "From the main method do the following −" }, { "code": null, "e": 3355, "s": 3346, "text": "ret := 1" }, { "code": null, "e": 3364, "s": 3355, "text": "ret := 1" }, { "code": null, "e": 3376, "s": 3364, "text": "ok := false" }, { "code": null, "e": 3388, "s": 3376, "text": "ok := false" }, { "code": null, "e": 3433, "s": 3388, "text": "Define an array of lists graph of size n + 1" }, { "code": null, "e": 3478, "s": 3433, "text": "Define an array of lists graph of size n + 1" }, { "code": null, "e": 3524, "s": 3478, "text": "Define an array of lists graph2 of size n + 1" }, { "code": null, "e": 3570, "s": 3524, "text": "Define an array of lists graph2 of size n + 1" }, { "code": null, "e": 3750, "s": 3570, "text": "for initialize i := 0, when i < size of edges, update (increase i by 1), do −insert edges[i, 1] at the end of graph[edges[i, 0]]insert edges[i, 0] at the end of graph[edges[i, 1]]" }, { "code": null, "e": 3828, "s": 3750, "text": "for initialize i := 0, when i < size of edges, update (increase i by 1), do −" }, { "code": null, "e": 3880, "s": 3828, "text": "insert edges[i, 1] at the end of graph[edges[i, 0]]" }, { "code": null, "e": 3932, "s": 3880, "text": "insert edges[i, 1] at the end of graph[edges[i, 0]]" }, { "code": null, "e": 3984, "s": 3932, "text": "insert edges[i, 0] at the end of graph[edges[i, 1]]" }, { "code": null, "e": 4036, "s": 3984, "text": "insert edges[i, 0] at the end of graph[edges[i, 1]]" }, { "code": null, "e": 4056, "s": 4036, "text": "Define one stack st" }, { "code": null, "e": 4076, "s": 4056, "text": "Define one stack st" }, { "code": null, "e": 4113, "s": 4076, "text": "dfs(target, target, graph, 0, t, st)" }, { "code": null, "e": 4150, "s": 4113, "text": "dfs(target, target, graph, 0, t, st)" }, { "code": null, "e": 4326, "s": 4150, "text": "while (not st is empty), do −node := top element of stsz := size of graph[node]if node is not equal to 1, then −(decrease sz by 1)ret := ret * (1.0 / sz)delete element from st" }, { "code": null, "e": 4356, "s": 4326, "text": "while (not st is empty), do −" }, { "code": null, "e": 4382, "s": 4356, "text": "node := top element of st" }, { "code": null, "e": 4408, "s": 4382, "text": "node := top element of st" }, { "code": null, "e": 4434, "s": 4408, "text": "sz := size of graph[node]" }, { "code": null, "e": 4460, "s": 4434, "text": "sz := size of graph[node]" }, { "code": null, "e": 4512, "s": 4460, "text": "if node is not equal to 1, then −(decrease sz by 1)" }, { "code": null, "e": 4546, "s": 4512, "text": "if node is not equal to 1, then −" }, { "code": null, "e": 4565, "s": 4546, "text": "(decrease sz by 1)" }, { "code": null, "e": 4584, "s": 4565, "text": "(decrease sz by 1)" }, { "code": null, "e": 4608, "s": 4584, "text": "ret := ret * (1.0 / sz)" }, { "code": null, "e": 4632, "s": 4608, "text": "ret := ret * (1.0 / sz)" }, { "code": null, "e": 4655, "s": 4632, "text": "delete element from st" }, { "code": null, "e": 4678, "s": 4655, "text": "delete element from st" }, { "code": null, "e": 4704, "s": 4678, "text": "if tt > t, then −return 0" }, { "code": null, "e": 4722, "s": 4704, "text": "if tt > t, then −" }, { "code": null, "e": 4731, "s": 4722, "text": "return 0" }, { "code": null, "e": 4740, "s": 4731, "text": "return 0" }, { "code": null, "e": 4777, "s": 4740, "text": "if tt is same as t, then −return ret" }, { "code": null, "e": 4804, "s": 4777, "text": "if tt is same as t, then −" }, { "code": null, "e": 4815, "s": 4804, "text": "return ret" }, { "code": null, "e": 4826, "s": 4815, "text": "return ret" }, { "code": null, "e": 4907, "s": 4826, "text": "if tt < t and target is same as 1 and size of graph[target] >= 1, then −return 0" }, { "code": null, "e": 4980, "s": 4907, "text": "if tt < t and target is same as 1 and size of graph[target] >= 1, then −" }, { "code": null, "e": 4989, "s": 4980, "text": "return 0" }, { "code": null, "e": 4998, "s": 4989, "text": "return 0" }, { "code": null, "e": 5070, "s": 4998, "text": "return (if tt < t and size of graph[target] > 1, then 0, otherwise ret)" }, { "code": null, "e": 5142, "s": 5070, "text": "return (if tt < t and size of graph[target] > 1, then 0, otherwise ret)" }, { "code": null, "e": 5212, "s": 5142, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 5223, "s": 5212, "text": " Live Demo" }, { "code": null, "e": 6792, "s": 5223, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n double ret = 1;\n bool ok;\n set<int> visited;\n int tt;\n bool dfs(int node, int start, vector<int> g[], int time, int t,\n stack<int>& st){\n if (visited.count(node))\n return false;\n visited.insert(node);\n if (node == 1) {\n tt = time;\n ok = true;\n return true;\n }\n for (int i = 0; i < g[node].size(); i++) {\n st.push(g[node][i]);\n if (dfs(g[node][i], start, g, time + 1, t, st))\n return true;\n ;\n st.pop();\n }\n return false;\n }\n double frogPosition(int n, vector<vector<int> >& edges, int t,\n int target){\n ret = 1;\n ok = false;\n vector<int> graph[n + 1];\n vector<int> graph2[n + 1];\n for (int i = 0; i < edges.size(); i++) {\n graph[edges[i][0]].push_back(edges[i][1]);\n graph[edges[i][1]].push_back(edges[i][0]);\n }\n stack<int> st;\n dfs(target, target, graph, 0, t, st);\n while (!st.empty()) {\n int node = st.top();\n double sz = (double)graph[node].size();\n if (node != 1)\n sz--;\n ret *= (1.0 / sz);\n st.pop();\n }\n if (tt > t)\n return 0;\n if (tt == t)\n return ret;\n if (tt < t && target == 1 && graph[target].size() >= 1)\n return 0;\n return tt < t && graph[target].size() > 1 ? 0 : ret;\n }\n};\nmain(){\n Solution ob;\n vector<vector<int>> v = {{1,2},{1,3},{1,7},{2,4},{2,6},{3,5}};\n cout << (ob.frogPosition(7,v,2,4));\n}" }, { "code": null, "e": 6839, "s": 6792, "text": "7, {{1,2},{1,3},{1,7},{2,4},{2,6},{3,5}}, 2, 4" }, { "code": null, "e": 6848, "s": 6839, "text": "0.166667" } ]
How to schedule local notifications in Android?
This example demonstrate about How to schedule local notification in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <? xml version = "1.0" encoding = "utf-8" ?> <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 = "16dp" tools :context = ".MainActivity" /> Step 3 − Add the following code to res/menu/main_menu.xml. <? xml version = "1.0" encoding = "utf-8" ?> <menu xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: app = "http://schemas.android.com/apk/res-auto" > <item android :id = "@+id/action_5" app :showAsAction = "never" android :title = "5 seconds" /> <item android :id = "@+id/action_10" app :showAsAction = "never" android :title = "10 seconds" /> <item android :id = "@+id/action_30" app :showAsAction = "never" android :title = "30 seconds" /> </menu> Step 4 − Add the following code to src/MainActivity. package app.tutorialspoint.com.notifyme ; import android.app.AlarmManager ; import android.app.Notification ; import android.app.NotificationManager ; import android.app.PendingIntent ; import android.content.Context ; import android.content.Intent ; import android.os.Bundle ; import android.os.SystemClock ; import android.support.v4.app.NotificationCompat ; import android.support.v7.app.AppCompatActivity ; import android.view.Menu ; import android.view.MenuItem ; public class MainActivity extends AppCompatActivity { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } @Override public boolean onCreateOptionsMenu (Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu. menu_main , menu) ; return true; } @Override public boolean onOptionsItemSelected (MenuItem item) { switch (item.getItemId()) { case R.id. action_5 : scheduleNotification(getNotification( "5 second delay" ) , 5000 ) ; return true; case R.id. action_10 : scheduleNotification(getNotification( "10 second delay" ) , 10000 ) ; return true; case R.id. action_30 : scheduleNotification(getNotification( "30 second delay" ) , 30000 ) ; return true; default : return super .onOptionsItemSelected(item) ; } } private void scheduleNotification (Notification notification , int delay) { Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ; notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ; notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ; PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ; long futureInMillis = SystemClock. elapsedRealtime () + delay ; AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ; assert alarmManager != null; alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , futureInMillis , pendingIntent) ; } private Notification getNotification (String content) { NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ; builder.setContentTitle( "Scheduled Notification" ) ; builder.setContentText(content) ; builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; builder.setAutoCancel( true ) ; builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; return builder.build() ; } } Step 5 − Add the following code to src/MyNotificationPublisher. package app.tutorialspoint.com.notifyme ; import android.app.Notification ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.content.BroadcastReceiver ; import android.content.Context ; import android.content.Intent ; import static app.tutorialspoint.com.notifyme.MainActivity. NOTIFICATION_CHANNEL_ID ; public class MyNotificationPublisher extends BroadcastReceiver { public static String NOTIFICATION_ID = "notification-id" ; public static String NOTIFICATION = "notification" ; public void onReceive (Context context , Intent intent) { NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context. NOTIFICATION_SERVICE ) ; Notification notification = intent.getParcelableExtra( NOTIFICATION ) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; assert notificationManager != null; notificationManager.createNotificationChannel(notificationChannel) ; } int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ; assert notificationManager != null; notificationManager.notify(id , notification) ; } } Step 6 − 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.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <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> <receiver android :name = ".MyNotificationPublisher" /> </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": 1140, "s": 1062, "text": "This example demonstrate about How to schedule local notification in android." }, { "code": null, "e": 1269, "s": 1140, "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": 1334, "s": 1269, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1663, "s": 1334, "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 = \"16dp\"\n tools :context = \".MainActivity\" />" }, { "code": null, "e": 1722, "s": 1663, "text": "Step 3 − Add the following code to res/menu/main_menu.xml." }, { "code": null, "e": 2258, "s": 1722, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<menu xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\" >\n <item\n android :id = \"@+id/action_5\"\n app :showAsAction = \"never\"\n android :title = \"5 seconds\" />\n <item\n android :id = \"@+id/action_10\"\n app :showAsAction = \"never\"\n android :title = \"10 seconds\" />\n <item\n android :id = \"@+id/action_30\"\n app :showAsAction = \"never\"\n android :title = \"30 seconds\" />\n</menu>" }, { "code": null, "e": 2311, "s": 2258, "text": "Step 4 − Add the following code to src/MainActivity." }, { "code": null, "e": 5229, "s": 2311, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.AlarmManager ;\nimport android.app.Notification ;\nimport android.app.NotificationManager ;\nimport android.app.PendingIntent ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.os.SystemClock ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.Menu ;\nimport android.view.MenuItem ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n @Override\n public boolean onCreateOptionsMenu (Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu. menu_main , menu) ;\n return true;\n }\n @Override\n public boolean onOptionsItemSelected (MenuItem item) {\n switch (item.getItemId()) {\n case R.id. action_5 :\n scheduleNotification(getNotification( \"5 second delay\" ) , 5000 ) ;\n return true;\n case R.id. action_10 :\n scheduleNotification(getNotification( \"10 second delay\" ) , 10000 ) ;\n return true;\n case R.id. action_30 :\n scheduleNotification(getNotification( \"30 second delay\" ) , 30000 ) ;\n return true;\n default :\n return super .onOptionsItemSelected(item) ;\n }\n }\n private void scheduleNotification (Notification notification , int delay) {\n Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ;\n notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ;\n notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ;\n PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ;\n long futureInMillis = SystemClock. elapsedRealtime () + delay ;\n AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ;\n assert alarmManager != null;\n alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , futureInMillis , pendingIntent) ;\n }\n private Notification getNotification (String content) {\n NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ;\n builder.setContentTitle( \"Scheduled Notification\" ) ;\n builder.setContentText(content) ;\n builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n builder.setAutoCancel( true ) ;\n builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n return builder.build() ;\n }\n}" }, { "code": null, "e": 5293, "s": 5229, "text": "Step 5 − Add the following code to src/MyNotificationPublisher." }, { "code": null, "e": 6684, "s": 5293, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.Notification ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.content.BroadcastReceiver ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport static app.tutorialspoint.com.notifyme.MainActivity. NOTIFICATION_CHANNEL_ID ;\npublic class MyNotificationPublisher extends BroadcastReceiver {\n public static String NOTIFICATION_ID = \"notification-id\" ;\n public static String NOTIFICATION = \"notification\" ;\n public void onReceive (Context context , Intent intent) {\n NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context. NOTIFICATION_SERVICE ) ;\n Notification notification = intent.getParcelableExtra( NOTIFICATION ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n assert notificationManager != null;\n notificationManager.createNotificationChannel(notificationChannel) ;\n }\n int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ;\n assert notificationManager != null;\n notificationManager.notify(id , notification) ;\n }\n}" }, { "code": null, "e": 6739, "s": 6684, "text": "Step 6 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 7599, "s": 6739, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\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 <receiver android :name = \".MyNotificationPublisher\" />\n </application>\n</manifest>" }, { "code": null, "e": 7946, "s": 7599, "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": 7988, "s": 7946, "text": "Click here to download the project code" } ]
Using Plotly Express to Create Interactive Scatter Plots | by Andy McDonald | Towards Data Science
Scatter plots allow us to plot two variables from a dataset and compare them. From these plots, we can understand if there is a relationship between the two variables, and what the strength of that relationship is. Within petrophysics scatter plots, are commonly known as crossplots. They are routinely used as part of the petrophysical interpretation workflow and can be used for a variety of tasks, including: clay and shale endpoints identification for our clay or shale volume calculations outlier detection lithology identification hydrocarbon identification rock typing regression analysis and more Within this short tutorial, we are going to see how to generate scatter plots using a popular Python plotting library called Plotly. Plotly is a web-based toolkit that is used to generate powerful and interactive data visualisations. It is very efficient and plots can be generated with very few lines of code. It is a popular library that contains a wide range of charts, including statistical, financial, maps, machine learning, and much more. The Plotly library can be used in two main ways: Plotly Graph Objects, which is a low-level interface for creating figures, traces, and layouts Plotly Express, which is a high level wrapper around Plotly Graph Objects. Plotly Express allows users to type much simpler syntax to generate the same plot. And it is Plotly Express that we are going to focus on for this tutorial. Within the following tutorial, we are going to see how to: Create 2D Scatter Plots Coloured with Categorical Data Create 2D Scatter Plots Coloured with Continuous Data Set Axes to Logarithmic A video version of this tutorial is available on my YouTube channel: For this tutorial, we will be working with two libraries. Pandas, which is imported as pd and will be used to load and store our data, and Plotly Express, which is the main focus of this tutorial and will be used to generate interactive visualisations. import plotly.express as pximport pandas as pd Loading & Checking Data The dataset we will be using for this article comes from a Machine Learning competition for lithology prediction that was run by Xeek and FORCE (https://xeek.ai/challenges/force-well-logs/overview). The objective of the competition was to predict lithology from a dataset consisting 98 training wells each with varying degrees of log completeness. The objective was to predict lithofacies based on the log measurements. To download the file, navigate to the Data section of the link above. The original data source can be downloaded at: https://github.com/bolgebrygg/Force-2020-Machine-Learning-competition Once the data has been loaded in, we can view the dataframe by calling df . As you can see below the dataset has 18,270 rows and 30 columns, which makes it difficult to visualise in a single view. As a result, pandas truncates the number of columns that are presented. To view all of the columns we can call upon df.columns to view all of the available columns: Index(['WELL', 'DEPTH_MD', 'X_LOC', 'Y_LOC', 'Z_LOC', 'GROUP', 'FORMATION','CALI', 'RSHA', 'RMED', 'RDEP', 'RHOB', 'GR', 'SGR', 'NPHI', 'PEF','DTC', 'SP', 'BS', 'ROP', 'DTS', 'DCAL', 'DRHO', 'MUDWEIGHT', 'RMIC','ROPA', 'RXO', 'FORCE_2020_LITHOFACIES_LITHOLOGY', 'FORCE_2020_LITHOFACIES_CONFIDENCE', 'LITH'], dtype='object') Now that we can see all of our columns, we can easily call upon them if needed. Creating scatter plots with plotly express is very simple. We call upon px.scatter and pass in the dataframe, along with the keyword arguments for the x-axis and the y-axis. px.scatter(df, x='NPHI', y='RHOB') When we run the above code, we get a basic scatter plot of our density (RHOB) and neutron porosity (NPHI) data. When working with this type of data it is common to scale the y-axis (RHOB) from about 1.5 g/cc to about 3 g/cc, and to have the scale inverted so that the largest value is at the bottom and the smallest is at the top of the axis. For the x-axis, the data is usually scaled from -0.05 to 0.6, however, as we have data points in excess of 0.6 we will set the maximum to 1 (which represents 100% porosity). To achieve this, we need to pass in two arguments: range_x and range_y. To invert the y-axis, we can pass the highest number first followed by the smallest number like so: range_x=[3, 1.5]. Once we add in the range arguments, we will have the following code: px.scatter(df_well, x='NPHI', y='RHOB', range_x=[-0.05, 1], range_y=[3, 1]) There are situations where we want to display data on a logarithmic scale. This can be applied to a single axis or both. In the example below, we are using slightly different data. This data is obtained from core plug measurements that have been taken at specified intervals along a core sample. core_data = pd.read_csv('L05_09_CORE.csv')core_data Let’s now create a simple scatter plot known as a poro-perm crossplot. This type of plot is commonly used to analyse trends within core data and to derive a relationship between core measured porosity and permeability. This can then be applied to log-derived porosity to predict a continuous permeability. As before, creating the scatter plot is as simple as calling upon px.scatter. px.scatter(core_data, x='CPOR', y='CKH', color='CGD', range_color=[2.64, 2.7]) We can see that the generated plot doesn’t look right. That is because permeability (CKH) can range from values as low as 0.01 mD to 10’s of thousands of mD. To get a better understanding of the data we commonly display it on a logarithmic scale. To achieve this, we can add in an argument called log_y and then specify a logarithmic range we want to display the data. In this case we will set to between 0.01 and 1,000 mD. px.scatter(core_data, x='CPOR', y='CKH', log_y=[0.01, 1000]) To gain more insight into our data, we can add a third variable onto the scatter plot by setting it in the colour argument. In this example, we are going to pass in the GR (Gamma Ray) curve. px.scatter(df_well, x='NPHI', y='RHOB', range_x=[-0.05, 1], range_y=[3.5, 1], color='GR') As you can see the colour is a little subdued. That is due to the range for the GR curve extending from 0 to a value in excess of 400 API. Typically this type of data is in the range of 0 to 150 API. To bring out more detail from the third variable, we can change the colour range by setting a range_color argument to go from 0 to 150. px.scatter(df_well, x='NPHI', y='RHOB', range_x=[-0.05, 1], range_y=[3.5, 1], color='GR', range_color=[0,150]) We can also use categorical variables to visualise the trends within the data. This can easily be added to our scatter plot by passing the GROUP column from the dataframe into the color argument. px.scatter(df_well, x='NPHI', y='RHOB', range_x=[-0.05, 1], range_y=[3.5, 1], color='GROUP') If we only want to visualise a few groups, we can left-mouse click on the name in the legend and it will turn that group off. As seen in the above examples, Plotly Express is a powerful library for visualising data. It allows you to create very powerful and interactive plots with minimal amounts of code. Extra information in the form of colour can enhance our understanding of the data and how it is distributed amongst different categories or varies with another variable. Thanks for reading! If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub. If you want to get in touch you can find me on LinkedIn or at my website. Interested in learning more about python and well log data or petrophysics? Follow me on Medium. If you enjoy reading these tutorials and want to support me as a writer and creator, then please consider signing up to become a Medium member. It’s $5 a month and you get unlimited access to many thousands of articles on a wide range of topics. If you sign up using my link, I will earn a small commission with no extra cost to you!
[ { "code": null, "e": 387, "s": 172, "text": "Scatter plots allow us to plot two variables from a dataset and compare them. From these plots, we can understand if there is a relationship between the two variables, and what the strength of that relationship is." }, { "code": null, "e": 584, "s": 387, "text": "Within petrophysics scatter plots, are commonly known as crossplots. They are routinely used as part of the petrophysical interpretation workflow and can be used for a variety of tasks, including:" }, { "code": null, "e": 666, "s": 584, "text": "clay and shale endpoints identification for our clay or shale volume calculations" }, { "code": null, "e": 684, "s": 666, "text": "outlier detection" }, { "code": null, "e": 709, "s": 684, "text": "lithology identification" }, { "code": null, "e": 736, "s": 709, "text": "hydrocarbon identification" }, { "code": null, "e": 748, "s": 736, "text": "rock typing" }, { "code": null, "e": 768, "s": 748, "text": "regression analysis" }, { "code": null, "e": 777, "s": 768, "text": "and more" }, { "code": null, "e": 910, "s": 777, "text": "Within this short tutorial, we are going to see how to generate scatter plots using a popular Python plotting library called Plotly." }, { "code": null, "e": 1223, "s": 910, "text": "Plotly is a web-based toolkit that is used to generate powerful and interactive data visualisations. It is very efficient and plots can be generated with very few lines of code. It is a popular library that contains a wide range of charts, including statistical, financial, maps, machine learning, and much more." }, { "code": null, "e": 1272, "s": 1223, "text": "The Plotly library can be used in two main ways:" }, { "code": null, "e": 1367, "s": 1272, "text": "Plotly Graph Objects, which is a low-level interface for creating figures, traces, and layouts" }, { "code": null, "e": 1525, "s": 1367, "text": "Plotly Express, which is a high level wrapper around Plotly Graph Objects. Plotly Express allows users to type much simpler syntax to generate the same plot." }, { "code": null, "e": 1658, "s": 1525, "text": "And it is Plotly Express that we are going to focus on for this tutorial. Within the following tutorial, we are going to see how to:" }, { "code": null, "e": 1713, "s": 1658, "text": "Create 2D Scatter Plots Coloured with Categorical Data" }, { "code": null, "e": 1767, "s": 1713, "text": "Create 2D Scatter Plots Coloured with Continuous Data" }, { "code": null, "e": 1791, "s": 1767, "text": "Set Axes to Logarithmic" }, { "code": null, "e": 1860, "s": 1791, "text": "A video version of this tutorial is available on my YouTube channel:" }, { "code": null, "e": 2113, "s": 1860, "text": "For this tutorial, we will be working with two libraries. Pandas, which is imported as pd and will be used to load and store our data, and Plotly Express, which is the main focus of this tutorial and will be used to generate interactive visualisations." }, { "code": null, "e": 2160, "s": 2113, "text": "import plotly.express as pximport pandas as pd" }, { "code": null, "e": 2184, "s": 2160, "text": "Loading & Checking Data" }, { "code": null, "e": 2791, "s": 2184, "text": "The dataset we will be using for this article comes from a Machine Learning competition for lithology prediction that was run by Xeek and FORCE (https://xeek.ai/challenges/force-well-logs/overview). The objective of the competition was to predict lithology from a dataset consisting 98 training wells each with varying degrees of log completeness. The objective was to predict lithofacies based on the log measurements. To download the file, navigate to the Data section of the link above. The original data source can be downloaded at: https://github.com/bolgebrygg/Force-2020-Machine-Learning-competition" }, { "code": null, "e": 3060, "s": 2791, "text": "Once the data has been loaded in, we can view the dataframe by calling df . As you can see below the dataset has 18,270 rows and 30 columns, which makes it difficult to visualise in a single view. As a result, pandas truncates the number of columns that are presented." }, { "code": null, "e": 3153, "s": 3060, "text": "To view all of the columns we can call upon df.columns to view all of the available columns:" }, { "code": null, "e": 3482, "s": 3153, "text": "Index(['WELL', 'DEPTH_MD', 'X_LOC', 'Y_LOC', 'Z_LOC', 'GROUP', 'FORMATION','CALI', 'RSHA', 'RMED', 'RDEP', 'RHOB', 'GR', 'SGR', 'NPHI', 'PEF','DTC', 'SP', 'BS', 'ROP', 'DTS', 'DCAL', 'DRHO', 'MUDWEIGHT', 'RMIC','ROPA', 'RXO', 'FORCE_2020_LITHOFACIES_LITHOLOGY', 'FORCE_2020_LITHOFACIES_CONFIDENCE', 'LITH'], dtype='object')" }, { "code": null, "e": 3562, "s": 3482, "text": "Now that we can see all of our columns, we can easily call upon them if needed." }, { "code": null, "e": 3736, "s": 3562, "text": "Creating scatter plots with plotly express is very simple. We call upon px.scatter and pass in the dataframe, along with the keyword arguments for the x-axis and the y-axis." }, { "code": null, "e": 3771, "s": 3736, "text": "px.scatter(df, x='NPHI', y='RHOB')" }, { "code": null, "e": 3883, "s": 3771, "text": "When we run the above code, we get a basic scatter plot of our density (RHOB) and neutron porosity (NPHI) data." }, { "code": null, "e": 4114, "s": 3883, "text": "When working with this type of data it is common to scale the y-axis (RHOB) from about 1.5 g/cc to about 3 g/cc, and to have the scale inverted so that the largest value is at the bottom and the smallest is at the top of the axis." }, { "code": null, "e": 4288, "s": 4114, "text": "For the x-axis, the data is usually scaled from -0.05 to 0.6, however, as we have data points in excess of 0.6 we will set the maximum to 1 (which represents 100% porosity)." }, { "code": null, "e": 4478, "s": 4288, "text": "To achieve this, we need to pass in two arguments: range_x and range_y. To invert the y-axis, we can pass the highest number first followed by the smallest number like so: range_x=[3, 1.5]." }, { "code": null, "e": 4547, "s": 4478, "text": "Once we add in the range arguments, we will have the following code:" }, { "code": null, "e": 4623, "s": 4547, "text": "px.scatter(df_well, x='NPHI', y='RHOB', range_x=[-0.05, 1], range_y=[3, 1])" }, { "code": null, "e": 4744, "s": 4623, "text": "There are situations where we want to display data on a logarithmic scale. This can be applied to a single axis or both." }, { "code": null, "e": 4919, "s": 4744, "text": "In the example below, we are using slightly different data. This data is obtained from core plug measurements that have been taken at specified intervals along a core sample." }, { "code": null, "e": 4971, "s": 4919, "text": "core_data = pd.read_csv('L05_09_CORE.csv')core_data" }, { "code": null, "e": 5277, "s": 4971, "text": "Let’s now create a simple scatter plot known as a poro-perm crossplot. This type of plot is commonly used to analyse trends within core data and to derive a relationship between core measured porosity and permeability. This can then be applied to log-derived porosity to predict a continuous permeability." }, { "code": null, "e": 5355, "s": 5277, "text": "As before, creating the scatter plot is as simple as calling upon px.scatter." }, { "code": null, "e": 5434, "s": 5355, "text": "px.scatter(core_data, x='CPOR', y='CKH', color='CGD', range_color=[2.64, 2.7])" }, { "code": null, "e": 5681, "s": 5434, "text": "We can see that the generated plot doesn’t look right. That is because permeability (CKH) can range from values as low as 0.01 mD to 10’s of thousands of mD. To get a better understanding of the data we commonly display it on a logarithmic scale." }, { "code": null, "e": 5858, "s": 5681, "text": "To achieve this, we can add in an argument called log_y and then specify a logarithmic range we want to display the data. In this case we will set to between 0.01 and 1,000 mD." }, { "code": null, "e": 5919, "s": 5858, "text": "px.scatter(core_data, x='CPOR', y='CKH', log_y=[0.01, 1000])" }, { "code": null, "e": 6110, "s": 5919, "text": "To gain more insight into our data, we can add a third variable onto the scatter plot by setting it in the colour argument. In this example, we are going to pass in the GR (Gamma Ray) curve." }, { "code": null, "e": 6200, "s": 6110, "text": "px.scatter(df_well, x='NPHI', y='RHOB', range_x=[-0.05, 1], range_y=[3.5, 1], color='GR')" }, { "code": null, "e": 6536, "s": 6200, "text": "As you can see the colour is a little subdued. That is due to the range for the GR curve extending from 0 to a value in excess of 400 API. Typically this type of data is in the range of 0 to 150 API. To bring out more detail from the third variable, we can change the colour range by setting a range_color argument to go from 0 to 150." }, { "code": null, "e": 6647, "s": 6536, "text": "px.scatter(df_well, x='NPHI', y='RHOB', range_x=[-0.05, 1], range_y=[3.5, 1], color='GR', range_color=[0,150])" }, { "code": null, "e": 6843, "s": 6647, "text": "We can also use categorical variables to visualise the trends within the data. This can easily be added to our scatter plot by passing the GROUP column from the dataframe into the color argument." }, { "code": null, "e": 6936, "s": 6843, "text": "px.scatter(df_well, x='NPHI', y='RHOB', range_x=[-0.05, 1], range_y=[3.5, 1], color='GROUP')" }, { "code": null, "e": 7062, "s": 6936, "text": "If we only want to visualise a few groups, we can left-mouse click on the name in the legend and it will turn that group off." }, { "code": null, "e": 7412, "s": 7062, "text": "As seen in the above examples, Plotly Express is a powerful library for visualising data. It allows you to create very powerful and interactive plots with minimal amounts of code. Extra information in the form of colour can enhance our understanding of the data and how it is distributed amongst different categories or varies with another variable." }, { "code": null, "e": 7432, "s": 7412, "text": "Thanks for reading!" }, { "code": null, "e": 7644, "s": 7432, "text": "If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub." }, { "code": null, "e": 7718, "s": 7644, "text": "If you want to get in touch you can find me on LinkedIn or at my website." }, { "code": null, "e": 7815, "s": 7718, "text": "Interested in learning more about python and well log data or petrophysics? Follow me on Medium." } ]
Create your own Word Cloud. Learn to build a very simple word cloud... | by Gurucharan M K | Towards Data Science
Hi everybody! Haven’t all of us seen such interesting and new forms of word clouds being displayed and wondered if we could also generate such word clouds. What if I tell you it is possible with a Python Program comprising of not more than 20 lines of code. Let’s dive in! In this story, I am going to show you a very simple and concise code on how to build and generate a very simple word cloud from any text data. For generating this word cloud, I will be using a data set that was originally created for building a spam comment classifier. The file 'Youtube05-Shakira.csv' is a data set that consists of 5 columns such as the COMMENT ID, AUTHOR, DATE, CONTENT and CLASS. The ‘CONTENT’ and ‘CLASS’ columns are used to build a machine learning model to classify a message if it is a spam message or not. For generating our word cloud, I will be using only words in the ‘CONTENT’ column. The first step in any python program will always be on importing the libraries. For this code we will require only three libraries, out of which two should already have been installed in your Python workspace. The only library to be additionally installed before this program is the ‘wordcloud’ library which can be easily installed using the ‘pip’ command. # Importing the Librariesfrom wordcloud import WordCloud, STOPWORDSimport pandas as pdimport matplotlib.pyplot as plt In the next step, we will read the data file ( .csv file) and store in into a Pandas DataFrame. The pandas data frames are always easier and faster to use when working with large datasets. The column required for our word cloud generation can be easily accessed from the pandas data frame. # Read 'Youtube05-Shakira.csv' filedata = pd.read_csv(r"Youtube05-Shakira.csv", encoding ="latin-1") In this step, we initialize two important strings for our word cloud generation. The ‘comment_words’ is the string that will be used to store all the words of the CONTENT column in a single line of text The ‘stop_words’ is used to store all the words that are very commonly used in English language such as ‘the’, ‘a’, ‘an’, ‘in’. These words will be later filtered while generating the word cloud. Now that we have stored the data file into a pandas dataframe, we now have to convert each row of the ‘CONTENT’ column to a very long, single line of text. The first step in this will be to split each word in a row ( a comment has a finite number of words) and store it in a variable. separate = i.split() After splitting the words, for homogeneity of all the words, we convert all the words to lowercase using the .lower() function. Finally, we join all the words and store it to the variable ‘comment_words’ using the function .join() The variable ‘comment_words’ now contains all the words in a single long text necessary to generate our word cloud. # Iterating through the .csv data file for i in data.CONTENT: i = str(i) separate = i.split() for j in range(len(separate)): separate[j] = separate[j].lower() comment_words += " ".join(separate)+" " In this step, we finally generate the word cloud using the ‘WordCloud’ function. In this we will be using the two variables ‘stop_words’ and ‘comment_words’. The code is self-explanatory and easy to understand. # Creating the Word Cloudfinal_wordcloud = WordCloud(width = 800, height = 800, background_color ='black', stopwords = stop_words, min_font_size = 10).generate(comment_words) The last and final step is to display our word cloud that we just generated using the above code. The ‘matplotlib.pyplot’ library is used to display the word cloud. Take a look at the word cloud generated below! # Displaying the WordCloud plt.figure(figsize = (10, 10), facecolor = None) plt.imshow(final_wordcloud) plt.axis("off") plt.tight_layout(pad = 0) plt.show() Hurray! You have now understood how to generate a very simple and basic word cloud using Python and a few lines of code. You can now use this as a base to generate various shapes and types of Word Clouds! I’m sharing a link to my github repository where the entire code in the .ipynb file is available for you to work on! github.com Although, this isn't a part of Machine Learning, this is one of the most basic utilization of another important field of Artificial Intelligence, the Natural Language Processing (NLP). So, go ahead and experiment with this new field of NLP. Till then, Happy Machine Learning!
[ { "code": null, "e": 444, "s": 171, "text": "Hi everybody! Haven’t all of us seen such interesting and new forms of word clouds being displayed and wondered if we could also generate such word clouds. What if I tell you it is possible with a Python Program comprising of not more than 20 lines of code. Let’s dive in!" }, { "code": null, "e": 587, "s": 444, "text": "In this story, I am going to show you a very simple and concise code on how to build and generate a very simple word cloud from any text data." }, { "code": null, "e": 714, "s": 587, "text": "For generating this word cloud, I will be using a data set that was originally created for building a spam comment classifier." }, { "code": null, "e": 976, "s": 714, "text": "The file 'Youtube05-Shakira.csv' is a data set that consists of 5 columns such as the COMMENT ID, AUTHOR, DATE, CONTENT and CLASS. The ‘CONTENT’ and ‘CLASS’ columns are used to build a machine learning model to classify a message if it is a spam message or not." }, { "code": null, "e": 1059, "s": 976, "text": "For generating our word cloud, I will be using only words in the ‘CONTENT’ column." }, { "code": null, "e": 1417, "s": 1059, "text": "The first step in any python program will always be on importing the libraries. For this code we will require only three libraries, out of which two should already have been installed in your Python workspace. The only library to be additionally installed before this program is the ‘wordcloud’ library which can be easily installed using the ‘pip’ command." }, { "code": null, "e": 1535, "s": 1417, "text": "# Importing the Librariesfrom wordcloud import WordCloud, STOPWORDSimport pandas as pdimport matplotlib.pyplot as plt" }, { "code": null, "e": 1825, "s": 1535, "text": "In the next step, we will read the data file ( .csv file) and store in into a Pandas DataFrame. The pandas data frames are always easier and faster to use when working with large datasets. The column required for our word cloud generation can be easily accessed from the pandas data frame." }, { "code": null, "e": 1926, "s": 1825, "text": "# Read 'Youtube05-Shakira.csv' filedata = pd.read_csv(r\"Youtube05-Shakira.csv\", encoding =\"latin-1\")" }, { "code": null, "e": 2007, "s": 1926, "text": "In this step, we initialize two important strings for our word cloud generation." }, { "code": null, "e": 2129, "s": 2007, "text": "The ‘comment_words’ is the string that will be used to store all the words of the CONTENT column in a single line of text" }, { "code": null, "e": 2325, "s": 2129, "text": "The ‘stop_words’ is used to store all the words that are very commonly used in English language such as ‘the’, ‘a’, ‘an’, ‘in’. These words will be later filtered while generating the word cloud." }, { "code": null, "e": 2481, "s": 2325, "text": "Now that we have stored the data file into a pandas dataframe, we now have to convert each row of the ‘CONTENT’ column to a very long, single line of text." }, { "code": null, "e": 2631, "s": 2481, "text": "The first step in this will be to split each word in a row ( a comment has a finite number of words) and store it in a variable. separate = i.split()" }, { "code": null, "e": 2759, "s": 2631, "text": "After splitting the words, for homogeneity of all the words, we convert all the words to lowercase using the .lower() function." }, { "code": null, "e": 2978, "s": 2759, "text": "Finally, we join all the words and store it to the variable ‘comment_words’ using the function .join() The variable ‘comment_words’ now contains all the words in a single long text necessary to generate our word cloud." }, { "code": null, "e": 3207, "s": 2978, "text": "# Iterating through the .csv data file for i in data.CONTENT: i = str(i) separate = i.split() for j in range(len(separate)): separate[j] = separate[j].lower() comment_words += \" \".join(separate)+\" \"" }, { "code": null, "e": 3418, "s": 3207, "text": "In this step, we finally generate the word cloud using the ‘WordCloud’ function. In this we will be using the two variables ‘stop_words’ and ‘comment_words’. The code is self-explanatory and easy to understand." }, { "code": null, "e": 3641, "s": 3418, "text": "# Creating the Word Cloudfinal_wordcloud = WordCloud(width = 800, height = 800, background_color ='black', stopwords = stop_words, min_font_size = 10).generate(comment_words)" }, { "code": null, "e": 3853, "s": 3641, "text": "The last and final step is to display our word cloud that we just generated using the above code. The ‘matplotlib.pyplot’ library is used to display the word cloud. Take a look at the word cloud generated below!" }, { "code": null, "e": 4031, "s": 3853, "text": "# Displaying the WordCloud plt.figure(figsize = (10, 10), facecolor = None) plt.imshow(final_wordcloud) plt.axis(\"off\") plt.tight_layout(pad = 0) plt.show()" }, { "code": null, "e": 4236, "s": 4031, "text": "Hurray! You have now understood how to generate a very simple and basic word cloud using Python and a few lines of code. You can now use this as a base to generate various shapes and types of Word Clouds!" }, { "code": null, "e": 4353, "s": 4236, "text": "I’m sharing a link to my github repository where the entire code in the .ipynb file is available for you to work on!" }, { "code": null, "e": 4364, "s": 4353, "text": "github.com" } ]
Circular Reveal Animation in Android - GeeksforGeeks
23 Feb, 2021 Animations in Android play an important role in the user experience. This makes the user focus on the main content, which they want. And also helps in user interactivity. Animations communicate with the user to really get engaged in application usage. So in this article, one of the animations in android which is the most popular one, Circular reveal animation is discussed. Have a look at the following image to get an idea of how the circular animation looks like. Note that we are going to implement this project using the Kotlin language. Step 1: Create an empty activity project Create an empty activity Android Studio Project. Or refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project. Note that select Kotlin as the programming language. Step 2: Working with the activity_main.xml file To implement the application’s main layout in which includes only a single button, which when clicked on it triggers the Circular reveal animation. To implement the UI invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/mainLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:gravity="center" android:text="GeeksforGeeks" android:textColor="@color/green_500" android:textSize="24sp" android:textStyle="bold" /> <!--The layout which is invisible initially--> <LinearLayout android:id="@+id/revealLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/green_200" android:gravity="center" android:orientation="vertical" android:visibility="gone"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@android:color/white" android:text="LEARN PROGRAMMING" android:textColor="@android:color/black" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@android:color/white" android:text="CONTRIBUTE" android:textColor="@android:color/black" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@android:color/white" android:text="VISIT WEBSITE" android:textColor="@android:color/black" /> </LinearLayout> <!--The Fab to toggle the visibility of circular reveal animation--> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentBottom="true" android:layout_gravity="bottom|end" android:layout_marginEnd="16dp" android:layout_marginBottom="16dp" app:srcCompat="@drawable/ic_add" /> </RelativeLayout> Output UI: Step 3: Working with the MainActivity.kt file Firstly, the code is for the circular reveal animation from the right bottom of the screen. Invoke the following code and refer to its output for better understanding, the comments are added for better understanding. Kotlin import android.animation.Animatorimport android.annotation.SuppressLintimport android.content.res.ColorStateListimport android.os.Buildimport android.os.Bundleimport android.view.Viewimport android.view.ViewAnimationUtilsimport androidx.annotation.RequiresApiimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.res.ResourcesCompatimport com.google.android.material.floatingactionbutton.FloatingActionButtonimport kotlin.math.hypotimport kotlin.math.max class MainActivity : AppCompatActivity() { private lateinit var mRevealLayout: View private lateinit var mFab: FloatingActionButton // boolean variable to check whether the // reveal layout is visible or not private var isRevealed = false @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mRevealLayout = findViewById(R.id.revealLayout) mFab = findViewById(R.id.fab) // initially the color of the FAB should be green mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.green_500, null ) ) // upon clicking the FAB the reveal should be // toggled according to the boolean value mFab.setOnClickListener { revealLayoutFun() } } // this function is triggered when // the FAB is clicked @RequiresApi(Build.VERSION_CODES.M) @SuppressLint("ResourceAsColor") private fun revealLayoutFun() { // based on the boolean value the // reveal layout should be toggled if (!isRevealed) { // get the right and bottom side // lengths of the reveal layout val x: Int = mRevealLayout.right val y: Int = mRevealLayout.bottom // here the starting radius of the reveal // layout is 0 when it is not visible val startRadius = 0 // make the end radius should match // the while parent view val endRadius = hypot( mRevealLayout.width.toDouble(), mRevealLayout.height.toDouble() ).toInt() // and set the background tint of the FAB to white // color so that it can be visible mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.white, null ) ) // now set the icon as close for the FAB mFab.setImageResource(R.drawable.ic_close) // create the instance of the ViewAnimationUtils to // initiate the circular reveal animation val anim = ViewAnimationUtils.createCircularReveal( mRevealLayout, x, y, startRadius.toFloat(), endRadius.toFloat() ) // make the invisible reveal layout to visible // so that upon revealing it can be visible to user mRevealLayout.visibility = View.VISIBLE // now start the reveal animation anim.start() // set the boolean value to true as the reveal // layout is visible to the user isRevealed = true } else { // get the right and bottom side lengths // of the reveal layout val x: Int = mRevealLayout.right val y: Int = mRevealLayout.bottom // here the starting radius of the reveal layout is its full width val startRadius: Int = max(mRevealLayout.width, mRevealLayout.height) // and the end radius should be zero // at this point because the layout should be closed val endRadius = 0 // now set the background tint of the FAB to green // so that it can be visible to the user mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.green_500, null ) ) // now again set the icon of the FAB to plus mFab.setImageResource(R.drawable.ic_add) // create the instance of the ViewAnimationUtils to // initiate the circular reveal animation val anim = ViewAnimationUtils.createCircularReveal( mRevealLayout, x, y, startRadius.toFloat(), endRadius.toFloat() ) // now as soon as the animation is ending, the reveal // layout should also be closed anim.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animator: Animator) {} override fun onAnimationEnd(animator: Animator) { mRevealLayout.visibility = View.GONE } override fun onAnimationCancel(animator: Animator) {} override fun onAnimationRepeat(animator: Animator) {} }) // start the closing animation anim.start() // set the boolean variable to false // as the reveal layout is invisible isRevealed = false } }} Output: Note: The layout of the application remains same only the code from the MainActivity.kt file are changed. Invoke the following code inside the MainActivity.kt file to reveal the same layout from the center of the screen. Kotlin import android.animation.Animatorimport android.annotation.SuppressLintimport android.content.res.ColorStateListimport android.os.Buildimport android.os.Bundleimport android.view.Viewimport android.view.ViewAnimationUtilsimport androidx.annotation.RequiresApiimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.res.ResourcesCompatimport com.google.android.material.floatingactionbutton.FloatingActionButtonimport kotlin.math.hypotimport kotlin.math.max class MainActivity : AppCompatActivity() { private lateinit var mRevealLayout: View private lateinit var mFab: FloatingActionButton // boolean variable to check whether // the reveal layout is visible or not private var isRevealed = false @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mRevealLayout = findViewById(R.id.revealLayout) mFab = findViewById(R.id.fab) // initially the color of the FAB should be green mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.green_500, null ) ) // upon clicking the FAB the reveal should // be toggled according to the boolean value mFab.setOnClickListener { revealLayoutFun() } } // this function is triggered when // the FAB is clicked @RequiresApi(Build.VERSION_CODES.M) @SuppressLint("ResourceAsColor") private fun revealLayoutFun() { // based on the boolean value the // reveal layout should be toggled if (!isRevealed) { // get the right and bottom side // lengths of the reveal layout val x: Int = mRevealLayout.right / 2 val y: Int = mRevealLayout.bottom / 2 // here the starting radius of the reveal // layout is 0 when it is not visible val startRadius = 0 // make the end radius should // match the while parent view val endRadius = hypot( mRevealLayout.width.toDouble(), mRevealLayout.height.toDouble() ).toInt() // and set the background tint of the FAB to white // color so that it can be visible mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.white, null ) ) // now set the icon as close for the FAB mFab.setImageResource(R.drawable.ic_close) // create the instance of the ViewAnimationUtils to // initiate the circular reveal animation val anim = ViewAnimationUtils.createCircularReveal( mRevealLayout, x, y, startRadius.toFloat(), endRadius.toFloat() ) // make the invisible reveal layout to visible // so that upon revealing it can be visible to user mRevealLayout.visibility = View.VISIBLE // now start the reveal animation anim.start() // set the boolean value to true as the reveal // layout is visible to the user isRevealed = true } else { // get the right and bottom side lengths // of the reveal layout val x: Int = mRevealLayout.right / 2 val y: Int = mRevealLayout.bottom / 2 // here the starting radius of the reveal layout is its full width val startRadius: Int = max(mRevealLayout.width, mRevealLayout.height) // and the end radius should be zero at this // point because the layout should be closed val endRadius = 0 // now set the background tint of the FAB to green // so that it can be visible to the user mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.green_500, null ) ) // now again set the icon of the FAB to plus mFab.setImageResource(R.drawable.ic_add) // create the instance of the ViewAnimationUtils // to initiate the circular reveal animation val anim = ViewAnimationUtils.createCircularReveal( mRevealLayout, x, y, startRadius.toFloat(), endRadius.toFloat() ) // now as soon as the animation is ending, the reveal // layout should also be closed anim.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animator: Animator) {} override fun onAnimationEnd(animator: Animator) { mRevealLayout.visibility = View.GONE } override fun onAnimationCancel(animator: Animator) {} override fun onAnimationRepeat(animator: Animator) {} }) // start the closing animation anim.start() // set the boolean variable to false // as the reveal layout is invisible isRevealed = false } }} Output: Android-Animation Technical Scripter 2020 Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Read Data from SQLite Database in Android? Flutter - Custom Bottom Navigation Bar How to Change the Background Color After Clicking the Button in Android? Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25036, "s": 25008, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25581, "s": 25036, "text": "Animations in Android play an important role in the user experience. This makes the user focus on the main content, which they want. And also helps in user interactivity. Animations communicate with the user to really get engaged in application usage. So in this article, one of the animations in android which is the most popular one, Circular reveal animation is discussed. Have a look at the following image to get an idea of how the circular animation looks like. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 25622, "s": 25581, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 25863, "s": 25622, "text": "Create an empty activity Android Studio Project. Or refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project. Note that select Kotlin as the programming language." }, { "code": null, "e": 25911, "s": 25863, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26059, "s": 25911, "text": "To implement the application’s main layout in which includes only a single button, which when clicked on it triggers the Circular reveal animation." }, { "code": null, "e": 26140, "s": 26059, "text": "To implement the UI invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 26144, "s": 26140, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/mainLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:fitsSystemWindows=\"true\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:gravity=\"center\" android:text=\"GeeksforGeeks\" android:textColor=\"@color/green_500\" android:textSize=\"24sp\" android:textStyle=\"bold\" /> <!--The layout which is invisible initially--> <LinearLayout android:id=\"@+id/revealLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/green_200\" android:gravity=\"center\" android:orientation=\"vertical\" android:visibility=\"gone\"> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:backgroundTint=\"@android:color/white\" android:text=\"LEARN PROGRAMMING\" android:textColor=\"@android:color/black\" /> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:backgroundTint=\"@android:color/white\" android:text=\"CONTRIBUTE\" android:textColor=\"@android:color/black\" /> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:backgroundTint=\"@android:color/white\" android:text=\"VISIT WEBSITE\" android:textColor=\"@android:color/black\" /> </LinearLayout> <!--The Fab to toggle the visibility of circular reveal animation--> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id=\"@+id/fab\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentEnd=\"true\" android:layout_alignParentBottom=\"true\" android:layout_gravity=\"bottom|end\" android:layout_marginEnd=\"16dp\" android:layout_marginBottom=\"16dp\" app:srcCompat=\"@drawable/ic_add\" /> </RelativeLayout>", "e": 28596, "s": 26144, "text": null }, { "code": null, "e": 28607, "s": 28596, "text": "Output UI:" }, { "code": null, "e": 28653, "s": 28607, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 28745, "s": 28653, "text": "Firstly, the code is for the circular reveal animation from the right bottom of the screen." }, { "code": null, "e": 28870, "s": 28745, "text": "Invoke the following code and refer to its output for better understanding, the comments are added for better understanding." }, { "code": null, "e": 28877, "s": 28870, "text": "Kotlin" }, { "code": "import android.animation.Animatorimport android.annotation.SuppressLintimport android.content.res.ColorStateListimport android.os.Buildimport android.os.Bundleimport android.view.Viewimport android.view.ViewAnimationUtilsimport androidx.annotation.RequiresApiimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.res.ResourcesCompatimport com.google.android.material.floatingactionbutton.FloatingActionButtonimport kotlin.math.hypotimport kotlin.math.max class MainActivity : AppCompatActivity() { private lateinit var mRevealLayout: View private lateinit var mFab: FloatingActionButton // boolean variable to check whether the // reveal layout is visible or not private var isRevealed = false @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mRevealLayout = findViewById(R.id.revealLayout) mFab = findViewById(R.id.fab) // initially the color of the FAB should be green mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.green_500, null ) ) // upon clicking the FAB the reveal should be // toggled according to the boolean value mFab.setOnClickListener { revealLayoutFun() } } // this function is triggered when // the FAB is clicked @RequiresApi(Build.VERSION_CODES.M) @SuppressLint(\"ResourceAsColor\") private fun revealLayoutFun() { // based on the boolean value the // reveal layout should be toggled if (!isRevealed) { // get the right and bottom side // lengths of the reveal layout val x: Int = mRevealLayout.right val y: Int = mRevealLayout.bottom // here the starting radius of the reveal // layout is 0 when it is not visible val startRadius = 0 // make the end radius should match // the while parent view val endRadius = hypot( mRevealLayout.width.toDouble(), mRevealLayout.height.toDouble() ).toInt() // and set the background tint of the FAB to white // color so that it can be visible mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.white, null ) ) // now set the icon as close for the FAB mFab.setImageResource(R.drawable.ic_close) // create the instance of the ViewAnimationUtils to // initiate the circular reveal animation val anim = ViewAnimationUtils.createCircularReveal( mRevealLayout, x, y, startRadius.toFloat(), endRadius.toFloat() ) // make the invisible reveal layout to visible // so that upon revealing it can be visible to user mRevealLayout.visibility = View.VISIBLE // now start the reveal animation anim.start() // set the boolean value to true as the reveal // layout is visible to the user isRevealed = true } else { // get the right and bottom side lengths // of the reveal layout val x: Int = mRevealLayout.right val y: Int = mRevealLayout.bottom // here the starting radius of the reveal layout is its full width val startRadius: Int = max(mRevealLayout.width, mRevealLayout.height) // and the end radius should be zero // at this point because the layout should be closed val endRadius = 0 // now set the background tint of the FAB to green // so that it can be visible to the user mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.green_500, null ) ) // now again set the icon of the FAB to plus mFab.setImageResource(R.drawable.ic_add) // create the instance of the ViewAnimationUtils to // initiate the circular reveal animation val anim = ViewAnimationUtils.createCircularReveal( mRevealLayout, x, y, startRadius.toFloat(), endRadius.toFloat() ) // now as soon as the animation is ending, the reveal // layout should also be closed anim.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animator: Animator) {} override fun onAnimationEnd(animator: Animator) { mRevealLayout.visibility = View.GONE } override fun onAnimationCancel(animator: Animator) {} override fun onAnimationRepeat(animator: Animator) {} }) // start the closing animation anim.start() // set the boolean variable to false // as the reveal layout is invisible isRevealed = false } }}", "e": 34524, "s": 28877, "text": null }, { "code": null, "e": 34532, "s": 34524, "text": "Output:" }, { "code": null, "e": 34638, "s": 34532, "text": "Note: The layout of the application remains same only the code from the MainActivity.kt file are changed." }, { "code": null, "e": 34753, "s": 34638, "text": "Invoke the following code inside the MainActivity.kt file to reveal the same layout from the center of the screen." }, { "code": null, "e": 34760, "s": 34753, "text": "Kotlin" }, { "code": "import android.animation.Animatorimport android.annotation.SuppressLintimport android.content.res.ColorStateListimport android.os.Buildimport android.os.Bundleimport android.view.Viewimport android.view.ViewAnimationUtilsimport androidx.annotation.RequiresApiimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.res.ResourcesCompatimport com.google.android.material.floatingactionbutton.FloatingActionButtonimport kotlin.math.hypotimport kotlin.math.max class MainActivity : AppCompatActivity() { private lateinit var mRevealLayout: View private lateinit var mFab: FloatingActionButton // boolean variable to check whether // the reveal layout is visible or not private var isRevealed = false @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mRevealLayout = findViewById(R.id.revealLayout) mFab = findViewById(R.id.fab) // initially the color of the FAB should be green mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.green_500, null ) ) // upon clicking the FAB the reveal should // be toggled according to the boolean value mFab.setOnClickListener { revealLayoutFun() } } // this function is triggered when // the FAB is clicked @RequiresApi(Build.VERSION_CODES.M) @SuppressLint(\"ResourceAsColor\") private fun revealLayoutFun() { // based on the boolean value the // reveal layout should be toggled if (!isRevealed) { // get the right and bottom side // lengths of the reveal layout val x: Int = mRevealLayout.right / 2 val y: Int = mRevealLayout.bottom / 2 // here the starting radius of the reveal // layout is 0 when it is not visible val startRadius = 0 // make the end radius should // match the while parent view val endRadius = hypot( mRevealLayout.width.toDouble(), mRevealLayout.height.toDouble() ).toInt() // and set the background tint of the FAB to white // color so that it can be visible mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.white, null ) ) // now set the icon as close for the FAB mFab.setImageResource(R.drawable.ic_close) // create the instance of the ViewAnimationUtils to // initiate the circular reveal animation val anim = ViewAnimationUtils.createCircularReveal( mRevealLayout, x, y, startRadius.toFloat(), endRadius.toFloat() ) // make the invisible reveal layout to visible // so that upon revealing it can be visible to user mRevealLayout.visibility = View.VISIBLE // now start the reveal animation anim.start() // set the boolean value to true as the reveal // layout is visible to the user isRevealed = true } else { // get the right and bottom side lengths // of the reveal layout val x: Int = mRevealLayout.right / 2 val y: Int = mRevealLayout.bottom / 2 // here the starting radius of the reveal layout is its full width val startRadius: Int = max(mRevealLayout.width, mRevealLayout.height) // and the end radius should be zero at this // point because the layout should be closed val endRadius = 0 // now set the background tint of the FAB to green // so that it can be visible to the user mFab.backgroundTintList = ColorStateList.valueOf( ResourcesCompat.getColor( resources, R.color.green_500, null ) ) // now again set the icon of the FAB to plus mFab.setImageResource(R.drawable.ic_add) // create the instance of the ViewAnimationUtils // to initiate the circular reveal animation val anim = ViewAnimationUtils.createCircularReveal( mRevealLayout, x, y, startRadius.toFloat(), endRadius.toFloat() ) // now as soon as the animation is ending, the reveal // layout should also be closed anim.addListener(object : Animator.AnimatorListener { override fun onAnimationStart(animator: Animator) {} override fun onAnimationEnd(animator: Animator) { mRevealLayout.visibility = View.GONE } override fun onAnimationCancel(animator: Animator) {} override fun onAnimationRepeat(animator: Animator) {} }) // start the closing animation anim.start() // set the boolean variable to false // as the reveal layout is invisible isRevealed = false } }}", "e": 40419, "s": 34760, "text": null }, { "code": null, "e": 40427, "s": 40419, "text": "Output:" }, { "code": null, "e": 40445, "s": 40427, "text": "Android-Animation" }, { "code": null, "e": 40469, "s": 40445, "text": "Technical Scripter 2020" }, { "code": null, "e": 40477, "s": 40469, "text": "Android" }, { "code": null, "e": 40484, "s": 40477, "text": "Kotlin" }, { "code": null, "e": 40503, "s": 40484, "text": "Technical Scripter" }, { "code": null, "e": 40511, "s": 40503, "text": "Android" }, { "code": null, "e": 40609, "s": 40511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40618, "s": 40609, "text": "Comments" }, { "code": null, "e": 40631, "s": 40618, "text": "Old Comments" }, { "code": null, "e": 40673, "s": 40631, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 40711, "s": 40673, "text": "Android Listview in Java with Example" }, { "code": null, "e": 40761, "s": 40711, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 40800, "s": 40761, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 40873, "s": 40800, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 40892, "s": 40873, "text": "Android UI Layouts" }, { "code": null, "e": 40905, "s": 40892, "text": "Kotlin Array" }, { "code": null, "e": 40947, "s": 40905, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 40974, "s": 40947, "text": "Kotlin Setters and Getters" } ]
Bubble Sort Visualization using JavaScript - GeeksforGeeks
08 Feb, 2021 GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Bubble Sort using JavaScript. We will see how the elements are swapped in Bubble Sort and how we get the final sorted array. We will also visualize the time complexity of Bubble Sort. Refer: BubbleSort Asynchronous Function in JavaScript Approach: First, we will generate a random array using Math.random() function. Different colors are used to indicate which elements are being compared, sorted, and unsorted. Since the algorithm performs the operation very fast, the setTimeout() function has been used to slow down the process. New array can be generated by pressing the “Ctrl+R” key. The sorting is performed using BubbleSort() function using swap() function Example: Below is the program to visualize the Bubble Sort algorithm. index.html HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="style.css" /></head> <body> <br /> <p class="header">Bubble Sort</p> <div id="array"></div> <script src="script.js"></script></body> </html> style.css: The following is the content for “style.css” used in the above file. * { margin: 0px; padding: 0px; box-sizing: border-box;} .header { font-size: 20px; text-align: center;} #array { background-color: white; height: 413px; width: 598px; margin: auto; position: relative; margin-top: 64px;} .block { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease;} .block_id { position: absolute; color: black; margin-top: -20px; width: 100%; text-align: center;} script.js: The following is the content for “script.js” file used in the above HTML code. var container = document.getElementById("array"); // Function to generate the array of blocksfunction generatearray() { for (var i = 0; i < 20; i++) { // Return a value from 1 to 100 (both inclusive) var value = Math.ceil(Math.random() * 100); // Creating element div var array_ele = document.createElement("div"); // Adding class 'block' to div array_ele.classList.add("block"); // Adding style to div array_ele.style.height = `${value * 3}px`; array_ele.style.transform = `translate(${i * 30}px)`; // Creating label element for displaying // size of particular block var array_ele_label = document.createElement("label"); array_ele_label.classList.add("block_id"); array_ele_label.innerText = value; // Appending created elements to index.html array_ele.appendChild(array_ele_label); container.appendChild(array_ele); }} // Promise to swap two blocksfunction swap(el1, el2) { return new Promise((resolve) => { // For exchanging styles of two blocks var temp = el1.style.transform; el1.style.transform = el2.style.transform; el2.style.transform = temp; window.requestAnimationFrame(function() { // For waiting for .25 sec setTimeout(() => { container.insertBefore(el2, el1); resolve(); }, 250); }); });} // Asynchronous BubbleSort functionasync function BubbleSort(delay = 100) { var blocks = document.querySelectorAll(".block"); // BubbleSort Algorithm for (var i = 0; i < blocks.length; i += 1) { for (var j = 0; j < blocks.length - i - 1; j += 1) { // To change background-color of the // blocks to be compared blocks[j].style.backgroundColor = "#FF4949"; blocks[j + 1].style.backgroundColor = "#FF4949"; // To wait for .1 sec await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); console.log("run"); var value1 = Number(blocks[j].childNodes[0].innerHTML); var value2 = Number(blocks[j + 1] .childNodes[0].innerHTML); // To compare value of two blocks if (value1 > value2) { await swap(blocks[j], blocks[j + 1]); blocks = document.querySelectorAll(".block"); } // Changing the color to the previous one blocks[j].style.backgroundColor = "#6b5b95"; blocks[j + 1].style.backgroundColor = "#6b5b95"; } //changing the color of greatest element //found in the above traversal blocks[blocks.length - i - 1] .style.backgroundColor = "#13CE66"; }} // Calling generatearray functiongeneratearray(); // Calling BubbleSort functionBubbleSort(); Output: CSS-Questions HTML-Questions JavaScript-Questions Technical Scripter 2020 CSS HTML JavaScript Sorting Technical Scripter Web Technologies Sorting HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25502, "s": 25474, "text": "\n08 Feb, 2021" }, { "code": null, "e": 25800, "s": 25502, "text": "GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Bubble Sort using JavaScript. We will see how the elements are swapped in Bubble Sort and how we get the final sorted array. We will also visualize the time complexity of Bubble Sort. " }, { "code": null, "e": 25807, "s": 25800, "text": "Refer:" }, { "code": null, "e": 25818, "s": 25807, "text": "BubbleSort" }, { "code": null, "e": 25854, "s": 25818, "text": "Asynchronous Function in JavaScript" }, { "code": null, "e": 25865, "s": 25854, "text": " Approach:" }, { "code": null, "e": 25934, "s": 25865, "text": "First, we will generate a random array using Math.random() function." }, { "code": null, "e": 26029, "s": 25934, "text": "Different colors are used to indicate which elements are being compared, sorted, and unsorted." }, { "code": null, "e": 26149, "s": 26029, "text": "Since the algorithm performs the operation very fast, the setTimeout() function has been used to slow down the process." }, { "code": null, "e": 26206, "s": 26149, "text": "New array can be generated by pressing the “Ctrl+R” key." }, { "code": null, "e": 26281, "s": 26206, "text": "The sorting is performed using BubbleSort() function using swap() function" }, { "code": null, "e": 26290, "s": 26281, "text": "Example:" }, { "code": null, "e": 26351, "s": 26290, "text": "Below is the program to visualize the Bubble Sort algorithm." }, { "code": null, "e": 26362, "s": 26351, "text": "index.html" }, { "code": null, "e": 26367, "s": 26362, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <link rel=\"stylesheet\" href=\"style.css\" /></head> <body> <br /> <p class=\"header\">Bubble Sort</p> <div id=\"array\"></div> <script src=\"script.js\"></script></body> </html>", "e": 26708, "s": 26367, "text": null }, { "code": null, "e": 26788, "s": 26708, "text": "style.css: The following is the content for “style.css” used in the above file." }, { "code": "* { margin: 0px; padding: 0px; box-sizing: border-box;} .header { font-size: 20px; text-align: center;} #array { background-color: white; height: 413px; width: 598px; margin: auto; position: relative; margin-top: 64px;} .block { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease;} .block_id { position: absolute; color: black; margin-top: -20px; width: 100%; text-align: center;}", "e": 27284, "s": 26788, "text": null }, { "code": null, "e": 27374, "s": 27284, "text": "script.js: The following is the content for “script.js” file used in the above HTML code." }, { "code": "var container = document.getElementById(\"array\"); // Function to generate the array of blocksfunction generatearray() { for (var i = 0; i < 20; i++) { // Return a value from 1 to 100 (both inclusive) var value = Math.ceil(Math.random() * 100); // Creating element div var array_ele = document.createElement(\"div\"); // Adding class 'block' to div array_ele.classList.add(\"block\"); // Adding style to div array_ele.style.height = `${value * 3}px`; array_ele.style.transform = `translate(${i * 30}px)`; // Creating label element for displaying // size of particular block var array_ele_label = document.createElement(\"label\"); array_ele_label.classList.add(\"block_id\"); array_ele_label.innerText = value; // Appending created elements to index.html array_ele.appendChild(array_ele_label); container.appendChild(array_ele); }} // Promise to swap two blocksfunction swap(el1, el2) { return new Promise((resolve) => { // For exchanging styles of two blocks var temp = el1.style.transform; el1.style.transform = el2.style.transform; el2.style.transform = temp; window.requestAnimationFrame(function() { // For waiting for .25 sec setTimeout(() => { container.insertBefore(el2, el1); resolve(); }, 250); }); });} // Asynchronous BubbleSort functionasync function BubbleSort(delay = 100) { var blocks = document.querySelectorAll(\".block\"); // BubbleSort Algorithm for (var i = 0; i < blocks.length; i += 1) { for (var j = 0; j < blocks.length - i - 1; j += 1) { // To change background-color of the // blocks to be compared blocks[j].style.backgroundColor = \"#FF4949\"; blocks[j + 1].style.backgroundColor = \"#FF4949\"; // To wait for .1 sec await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); console.log(\"run\"); var value1 = Number(blocks[j].childNodes[0].innerHTML); var value2 = Number(blocks[j + 1] .childNodes[0].innerHTML); // To compare value of two blocks if (value1 > value2) { await swap(blocks[j], blocks[j + 1]); blocks = document.querySelectorAll(\".block\"); } // Changing the color to the previous one blocks[j].style.backgroundColor = \"#6b5b95\"; blocks[j + 1].style.backgroundColor = \"#6b5b95\"; } //changing the color of greatest element //found in the above traversal blocks[blocks.length - i - 1] .style.backgroundColor = \"#13CE66\"; }} // Calling generatearray functiongeneratearray(); // Calling BubbleSort functionBubbleSort();", "e": 30348, "s": 27374, "text": null }, { "code": null, "e": 30356, "s": 30348, "text": "Output:" }, { "code": null, "e": 30370, "s": 30356, "text": "CSS-Questions" }, { "code": null, "e": 30385, "s": 30370, "text": "HTML-Questions" }, { "code": null, "e": 30406, "s": 30385, "text": "JavaScript-Questions" }, { "code": null, "e": 30430, "s": 30406, "text": "Technical Scripter 2020" }, { "code": null, "e": 30434, "s": 30430, "text": "CSS" }, { "code": null, "e": 30439, "s": 30434, "text": "HTML" }, { "code": null, "e": 30450, "s": 30439, "text": "JavaScript" }, { "code": null, "e": 30458, "s": 30450, "text": "Sorting" }, { "code": null, "e": 30477, "s": 30458, "text": "Technical Scripter" }, { "code": null, "e": 30494, "s": 30477, "text": "Web Technologies" }, { "code": null, "e": 30502, "s": 30494, "text": "Sorting" }, { "code": null, "e": 30507, "s": 30502, "text": "HTML" }, { "code": null, "e": 30605, "s": 30507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30642, "s": 30605, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30671, "s": 30642, "text": "Form validation using jQuery" }, { "code": null, "e": 30710, "s": 30671, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30752, "s": 30710, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 30787, "s": 30752, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 30847, "s": 30787, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30908, "s": 30847, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30961, "s": 30908, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31011, "s": 30961, "text": "How to Insert Form Data into Database using PHP ?" } ]
Allow users to change font size of a webpage using JavaScript - GeeksforGeeks
19 Aug, 2021 If you have seen some websites especially some Indian government portals, you would have noticed three small buttons at the top rightmost corner of the page looking something like this: -A A A+. These buttons generally allow the website users to change the font size of the entire page or a certain portion of the page to a specific size to improve the readability of the page. In this post, we are going to learn how to achieve this feature for a specific div using JavaScript. However, usage of the buttons provides users only a few options to change the font size. Using an HTML slider allows users to choose a font size from within a wide range thus giving users more options to choose from. So, apart from buttons, we are also going to achieve the same feature using an HTML slider. Approach: Define the <div> tag consisting the <p> tag, slider & 3 buttons.Make a JavaScript function to change the font size of the content in the div section. Use OnClick() event for the button click & for moving the slider, use OnChange() event.In the case of a button click, use the DOM to access the <div> tag for changing the value of the font-size attribute from javascript itself. In the case of moving the slider, again use DOM to access the value of the slider that has been set by the user and use this value as the font-size value for the <div> tag. Define the <div> tag consisting the <p> tag, slider & 3 buttons. Make a JavaScript function to change the font size of the content in the div section. Use OnClick() event for the button click & for moving the slider, use OnChange() event. In the case of a button click, use the DOM to access the <div> tag for changing the value of the font-size attribute from javascript itself. In the case of moving the slider, again use DOM to access the value of the slider that has been set by the user and use this value as the font-size value for the <div> tag. We will follow the above approach to build the font size controller & will make it stepwise manner. Step 1: Create a simple HTML page with three buttons, a div consisting of a paragraph, and a slider. We are going to change the font size of this div content using the buttons or the slider. We will apply only the essential CSS stylings. HTML <!DOCTYPE html><html> <body> <center> <h1 style="color: green">GeeksForGeeks</h1> <button type="button" name="btn1">-A</button> <button type="button" name="btn2">A</button> <button type="button" name="btn3">A+</button> <br /><br /> <div style="padding: 20px; margin: 50px; font-size: 20px; border: 5px solid green;" id="container" class="container"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer ming science and programarticles,quizzes and practice/ competitive programming/company interview questions. </p> </div> <input type="range" min="10" max="30" id="slider" value="20" /> </center></body> </html> Step 2: We will write a JavaScript function to change the font size of the div when the user clicks the button or moves the slider. This change can be observed by using JavaScript events. Make use of the onClick() event to observe if the user has clicked the button and make use of the onChange() event to sense if the user has moved the slider. Create two functions for the two triggers events (ie. onClick and onChange). For the button functionality, a parametrized function will be created for the onClick event where each button will send a unique number which will be the font size of the div. Using the Document object module (DOM), we can access our <div> tag and change the value of the font-size attribute from javascript itself. For the Slider functionality, a normal non-parameterized function will be created for the onChange event. Using the Document object module (DOM), we can access the value of the slider that has been set by the user and use this value as the font-size value for our <div> tag. Javascript <script> var cont = document.getElementById("container"); function changeSizeByBtn(size) { // Set value of the parameter as fontSize cont.style.fontSize = size; } function changeSizeBySlider() { var slider = document.getElementById("slider"); // Set slider value as fontSize cont.style.fontSize = slider.value; }</script> Step 3: Add the appropriate functions to the event attributes of the button and the slider. Click the buttons or move the slider and you should see the font size of the div contents to be changing. Complete code: HTML <!DOCTYPE html><html> <body> <center> <h1 style="color: green">GeeksForGeeks</h1> <button type="button" onclick="changeSizeByBtn(15)" name="btn1"> -A </button> <button type="button" onclick="changeSizeByBtn(20)" name="btn2"> A </button> <button type="button" onclick="changeSizeByBtn(25)" name="btn3"> A+ </button> <br /><br /> <div style="padding: 20px; margin: 50px; font-size: 20px; border: 5px solid green;" id="container" class="container"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer scienc and programming articles quizzes and practice/ competitive programming/company interview questions. </p> </div> <input type="range" min="10" max="30" id="slider" onchange="changeSizeBySlider()" value="20" /> </center> <script> var cont = document.getElementById("container"); function changeSizeByBtn(size) { // Set value of the parameter as fontSize cont.style.fontSize = size; } function changeSizeBySlider() { var slider = document.getElementById("slider"); // Set slider value as fontSize cont.style.fontSize = slider.value; } </script></body> </html> Output: changing font size using JavaScript HTML-Questions HTML-Tags JavaScript-Questions CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25400, "s": 25372, "text": "\n19 Aug, 2021" }, { "code": null, "e": 26190, "s": 25400, "text": "If you have seen some websites especially some Indian government portals, you would have noticed three small buttons at the top rightmost corner of the page looking something like this: -A A A+. These buttons generally allow the website users to change the font size of the entire page or a certain portion of the page to a specific size to improve the readability of the page. In this post, we are going to learn how to achieve this feature for a specific div using JavaScript. However, usage of the buttons provides users only a few options to change the font size. Using an HTML slider allows users to choose a font size from within a wide range thus giving users more options to choose from. So, apart from buttons, we are also going to achieve the same feature using an HTML slider." }, { "code": null, "e": 26200, "s": 26190, "text": "Approach:" }, { "code": null, "e": 26752, "s": 26200, "text": "Define the <div> tag consisting the <p> tag, slider & 3 buttons.Make a JavaScript function to change the font size of the content in the div section. Use OnClick() event for the button click & for moving the slider, use OnChange() event.In the case of a button click, use the DOM to access the <div> tag for changing the value of the font-size attribute from javascript itself. In the case of moving the slider, again use DOM to access the value of the slider that has been set by the user and use this value as the font-size value for the <div> tag." }, { "code": null, "e": 26817, "s": 26752, "text": "Define the <div> tag consisting the <p> tag, slider & 3 buttons." }, { "code": null, "e": 26991, "s": 26817, "text": "Make a JavaScript function to change the font size of the content in the div section. Use OnClick() event for the button click & for moving the slider, use OnChange() event." }, { "code": null, "e": 27134, "s": 26991, "text": "In the case of a button click, use the DOM to access the <div> tag for changing the value of the font-size attribute from javascript itself. " }, { "code": null, "e": 27307, "s": 27134, "text": "In the case of moving the slider, again use DOM to access the value of the slider that has been set by the user and use this value as the font-size value for the <div> tag." }, { "code": null, "e": 27407, "s": 27307, "text": "We will follow the above approach to build the font size controller & will make it stepwise manner." }, { "code": null, "e": 27645, "s": 27407, "text": "Step 1: Create a simple HTML page with three buttons, a div consisting of a paragraph, and a slider. We are going to change the font size of this div content using the buttons or the slider. We will apply only the essential CSS stylings." }, { "code": null, "e": 27652, "s": 27647, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color: green\">GeeksForGeeks</h1> <button type=\"button\" name=\"btn1\">-A</button> <button type=\"button\" name=\"btn2\">A</button> <button type=\"button\" name=\"btn3\">A+</button> <br /><br /> <div style=\"padding: 20px; margin: 50px; font-size: 20px; border: 5px solid green;\" id=\"container\" class=\"container\"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer ming science and programarticles,quizzes and practice/ competitive programming/company interview questions. </p> </div> <input type=\"range\" min=\"10\" max=\"30\" id=\"slider\" value=\"20\" /> </center></body> </html>", "e": 28558, "s": 27652, "text": null }, { "code": null, "e": 28982, "s": 28558, "text": "Step 2: We will write a JavaScript function to change the font size of the div when the user clicks the button or moves the slider. This change can be observed by using JavaScript events. Make use of the onClick() event to observe if the user has clicked the button and make use of the onChange() event to sense if the user has moved the slider. Create two functions for the two triggers events (ie. onClick and onChange). " }, { "code": null, "e": 29298, "s": 28982, "text": "For the button functionality, a parametrized function will be created for the onClick event where each button will send a unique number which will be the font size of the div. Using the Document object module (DOM), we can access our <div> tag and change the value of the font-size attribute from javascript itself." }, { "code": null, "e": 29573, "s": 29298, "text": "For the Slider functionality, a normal non-parameterized function will be created for the onChange event. Using the Document object module (DOM), we can access the value of the slider that has been set by the user and use this value as the font-size value for our <div> tag." }, { "code": null, "e": 29584, "s": 29573, "text": "Javascript" }, { "code": "<script> var cont = document.getElementById(\"container\"); function changeSizeByBtn(size) { // Set value of the parameter as fontSize cont.style.fontSize = size; } function changeSizeBySlider() { var slider = document.getElementById(\"slider\"); // Set slider value as fontSize cont.style.fontSize = slider.value; }</script>", "e": 29948, "s": 29584, "text": null }, { "code": null, "e": 30146, "s": 29948, "text": "Step 3: Add the appropriate functions to the event attributes of the button and the slider. Click the buttons or move the slider and you should see the font size of the div contents to be changing." }, { "code": null, "e": 30161, "s": 30146, "text": "Complete code:" }, { "code": null, "e": 30166, "s": 30161, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color: green\">GeeksForGeeks</h1> <button type=\"button\" onclick=\"changeSizeByBtn(15)\" name=\"btn1\"> -A </button> <button type=\"button\" onclick=\"changeSizeByBtn(20)\" name=\"btn2\"> A </button> <button type=\"button\" onclick=\"changeSizeByBtn(25)\" name=\"btn3\"> A+ </button> <br /><br /> <div style=\"padding: 20px; margin: 50px; font-size: 20px; border: 5px solid green;\" id=\"container\" class=\"container\"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer scienc and programming articles quizzes and practice/ competitive programming/company interview questions. </p> </div> <input type=\"range\" min=\"10\" max=\"30\" id=\"slider\" onchange=\"changeSizeBySlider()\" value=\"20\" /> </center> <script> var cont = document.getElementById(\"container\"); function changeSizeByBtn(size) { // Set value of the parameter as fontSize cont.style.fontSize = size; } function changeSizeBySlider() { var slider = document.getElementById(\"slider\"); // Set slider value as fontSize cont.style.fontSize = slider.value; } </script></body> </html>", "e": 31723, "s": 30166, "text": null }, { "code": null, "e": 31731, "s": 31723, "text": "Output:" }, { "code": null, "e": 31767, "s": 31731, "text": "changing font size using JavaScript" }, { "code": null, "e": 31782, "s": 31767, "text": "HTML-Questions" }, { "code": null, "e": 31792, "s": 31782, "text": "HTML-Tags" }, { "code": null, "e": 31813, "s": 31792, "text": "JavaScript-Questions" }, { "code": null, "e": 31817, "s": 31813, "text": "CSS" }, { "code": null, "e": 31822, "s": 31817, "text": "HTML" }, { "code": null, "e": 31833, "s": 31822, "text": "JavaScript" }, { "code": null, "e": 31850, "s": 31833, "text": "Web Technologies" }, { "code": null, "e": 31855, "s": 31850, "text": "HTML" }, { "code": null, "e": 31953, "s": 31855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31962, "s": 31953, "text": "Comments" }, { "code": null, "e": 31975, "s": 31962, "text": "Old Comments" }, { "code": null, "e": 32012, "s": 31975, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32041, "s": 32012, "text": "Form validation using jQuery" }, { "code": null, "e": 32080, "s": 32041, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32122, "s": 32080, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 32157, "s": 32122, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 32217, "s": 32157, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32278, "s": 32217, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32331, "s": 32278, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32381, "s": 32331, "text": "How to Insert Form Data into Database using PHP ?" } ]
MongoDB - $pull Operator - GeeksforGeeks
10 May, 2020 MongoDB provides different types of array update operators to update the values of the array fields in the documents and $pull operator is one of them. This operator is used to remove all the instances of the value or the value that matches the specified condition from the existing array. Syntax: { $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } } Here, <field> can specify with dot notation in embedded/nested documents or an array. In $pull operator, if you specify the <condition> and the array contains the embedded/nested documents, then this operator applies the <condition> as if each array item were a document in a collection. If you specify a <value> in the $pull operator to remove is an array, then this operator will remove only those items in the array that match the specified <value>. Here, the order must be same. If you specify a <value> in the $pull operator to remove is a document, then this operator will remove only those items in the array that have exact same fields and values. Here, the order of the fields can differ. You can use this operator with methods like update(), findAndModify(), etc., according to your requirement. In the following examples, we are working with: Database: GeeksforGeeksCollection: contributorDocument: two documents that contain the details of the contributor in the form of field-value pairs. In this example, we are removing the specified elements, i.e., [“C#”, “Perl”] from the language field. db.contributor.update({},... {$pull: {language: {$in: ["C#", "Perl"]}}},... {multi: true}) In this example, we are removing semester marks that are less than and equal to ($lte) 73 from the personal.semesterMarks field in the document that matches the specified condition, i.e., name: “Rohit”. db.contributor.update({name: "Rohit"}, {$pull: {"personal.semesterMarks": {$lte: 75}}}) In this example, we are removing language: “Java” and tArticles: 50 items from the array of documents, i.e., articles field. db.contributor.update({}, ... {$pull: {articles: {language: "Java", tArticles: 50}}}, ... {multi: true}) MongoDB MongoDB-operators MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Spring Boot JpaRepository with Example Aggregation in MongoDB MongoDB - db.collection.Find() Method MongoDB - Check the existence of the fields in the specified collection Mongoose Populate() Method How to build a basic CRUD app with Node.js and ReactJS ? Upsert in MongoDB How to connect MongoDB with ReactJS ? MongoDB - Distinct() Method MongoDB - limit() Method
[ { "code": null, "e": 23922, "s": 23894, "text": "\n10 May, 2020" }, { "code": null, "e": 24212, "s": 23922, "text": "MongoDB provides different types of array update operators to update the values of the array fields in the documents and $pull operator is one of them. This operator is used to remove all the instances of the value or the value that matches the specified condition from the existing array." }, { "code": null, "e": 24220, "s": 24212, "text": "Syntax:" }, { "code": null, "e": 24297, "s": 24220, "text": "{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }" }, { "code": null, "e": 24383, "s": 24297, "text": "Here, <field> can specify with dot notation in embedded/nested documents or an array." }, { "code": null, "e": 24585, "s": 24383, "text": "In $pull operator, if you specify the <condition> and the array contains the embedded/nested documents, then this operator applies the <condition> as if each array item were a document in a collection." }, { "code": null, "e": 24780, "s": 24585, "text": "If you specify a <value> in the $pull operator to remove is an array, then this operator will remove only those items in the array that match the specified <value>. Here, the order must be same." }, { "code": null, "e": 24995, "s": 24780, "text": "If you specify a <value> in the $pull operator to remove is a document, then this operator will remove only those items in the array that have exact same fields and values. Here, the order of the fields can differ." }, { "code": null, "e": 25103, "s": 24995, "text": "You can use this operator with methods like update(), findAndModify(), etc., according to your requirement." }, { "code": null, "e": 25151, "s": 25103, "text": "In the following examples, we are working with:" }, { "code": null, "e": 25299, "s": 25151, "text": "Database: GeeksforGeeksCollection: contributorDocument: two documents that contain the details of the contributor in the form of field-value pairs." }, { "code": null, "e": 25402, "s": 25299, "text": "In this example, we are removing the specified elements, i.e., [“C#”, “Perl”] from the language field." }, { "code": "db.contributor.update({},... {$pull: {language: {$in: [\"C#\", \"Perl\"]}}},... {multi: true})", "e": 25493, "s": 25402, "text": null }, { "code": null, "e": 25696, "s": 25493, "text": "In this example, we are removing semester marks that are less than and equal to ($lte) 73 from the personal.semesterMarks field in the document that matches the specified condition, i.e., name: “Rohit”." }, { "code": "db.contributor.update({name: \"Rohit\"}, {$pull: {\"personal.semesterMarks\": {$lte: 75}}})", "e": 25806, "s": 25696, "text": null }, { "code": null, "e": 25931, "s": 25806, "text": "In this example, we are removing language: “Java” and tArticles: 50 items from the array of documents, i.e., articles field." }, { "code": "db.contributor.update({}, ... {$pull: {articles: {language: \"Java\", tArticles: 50}}}, ... {multi: true})", "e": 26036, "s": 25931, "text": null }, { "code": null, "e": 26044, "s": 26036, "text": "MongoDB" }, { "code": null, "e": 26062, "s": 26044, "text": "MongoDB-operators" }, { "code": null, "e": 26070, "s": 26062, "text": "MongoDB" }, { "code": null, "e": 26168, "s": 26070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26177, "s": 26168, "text": "Comments" }, { "code": null, "e": 26190, "s": 26177, "text": "Old Comments" }, { "code": null, "e": 26229, "s": 26190, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 26252, "s": 26229, "text": "Aggregation in MongoDB" }, { "code": null, "e": 26290, "s": 26252, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 26362, "s": 26290, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 26389, "s": 26362, "text": "Mongoose Populate() Method" }, { "code": null, "e": 26446, "s": 26389, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 26464, "s": 26446, "text": "Upsert in MongoDB" }, { "code": null, "e": 26502, "s": 26464, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 26530, "s": 26502, "text": "MongoDB - Distinct() Method" } ]
Front Office Management - Quick Guide
Every multi-departmental physical business needs to have a front office or reception to receive the visitors. Front Office Department is the face and as well as the voice of a business. Regardless of the star rating of the hotel or the hotel type, the hotel has a front office as its most visible department. For a business such as hospitality, the front office department comes with an aspect of elevating customer experience with the business. Front Office department is a common link between the customers and the business. Let us learn more about it. It is the one of the many departments of the hotel business which directly interacts with the customers when they first arrive at the hotel. The staff of this department is very visible to the guests. Front office staff handles the transactions between the hotel and its guests. The staff receives the guests, handles their requests, and strikes the first impression about the hotel into their minds. Front office department includes − Front Desk Uniformed services Concierges Front Office Accounting System Private Branch Exchange (PBX), a private telephone network used within an organization Following are the most basic responsibilities a front office can handle. Creating guest database Handling guest accounts Coordinating guest service Trying to sell a service Ensuring guest satisfaction Handling in-house communication through PBX There are two categories of Front Office Operations − These operations are visible to the guests of the hotel. The guests can interact and see these operations, hence, the name Front-House operations. Few of these operations include − Interacting with the guests to handle request for an accommodation. Checking accommodation availability and assigning it to the guest. Collecting detail information while guest registration. Creating a guest’s account with the FO accounting system. Issuing accommodation keys to the guest. Settling guest payment at the time of check-out. Front Office staff conducts these operations in the absence of the guests or when the guest’s involvement is not required. These operations involve activities such as − Determining the type of guest (fresh/repeat) by checking the database. Ensuring preferences of the guest to give a personal touch to the service. Maintaining guest’s account with the accounting system. Preparing the guest’s bill. Collecting the balance amount of guest bills. Generating reports. Generally, a guest’s interaction with the hotel is divided into the following four sequential phases − It is the stage when the customer is planning to avail an accommodation in the hotel. In this first stage, the customer or the prospective guest enquires about the availability of the desired type of accommodation and its amenities via telephonic call or an e-mail. The customer also tries to find out more information about the hotel by visiting its website. At the hotel end, the front office accounting system captures the guest’s information such as name, age, contact numbers, probable duration of stay for room reservation and so on. The front office reception staff receives the guest in the reception. The porters bring in the guest luggage. For the guest with confirmed reservation, the front office clerk hands over a Guest Registration Card (GRC) to the guest and requests the guest to fill in personal information regarding the stay in the hotel. The clerk then registers the guest in the database thereby creating a guest record and a guest account along with it. Later, the clerk hands over a welcome kit and keys of the accommodation. After the procedure of registration, the guest can start occupying the accommodation. During occupancy, a front office accounting system is responsible for tracking guest charges against his/her purchases from the hotel restaurants, room service, bar, or any outgoing telephone calls made via the hotel’s communication systems. The front office staff is responsible to manage and issue the right keys of the accommodations to the right guests. On guests’ request, the staff also makes arrangement for transportation, babysitting, or local touring while the guest is staying in the hotel. During guest departure, the front office accounting system ensures payment for goods and services provided. If a guest’s bill is not completely paid, the balance is transferred from guest to non-guest records. When this occurs, collection becomes the responsibility of the back office accounting division. At the time of guest departure, the front office staff thanks the guest for giving an opportunity to serve and arrange for handling luggage. In addition, if the guest requires airport or other drop service, the front office bell desk fulfils it. Following are some common terms used in relation to the front office department − Account receivables The amount of money an organization has the right to receive within some specified period (say 30 days) against the delivery of products/services. Bell desk An extension of front desk that deals with personalized guest services. Cancellation charges They are the charges borne by the guest on cancellation of a confirmed reservation or for not showing-up on confirmed reservation. Concierge Information desk that assists guests for transportation, booking of events outside the hotel. GRC Guest Registration Card, which the guest needs to fill in with personal formation at the time of registration. Guest Customer of the hotel business being served. IP-PBX Internet Protocol Private Branch Exchange, where internet protocol is used for call transmission. MICE Acronym for Meetings, Incentives, Conferences, and Exhibitions. Non-guest Customer of a hotel business not being served at the moment. No-show A guest who has reserved an accommodation neither turns up nor cancels it. OHMS Online Hotel Management System, a software system to manage all back-office operations of a hotel. PBX Private Branch Exchange, a private network of telephones within an organization. POS Acronym for Point of Sale. It is the revenue generating place in the hotel where retail transactions are carried out. Rack rate The price at which the hotel rooms are sold before applying discount. SMERF Acronym for Social, Military, Educational, Religious, and Fraternal. Trial balance It is a report of accounts that represents ending balance of each account in the list. It is prepared at the end of an accounting period. Uniformed services Personalized services provided to the guests. Valet A male attendant to park and clean the car. Whitney System An old reservation system for hotel accommodations. Yield Management A variable pricing strategy, based on understanding, anticipating and influencing consumer behavior in order to maximize revenue from a fixed, perishable resource. Front office area is commonly termed as ‘Reception’, as it is the place where the guests are received when they arrive at the hotel. It is the first point of interaction between the hotel and the guests. Being the prime interface between the hotel services and the guests, the front office is located near the main entrance of the hotel. The front office structure can be viewed in two ways: the physical setup and the operational structure of the department. The physical setup includes key-hanging boards, bell desk and guest-mail handling register. The front desk is equipped with various compartments, the computerized property management system, and an in-house communication system. The front desk is where the guests temporarily await to find an accommodation or to clear their bill. Hence, it needs to be positioned appropriately such that the staff and the guests can use them conveniently. The front desk needs to be − Positioned at an adequate height and reach. An adequately lit-up area. Aesthetically furnished. Preferably near the hotel lobby and lift. Preferably near the sitting area. Wide enough to make the staff member communicate with the guests across the desk. The front office staff needs to communicate with the staff of the same as well as all other departments of the hotel. This is termed as internal communication. It mostly relies upon the PBX or IP-PBX system. When the front office communicates with the potential customers outside the hotel, corporate offices, and other ancillary service providers, then it is an external communication. Any formal communication outside the hotel is mostly carried out using e-mails and phone calls. For sending coupons or other promotional material, renewing agreements with travel agents or airlines, the front office staff may opt for postal mail. There are lot of staff working under front office manager. The structure of the front office department changes according to the size of the hotel business, physical size of the hotel, and the hotel management policies. Following is the general structure of the front office department − Front office department manager heads the team of staff working on various activities and responsibilities in the front office department. Few prominent activities that the front office staff is involved in are − Reservation − It includes handling request of customers for reserving accommodations. Reservation − It includes handling request of customers for reserving accommodations. Reception − It includes receiving the guests according to the highest standards and registering them appropriately. It also includes bidding the guests off. Reception − It includes receiving the guests according to the highest standards and registering them appropriately. It also includes bidding the guests off. Guest Services − They are also known as Uniformed Services. It includes personalized guest services such as − Handling guest luggage. Handling guest mail. Delivering newspapers in accommodations. Paging the guest inside the hotel (locating the guest in the hotel). Arranging for a doctor in emergency. Parking guest’s automobiles. Arranging for reservations at the places of entertainment outside the hotel. Guest Services − They are also known as Uniformed Services. It includes personalized guest services such as − Handling guest luggage. Handling guest mail. Delivering newspapers in accommodations. Paging the guest inside the hotel (locating the guest in the hotel). Arranging for a doctor in emergency. Parking guest’s automobiles. Arranging for reservations at the places of entertainment outside the hotel. Accounts − It mainly includes a front office cashier and a Night Auditor. The cashier is responsible for handling guest payments. He typically reports to the accounts manager rather than the front office manager. The night auditor performs the duties of front desk reception as well as accounting partly during the night shift. He needs to report to the heads of both departments, front office, and accounting. Accounts − It mainly includes a front office cashier and a Night Auditor. The cashier is responsible for handling guest payments. He typically reports to the accounts manager rather than the front office manager. The night auditor performs the duties of front desk reception as well as accounting partly during the night shift. He needs to report to the heads of both departments, front office, and accounting. Communication − It involves handling communication among various other departments and guests of the hotel. Communication − It involves handling communication among various other departments and guests of the hotel. Let us discuss a few prominent ranks in the front office department and their respective responsibilities − In the context of hotel, the term reservation is used for booking a particular accommodation in the hotel by a guest for a period of time. Reservation section does not directly deal with the guests. Some important tasks a reservation manager is responsible for are − Having knowledge about the reservation systems. Providing and updating information on tours, prices, and itineraries. Reviewing daily hotel reservations. Preparing occupancy forecast. Updating travel agent rates in the system. Handling correspondence with outside travel agencies. Allocating daily tasks to the reservation staff. Ensuring special deals with repeat guests, VIPs, or guest groups. Training the staff under hand. Following are some prominent roles and responsibilities of the reception manager − Dealing with arrival and departure of the guests. Dealing with arrival and departure of the guests. Welcoming the guests, escorting them to the room, and seeing them off. Welcoming the guests, escorting them to the room, and seeing them off. Ensuring professional greeting of clients, visitors, and guests. Ensuring professional greeting of clients, visitors, and guests. Coordination with housekeeping department for cleaning rooms. Coordination with housekeeping department for cleaning rooms. Filling registration cards for the guests with reserved accommodation or help the guests to fill it up. Filling registration cards for the guests with reserved accommodation or help the guests to fill it up. Arranging surprise gift for the guests on their special days. Arranging surprise gift for the guests on their special days. Training of receptionists. Training of receptionists. Handling appraisals and performance rewards of the staff. Handling appraisals and performance rewards of the staff. Reviewing current standards of front office services and procedures, and implementing new practices if required. Reviewing current standards of front office services and procedures, and implementing new practices if required. Ensuring and Scheduling front office desk staff. Ensuring and Scheduling front office desk staff. Managing VIP functions and events taking place in the hotel. Managing VIP functions and events taking place in the hotel. Upgrading software if required. Upgrading software if required. Updating backup database regularly. Updating backup database regularly. The responsibilities of the guest service manager include − Handling guest mails, letters, and couriers. Ensuring guest messages are delivered at the right time. Training the guest service staff such as concierges, bell staff, wallet parking staff, and porters. Maintaining guest service suggestion cards and guest complaints. Scheduling and appraising guest service staff. Ensuring the staff delivers services, accurately and timely. This manager works during the night hours. The typical responsibilities of a night audit manager are &mnus; Posting accommodation charges, taxes, and other paid services such as restaurant, Internet charges to each guest's account accurately. Posting accommodation charges, taxes, and other paid services such as restaurant, Internet charges to each guest's account accurately. Taking the responsibility as a duty manager for night shift. Taking the responsibility as a duty manager for night shift. Settling guest accounts if required. Settling guest accounts if required. Authoring security of the hotel during night shift. Authoring security of the hotel during night shift. The communication manager is responsible for − Keeping in check all communication facilities such as PBX, facsimile, internet in the hotel. Training and scheduling telephone operators in case of large hotels. Ensuring immediate delivery of fax to the guests, if required. Appraising telephone operators. Changing the communication systems to the latest technology for easy use. Being a part of the service industry, the front office staff needs to have the following qualities and competencies. The front office staff members are required to − Understand their respective roles and responsibilities in the hotel and front office as an operation. Equip themselves with basic etiquettes and mannerism. Possess pleasant, polite, and cordial personality. Wear clean and neat uniform with same accessories and footwear. Conduct themselves with professionalism, positive attitude, and cooperative nature. Possess extraordinary communication skills. Be a team player. Possess the ability to tackle tricky situations. Reservation of the hotel accommodation is one of the important responsibilities of the front office department. A potential guest contacts a hotel for availability of the desired type of accommodation and any allied services that the hotel offers. The front office department needs to react to the enquiry of the guests. For a guest, reservation increases the chances of a better deal for assured accommodation on arrival. For a hotel, reservation can enable a better management of guest experience during usual as well as peak seasons. Reservation procedure varies depending on the size and brand of the hotel and the reservation system employed. Let us know the details how the front office handles reservations. An efficient and effective reservation system is what adds to the hotel’s profitability. Following are the most popular reservation systems − It was developed in 1940 by Whitney Paper Corporation from New York, hence the name. This is a conventional manual reservation system the hotels used to follow during pre-computer days in the hotels. It contains the following setup for reservation − Slip for request of accommodation reservation Whitney slip that records guest name, accommodation type, number, and duration of stay Temporary/Permanent arrival slip Guest bill Guest registration card Correspondence file Bedroom journal that records daily occupancy of the guest with date, guest name, room type, and room number Let us see how a Whitney slip and the bedroom journal looks like. Though this system proved efficient, it generated a lot of paperwork with occasional scope for errors. The drawbacks were overcome by the central reservation system. It is a computerized reservation system that reduces paperwork and can handle large amount of reservation data effortlessly. In this system, since the guest data and reservation data are stored on the storage disks of the computers, it can be accessed at wish. It is stored in the form of a database of collection of records which can enable searching, adding, removing, or updating any guest related data. The computerized reservation system not only helps to make guest reservations but also helps to forecast how many accommodations can be reserved in an upcoming time period. This is how a CRS typically works − The guests of hotel sales agents call for checking room availability. It is forwarded to the front office reservation staff. The staff finds out details about the requirement and checks the availability of desired accommodation in the database. According to the reservation policies and procedures, the reservation staff member then notifies or suggests the reception about the accommodation availability and takes further appropriate action. The Internet has brought a momentum in the hospitality business as well. It facilitates seamless management of a hotel’s offices located at various places and their various departments. The hotel businesses are actively working on the Internet 24 hours a day, seven days a week. The Internet has simplified complex system of reservations. It enables Online Hotel Management Systems (OHMS) such as Hotelogix to help guests reserve accommodation of their choice fast and conveniently. The guests of the hotel can access rate charts, accommodation availability, check-in and check-out timings, details about the restaurants, and so on, at their own convenience. People travel for various reasons such as personal as well as for MICE. There are various sources from whom the requests of reservation pour in − Direct Request from Guests − The prospective guests can approach individually to the hotel for reservation of accommodation mostly when they are single travelers or family travelers. Direct Request from Guests − The prospective guests can approach individually to the hotel for reservation of accommodation mostly when they are single travelers or family travelers. Request from Travel Agent − They can approach the hotel for booking accommodations for group travelers. Request from Travel Agent − They can approach the hotel for booking accommodations for group travelers. Request from Corporate Agent − An organization can request a hotel to reserve accommodations for their employees, clients, or visitors. Request from Corporate Agent − An organization can request a hotel to reserve accommodations for their employees, clients, or visitors. Request from Airlines − The airlines can reserve accommodations for their working staff for routine stay as well as in case of flight cancellations. Request from Airlines − The airlines can reserve accommodations for their working staff for routine stay as well as in case of flight cancellations. Request from Institutions − Various SMERF or NGO institutions request to reserve hotels for sports people, delegations of embassies, or performing-art program groups, workshop groups, and alike who travel to different location. Request from Institutions − Various SMERF or NGO institutions request to reserve hotels for sports people, delegations of embassies, or performing-art program groups, workshop groups, and alike who travel to different location. The first step in reserving an accommodation is to check if the requested kind of accommodation is available for selling for a specific period of time. It is done by checking forecast boards or computerized systems. Reservation of an accommodation is accepted if the desired type of accommodation is available in the hotel for selling. If it is not available during a rush season or if the guest is in urgent need, the staff member suggests for almost similar alternative accommodation by stating its amenities and facilities. Reservation is accepted in the following cases in conjunction with the availability of the accommodation − Is the guest new to the hotel? Does the guest have good credentials with the hotel regarding payment and behavior? Is the guest a VIP? Denial of reservation directly means loss of revenue. But there are certain situations when the reservation staff turns down the reservation for the guests or agents. The potential causes of denying reservation are − All accommodations in hotel booked − In such case, the reservation staff refuses the reservation politely and suggests an alternative hotel in the same area or different property of the same owner in a nearby area. All accommodations in hotel booked − In such case, the reservation staff refuses the reservation politely and suggests an alternative hotel in the same area or different property of the same owner in a nearby area. Requested type of accommodation not available − In such case, the reservation staff suggests an alternate accommodation. Requested type of accommodation not available − In such case, the reservation staff suggests an alternate accommodation. Guest/Agent blacklisted − Some guests or agents are blacklisted due to their history of payment dues against the hotel. In such case, the reservation clerk seeks for reservation manager’s advice. Guest/Agent blacklisted − Some guests or agents are blacklisted due to their history of payment dues against the hotel. In such case, the reservation clerk seeks for reservation manager’s advice. Finally, the reservation section of the front office prepares the list of the reservations for the day and sends it to the front desk. The list also contains vital information such as if the guest is new or repeat, guest preferences about room location or décor. The rooms are then prepared by housekeeping. This is yet another event when the hotel loses business with a guest. Though the fact is overt loss of revenue, the front office staff must react to it politely and gracefully. The staff member also needs to convey any cancellation charges the guest must pay while cancelling the reservation. Cancellation is done in the following steps − Finding out details of the guest and respective reserved accommodation. Verifying charges of cancellation, if any. Notifying the guest about cancellation charges. Cancelling the reservation in the system. Updating the system for accommodation availability. Confirming the guest about the cancellation. Reservation reports are generated for the sake of helping the management find trends and making forecast about business. The reports typically are of the following types − Occupancy report Special arrival report Revenue forecast report Turnaway report Guest registration is nothing but recording the guest’s information for official purposes. At the time of reservation, the front office staff asks the guests to enter their personal information on the GRC. Registration activity is mandatory for both; the guest with reserved accommodation as well as for the walk-in guest. During registration, the guest is required to enter important information on the GRC such as guest name, contact number, purpose of stay at the hotel, and passport and visa details in case of foreign guest. It is the responsibility of the front office staff not to reveal the guest information to unauthorized persons. Let us learn more about registration. This procedure involves the prospective guests enquiring about the availability of desired type of accommodation. Registration can also be conducted in advance before arrival. It can be done via telephonic conversation in case of frequent guests, VIPs, or group guests. In case of new walk-in guest, pre-registration is absent as there is no prior interaction between the guest and the hotel. Pre-registration activity accelerates the actual registration process where the desired accommodation is marked as reserved. Since terror attacks on 9/11, the hotels are mandatorily verifying guests’ identities. The staff verifies guest’s identity first by politely asking the guest’s name. The staff member then requests to show a photo ID such as driving license or a valid identity card from a well-known organization where the guest is working. If the guests are from a foreign country, the staff requests them to show passport. The staff member is authorized to ask any verifying questions politely. The true copies of the passport or ID card are made to verify the guest’s identity and to prepare guest database. Following is a typical format of a registration card − Email: Fax: Card Details: Card Number: Date of Expiry: When the guests arrive at the hotel, the front desk staff hands over the GRC to the guest to fill up the information. In case of VIPs, the staff enters the information on the card and receives the guest’s signature. The staff then creates a registration record of the guest, countersigns, attaches the true copies of the passport or other ID cards, and files this set in the guest history file. The guest reservation record is created as a registration record in the software system. Guests can pay in advance or at the time of checking-out. Those who have paid in advance are put under Paid-In-Advance (PIA) list. There are various modes of payment out of which a mode that guest prefers is recorded at the time of registration. Following payment methods are available − Cash Payment (which also include money order, travelers’ cheque). Credit Card/Debit Card Payment (which are accepted only if the cards have not expired). Cheque Payment (where post-dated cheques are not accepted). Direct Billing. Special Payment such as gift card and voucher. The guests need to select one of the options of payment at the time of registration. The front office staff assigns an accommodation to the guest only when the registration is complete. The staff member records the accommodation number into the PMS and describes about its positive attributes briefly. The reservations staff also informs the bell-boy to take the guest luggage. After the accommodation is assigned, the front office staff gives away the keys or the computerized secret code keys for accessing the accommodation. It is a general practice to not to speak anything about the room number or the computerized key loudly while giving it to the guest. The bell attendant then assists the guest with luggage handling to the accommodation and explaining the accommodation features. The attendant then gives the keys to the guest, greets for best stay, and leaves the accommodation by closing the door. If the guest is not satisfied with the accommodation for any unsatisfactory or unpleasant reasons, the bell attendant can bring this to the notice of the front desk staff. In addition, if the guest has special requirements such as a cradle for a baby or hot water bag or a shaving kit and alike, the front office staff is obliged to fulfil the request on time. Accounting section of any business or organization tracks, records, and manages the financial transactions of the business with its customers and clients. The accounting department handles the financial health and tracks the performance of any business directly. It is helpful for the management to take appropriate decisions. When it comes to a hotel business, accounting is managing expenses and revenue. It provides a clear information to the guests thereby avoiding any unpleasant surprises to the guests. Let us know more about the accounts section of front office. It is a systematic process in which the front office accounting staff identifies, records, measures, classifies, verifies, summarizes, interprets, organizes, and communicates financial information for a hotel business. In the simplest form, a front office account resembles English alphabet ‘Block-T’. In the domain of front office accounting, the charges are entered on the left side of the ‘T’. They increase the account balance. The payments are entered on the right side of the ‘T’. They decrease the account balance. Net Outstanding Balance = Previous Balance + Debit – Credit Where debit increases the outstanding balance and credit decreases it. Most of the contemporary hotel businesses employ automated accounting system. The objectives of accounting system are − To handle transactions between the guests and the hotel accurately. To track the transactions throughout the guest’s occupancy. To monitor the guest’s credit limit. To avoid possibility of any fraud. To organize and report the transactional information. There are following typical accounts in hotel business dealing with customers − Guest Account Non-guest or City Account Management Account Here are some prominent differences between a guest and a city account − Some hotels allow the managers to entertain the guests’ queries or grievances, or any possibility of acquiring a business deal over a brief interaction with the guests. For example, if a guest has some problem about the hotel policy, the manager calls the guest for interaction over a coffee or a drink and tries to resolve the same. The expenses towards this interaction are then recorded on the management account. A folio is a statement of all transaction that has taken place in a single account. The front office staff records all the transactions between the guest and the hotel on the folio. The folio is opened with zero initial balance. The balance in the folio then increases or decreases depending upon the transactions. At the time of check-out, the folio balance must return to zero on settlement of payment. There are following major types of folios − Guest − Assigned to charge for individual guests. Guest − Assigned to charge for individual guests. Master − Assigned charge for group/organization. Master − Assigned charge for group/organization. Non-guest − Assigned for non-resident guest. Non-guest − Assigned for non-resident guest. Employee − Assigned for hotel employee to charge against coffee shop privileges. Employee − Assigned for hotel employee to charge against coffee shop privileges. The process of recording the entries on the folio is called ‘Posting’ of transactions. There are two basic types of postings − Credit − They reduce the guest’s outstanding balance. These entries include complete or partial payment, or adjustments against tokens. Credit − They reduce the guest’s outstanding balance. These entries include complete or partial payment, or adjustments against tokens. Debit − They increase the outstanding balance in the guest account. Debit entries include charges under restaurant, room-service, health center/spa, laundry, telephone, and transportation. Debit − They increase the outstanding balance in the guest account. Debit entries include charges under restaurant, room-service, health center/spa, laundry, telephone, and transportation. Vouchers are detailed documentary evidences for a transaction. It transfers the transaction from its source to the front office. Vouchers are used to notify the front office about guest’s purchases or availing of any service at the hotel. The following typical vouchers are used in the hotel − Cash Receipt Voucher Commission Voucher Charge Voucher Petty Cash Voucher Allowance Voucher Miscellaneous Charge Order (MCO) Paid-out Voucher (VPO) Transfer voucher Here are some typical vouchers. The ledgers are a group of accounts. There are two ledgers the front office handles − Guest ledger − A set of all guest accounts currently residing in the hotel. Guest ledger − A set of all guest accounts currently residing in the hotel. Non-guest ledger − A set of all unsettled, departed guest accounts. Non-guest ledger − A set of all unsettled, departed guest accounts. There are two other types of ledgers used in the hotel. Both types of ledgers are used by back office accounting section as given − Receivable ledger − The back office accounting staff mails the bills and statements to the guests after their departure without settling the bills and ensures the payments for services provided. Receivable ledger − The back office accounting staff mails the bills and statements to the guests after their departure without settling the bills and ensures the payments for services provided. Payable ledger − The staff handles amounts of money paid in advance on behalf of the guest to the hotel for future consumption of goods and services. Payable ledger − The staff handles amounts of money paid in advance on behalf of the guest to the hotel for future consumption of goods and services. There are various issues regarding account settlement − By Guest − The guest settles own account by cash/credit card/cheque. By Organization − The organization settles guest account by transferring money to the hotel account. There are following popular methods of account settlement − Account Settlement in Local Currency − A guest can pay in terms of a local currency where the payment is not chargeable with conversion fees. Account Settlement in Foreign Currency − If the guest prefers to pay in foreign currency, the service of payment by the bank is chargeable for around 3% to 6% of the total payable amount. Account Settlement Using Traveler Check − Travelers’ cheques, the pre-printed cheques in the denominations of major world currencies are a good option to paying by cash. Debit Card − Use of magnetic cards for payment against account is most common today. Paying by debit cards is as good as paying by cash as the amount of money is instantly transferred from the guest’s bank account into the hotel’s bank account. In case of credit card settlement, the accounting staff mails the charge vouchers signed by guests to the credit card company; preferably within a specified time. The credit card company then settles the guest account by transferring money against it. Credit Settlement by Organization − Many national, international, private, or public organizations send their employees or students for attending workshops, seminar, or meetings. Such organizations tie-up with the hotel for paying the bills of their employees on credit. The organizations reserve accommodations depending on the number of room nights (number of rooms × number of nights the representatives are expected to occupy). This is popularly known as account Settlement using Direct Billing. In direct billing account settlement, the front office staff verifies guest folios and transfers the guest account to non-guest or city account. The hotel’s back-office accounting verifies the guest folios and is responsible to collect the direct billing amount from a direct billing agency such as embassy, university, or organizations. The accounting section also notifies the guests that if the direct billing agency fails or refuses to pay the charges then the guests need to settle the account by paying them from their pocket. Combined Account Settlement − A guest can settle account by paying partial amount in cash and remaining amount on credit. The front office staff needs to prepare the supporting document for such kind of payment and hands it over to the back-office accounts. Healthy communication in the organization fosters mutual trust and sense of cooperation among the staff members and the guests as well as between the staff members and the management body. Front office communication with other departments can make or break the guests’ stay at the hotel. As the front office is responsible to sell the hotel accommodations, it is a major driving force for generating revenue. Hence, communication within and out of front office department needs to be vibrant and positive. Front office department is responsible for communicating with all other departments in the hotel as well as different sections within the department. To get the front office and back office jobs done successfully, the front office staff members need to communicate with their peers as well as the colleagues and subordinates. Within the department, the staff of front office communicate with each other to provide the best possible guest services such as reserving accommodations, registering guests, managing guest accounts, handling guest mails, and personalized guest services. Front office interacts with various departments since the guest inquire about reservation through the entire guest cycle up to the guest’s departure. Here is how front office needs to communicate with the other departments − Communication with Human Resource − Front Office department is engaged with the HR department to interview, help shortlist them, and select the most eligible employees. It also contacts the HR department for employee training and induction programs, salaries, leaves, dues, and appraisals. Communication with Human Resource − Front Office department is engaged with the HR department to interview, help shortlist them, and select the most eligible employees. It also contacts the HR department for employee training and induction programs, salaries, leaves, dues, and appraisals. Communication with Accounts − As front office department handles guest accounts with a complete responsibility, the staff needs to often interact with the back-office accounting colleagues regarding payment settlements or dues of guests or non-guests, discount offers, and coupons settlement. It also needs to sort out and get actual status of night auditing with accounts. Communication with Accounts − As front office department handles guest accounts with a complete responsibility, the staff needs to often interact with the back-office accounting colleagues regarding payment settlements or dues of guests or non-guests, discount offers, and coupons settlement. It also needs to sort out and get actual status of night auditing with accounts. Communication with Food and Beverage Department − Since front office department is the one where the guests speak about their food and beverage requirements during reservation, the front office needs to communicate with the food and beverage sections frequently. It also keeps the track of guest’s purchases from the restaurant, the bar, or coffee shops in the hotel. It conveys special requests of the guest regarding food and beverage to the F&B department. It deals, accepts, and reserves banquet inquiries and coordinates them with the respective departments. Communication with Food and Beverage Department − Since front office department is the one where the guests speak about their food and beverage requirements during reservation, the front office needs to communicate with the food and beverage sections frequently. It also keeps the track of guest’s purchases from the restaurant, the bar, or coffee shops in the hotel. It also keeps the track of guest’s purchases from the restaurant, the bar, or coffee shops in the hotel. It conveys special requests of the guest regarding food and beverage to the F&B department. It conveys special requests of the guest regarding food and beverage to the F&B department. It deals, accepts, and reserves banquet inquiries and coordinates them with the respective departments. It deals, accepts, and reserves banquet inquiries and coordinates them with the respective departments. Communication with Marketing and Sales Department − Sales and Marketing department highly relies upon front office inputs about the guests. The guest history compiled by the front office department is an excellent source for segmenting the customers, prepare customer-oriented packages, and plan and execute the campaigns. The front office staff contacts marketing and sales department in case there is a need to prepare electronic marquees or message boards for promotions. Communication with Marketing and Sales Department − Sales and Marketing department highly relies upon front office inputs about the guests. The guest history compiled by the front office department is an excellent source for segmenting the customers, prepare customer-oriented packages, and plan and execute the campaigns. The front office staff contacts marketing and sales department in case there is a need to prepare electronic marquees or message boards for promotions. Communication with Housekeeping − The front office staff needs to interact with the housekeeping department on the concerns such as − Readiness of vacated accommodation for selling. Security of the accommodation. Guest’s complaints and requirements about any amenities is initiated at the front desk. Guest’s requirement of removing soiled dishes or linen from the accommodation. In addition, the housekeeping department relies upon front office staff for the number of accommodations sold, departures, walk-ins, stay-over guests, and no-shows. Timely distribution of the accommodation sales helps the housekeeping manager to plan employee personal leaves and vacations. Communication with Housekeeping − The front office staff needs to interact with the housekeeping department on the concerns such as − Readiness of vacated accommodation for selling. Readiness of vacated accommodation for selling. Security of the accommodation. Security of the accommodation. Guest’s complaints and requirements about any amenities is initiated at the front desk. Guest’s complaints and requirements about any amenities is initiated at the front desk. Guest’s requirement of removing soiled dishes or linen from the accommodation. Guest’s requirement of removing soiled dishes or linen from the accommodation. In addition, the housekeeping department relies upon front office staff for the number of accommodations sold, departures, walk-ins, stay-over guests, and no-shows. Timely distribution of the accommodation sales helps the housekeeping manager to plan employee personal leaves and vacations. In addition, the housekeeping department relies upon front office staff for the number of accommodations sold, departures, walk-ins, stay-over guests, and no-shows. Timely distribution of the accommodation sales helps the housekeeping manager to plan employee personal leaves and vacations. Communication with Banqueting − The front office and banqueting department needs to interact with each other on the concerns such as − Expected number of guests to attend the banquet. Showing directions of the venue to the unfamiliar banquet guests. Posting of daily messages on felt board regarding venue, occasion, hosts and guests. Settling of the city account against the banquet service for the guest. Communication with Banqueting − The front office and banqueting department needs to interact with each other on the concerns such as − Expected number of guests to attend the banquet. Expected number of guests to attend the banquet. Showing directions of the venue to the unfamiliar banquet guests. Showing directions of the venue to the unfamiliar banquet guests. Posting of daily messages on felt board regarding venue, occasion, hosts and guests. Posting of daily messages on felt board regarding venue, occasion, hosts and guests. Settling of the city account against the banquet service for the guest. Settling of the city account against the banquet service for the guest. A vital link between the prospective guests and the hotel itself is switchboard operator who represents the hotel. When the customers call the hotel, the call first arrives at the switchboard operator. Using knowledge of the portfolio, tone of speaking, and the command over language the switchboard operator can handle the influx of the calls. The operator represents the competency of the hotel in the market while speaking with the customers. Generally, the switchboard operator greets the guests and transfers their call to appropriate department. There are two schools of thoughts regarding the area where a switchboard operator should work. Some experts say that they should be visible and some expert advice to assign a separate aloof place for them in the hotel. Today, the task of a switchboard operator for transferring the incoming calls to various departments is computerized and requires less human involvement. The switchboard operators are informed not to transfer any call to the executive chef or to the banquet manager during busy work hours. Hence, the operator needs to take the message accurately and pass them on to the respective persons on time. Communication necessarily is about verbal language as well as body language. Here are some common Do’s and Don’ts the front office staff follows while communicating − Always present yourself with a warm smile. Always present yourself with a warm smile. Always stand and walk erect which reflects your confidence. Always stand and walk erect which reflects your confidence. Get hold on to your domain subject. Try to know more about your portfolio. This saves you from the embarrassing situations when you are expected to answer the guests. Get hold on to your domain subject. Try to know more about your portfolio. This saves you from the embarrassing situations when you are expected to answer the guests. Before you start speaking, find out important points about the issue. Before you start speaking, find out important points about the issue. Speak in audible voice. Speak in audible voice. Use simple and correct language. Use simple and correct language. Use a language that can be understood by everyone. Use a language that can be understood by everyone. If you need to talk to your colleague in the presence of guest, talk in a standard language of communication. If you need to talk to your colleague in the presence of guest, talk in a standard language of communication. Speak only if it is going to be useful to the guests and colleagues. Always speak by maintaining eye contact with the listener. Speak only if it is going to be useful to the guests and colleagues. Always speak by maintaining eye contact with the listener. In case your conversation is interrupted, continue it with a short recap of what has been already discussed. In case your conversation is interrupted, continue it with a short recap of what has been already discussed. While you listen, always pay undivided attention to the speaker. Communicate to understand; not to react. While you listen, always pay undivided attention to the speaker. Communicate to understand; not to react. If the guest asks you to arrange for too many things, then repeat them for confirming. If the guest asks you to arrange for too many things, then repeat them for confirming. Ask politely if you have missed to hear any point the guest or the colleague is putting forward. Ask politely if you have missed to hear any point the guest or the colleague is putting forward. Do not use jargon or words such as “hmm-hmm”, “yep”, and alike. Instead, use “perfect”, “absolutely”, and similar words. Do not use jargon or words such as “hmm-hmm”, “yep”, and alike. Instead, use “perfect”, “absolutely”, and similar words. Do not speak too fast, too slow, or in too low or high voice. Do not speak too fast, too slow, or in too low or high voice. Do not interrupt the speaker. Do not interrupt the speaker. Do not speak with the colleagues, if it is not related to the business during working hours. Do not speak with the colleagues, if it is not related to the business during working hours. Do not speak under assumptions. Do not speak under assumptions. Do not hastily arrive at the conclusion unless you know. Do not hastily arrive at the conclusion unless you know. Do not run around the area of work. Do not run around the area of work. Do not appear harsh with your subordinates. Do not appear harsh with your subordinates. Do not appear untidy on work. Do not appear untidy on work. Front office communication not only includes verbal or textual communication but also body language of the staff. Following are some essential attributes the front office staff must have − Pleasant, sturdy, and agile personality High sense of good conduct and hygiene Ability to solve problems and decide quickly Salesmanship Integrity Punctuality Knowledge of etiquettes, and manners Command over language Confident yet polite nature Capacity to tackle situations of emergency Integrity and honesty Auditing is nothing but conducting financial inspection of the organization. For a hotel business, the finance management starts at the front office. Accurate posting of transactions on the guest folios start at the front office, which is further carried to the back-office accounting department. The guest accounts are counterchecked on a daily basis during auditing. Experts recommend the hotel management team to go through the night audit reports daily to get an insight of the hotel occupancy and finances. Let us see what night auditing is and details about the same. It is the process of auditing where the night auditor reviews all financial activities of the hotel that has taken place in one day. The auditing process for the day is generally conducted at the end of the day during the following night, hence the name ‘Night Audit’. It can be performed by the conventional method of using papers, receipts, vouchers, coupons, and files. But performing audit using modern PMS systems is easy, fast, and efficient. The night auditor performs the following steps during night audit activity − Posting accommodation and tax charg Accumulating guest service charges and payments Settling financial activities of various departments Settling the account receivables Running the trial balance for the day Preparing the night audit report The objective of night audit is to evaluate the hotel’s financial activities. Night audit not only reviews guest accounts by checking credits and debits but also tracks the credit limits of the guests and tallies projected and actual sales from various departments. Night audit reviews daily cash flow into and out of the hotel’s account. Night audit has a large significance in hotel business operations. The management body refers night audit report to plan future goals and control the expenses. The managers can react immediately on the acquired information. Apart from the basic audit activities listed above, the night auditor carries out the following responsibilities − Taking over from the last shift. Checking-in or checking-out the guests after 11:00 pm at night. Registering the guests. Allocating accommodations to the newly checked-in guests. Settling transactions in the newly created guest accounts. Verifying guest folios. Verifying room status report. Balancing all paperwork with the accounts in the PMS. Remaining liable for security of the premises. Handling guest accommodation keys. Taking backup of the PMS generated reports. Preparing lists of expected guest arrivals for the next day. Closing financial activities for a day. Starting financial activities for the next day. Receiving and recording bank deposits. Today, the PMS helps night auditors to a great extent in auditing and generating accurate reports. Here are some typical reports generated during night audit − Night Audit Accommodation Report − It gives a snapshot of the days when accommodations are occupied, the days when the accommodations are available, check-ins, check-outs, no-shows, and cancellations. This report can show further details for any of the items listed above. Night Audit Accommodation Report − It gives a snapshot of the days when accommodations are occupied, the days when the accommodations are available, check-ins, check-outs, no-shows, and cancellations. This report can show further details for any of the items listed above. Night Audit Counter Report − It gives details on cash and credit card receipts and withdrawals. Night Audit Counter Report − It gives details on cash and credit card receipts and withdrawals. Night Audit Revenue Report − It delivers information on accommodation revenue, cancellation and no show revenue, and other POS revenue. Revenue generated through various agencies and bodies such as travel agents, corporate organizations, internet booking. etc., is also listed in this report. Night Audit Revenue Report − It delivers information on accommodation revenue, cancellation and no show revenue, and other POS revenue. Revenue generated through various agencies and bodies such as travel agents, corporate organizations, internet booking. etc., is also listed in this report. Night Audit Tax Report − Contains all the tax information on reservation revenue and other POS revenues such as VAT, luxury tax, and service tax. Night Audit Tax Report − Contains all the tax information on reservation revenue and other POS revenues such as VAT, luxury tax, and service tax. Cashier’s report − It is the detailed list of cashier activity of cash influx and out flux, credit cards, and PMS totals. Cashier’s report is very important part of the financial control system of a hotel. The front office manager reviews the night audit and looks for any divergences between the actual amount received and the PMS total. Cashier’s report − It is the detailed list of cashier activity of cash influx and out flux, credit cards, and PMS totals. Cashier’s report is very important part of the financial control system of a hotel. The front office manager reviews the night audit and looks for any divergences between the actual amount received and the PMS total. Manager’s Report − It is a statistical list of previous day’s occupancy. It includes details about available accommodations, occupied accommodations, sold and vacated accommodations, rack-rate, number of guests in the hotel, number of no-shows, and so on. Manager’s Report − It is a statistical list of previous day’s occupancy. It includes details about available accommodations, occupied accommodations, sold and vacated accommodations, rack-rate, number of guests in the hotel, number of no-shows, and so on. General Manager’s Report − Each department in the hotel is required to send daily sales report to the front office. Using their information, a departmental total report is generated for the general manager’s assessment. The General Manager determines the profit-generating departments and evaluates the success of sales and marketing. General Manager’s Report − Each department in the hotel is required to send daily sales report to the front office. Using their information, a departmental total report is generated for the general manager’s assessment. The General Manager determines the profit-generating departments and evaluates the success of sales and marketing. High Balance Report − This is a detailed report about the guests who have exceeded the credit limit set by the hotel management. High Balance Report − This is a detailed report about the guests who have exceeded the credit limit set by the hotel management. Ledger Balance Summary Report − It displays the opening and closing balances for the Advance Deposit Ledger, Guest Ledger, and City Ledger. Ledger Balance Summary Report − It displays the opening and closing balances for the Advance Deposit Ledger, Guest Ledger, and City Ledger. Room Rate Audit Report − It lists all rates that are applied to each guest and the difference from the rack rate with the predetermined rack code. Room Rate Audit Report − It lists all rates that are applied to each guest and the difference from the rack rate with the predetermined rack code. Here are some formulae used to balance night audit − The formula for balancing bank deposit is − Total Bank Deposits - Total Cash Sales - Credit card received A/R – Cash received A/R = 0 The formula for balancing guest ledger is − Total Revenue - Paid-outs and non-collect sales = Daily revenue - Total cash income - Today’s outstanding A/R income = 0 The formula for balancing city ledger is − Yesterday's outstanding A/R + Today's outstanding A/R income = Total outstanding A/R - Credit card received and applied to A/R – Cash received and applied to A/R = balance of A/R In any business organization, common procedures occur in sequence. They are linear. In addition, some procedures also repeat over a time. The organization needs to find out such linear and repeating procedures to compile them into sets of Standard Operating Procedures (SOPs). These procedures when compiled step by step, can prove to be an excellent learning material for training the newly joined staff in a short period of time. Let us learn about a few SOPs followed in the front office department. This is a procedure followed by the bell desk staff at the time of the guest’s arrival and departure. It goes as follows − As a bellboy look for the new arrival of guest. The guest vehicle stops at the hotel entrance. Go ahead and open the vehicle door. Greet the guest as, "Welcome to (hotel_name), I am (own_name). Do you need any help with your luggage?" Help the elderly/disables guests to get out of the vehicle if required. Take the luggage in charge and ensure that nothing is left in the vehicle. Ask the guest’s name politely as, "May I know your name Sir/Madam?" Tag the luggage with the guest name. Ask if anything fragile or perishable is in the luggage. Add this information on the luggage tag. Inform the guest that their luggage is with you. Escort the guest to the hotel reception. Inform the guest that you will be taking care of their luggage. With the other front office staff, find out the accommodation number allotted to the guest. Write the accommodation number on the luggage tag. Confirm if the guest registration formality is complete. If the room is ready, take the luggage to the room by the staff elevator. Place the luggage on the luggage rack. If the room is not ready, then take the luggage to the store room. Record the luggage details into the Daily Luggage Register. Inform the guest that you are going to guest’s accommodation to collect the luggage. Inform the guest that you are going to guest’s accommodation to collect the luggage. Have an informal conversation with the guest as, "Mr./Ms. (Guest_Name), I hope you enjoyed your stay with us. Do you need an airport transport?" Have an informal conversation with the guest as, "Mr./Ms. (Guest_Name), I hope you enjoyed your stay with us. Do you need an airport transport?" Collect the luggage from the guest room. Collect the luggage from the guest room. If the guest needs to store the luggage for long term, tag the luggage with the guest name, accommodation number, date and time of collection, contact number, and receive the guest’s signature on long-term luggage request form. If the guest needs to store the luggage for long term, tag the luggage with the guest name, accommodation number, date and time of collection, contact number, and receive the guest’s signature on long-term luggage request form. Ensure with the guest that nothing perishable is there in the luggage. Ensure with the guest that nothing perishable is there in the luggage. Store the luggage on the designated departure area. Store the luggage on the designated departure area. If the guest is leaving the hotel immediately after check-out, then bring the luggage to the lobby. If the guest is leaving the hotel immediately after check-out, then bring the luggage to the lobby. If a transport vehicle is ready to go then place the luggage in the vehicle. If a transport vehicle is ready to go then place the luggage in the vehicle. Request the guest to verify the loaded luggage. Request the guest to verify the loaded luggage. Update the departure luggage movement on the Daily Luggage movement register. Update the departure luggage movement on the Daily Luggage movement register. The SOP goes as follows − Pick up the incoming call in three rings. Pick up the incoming call in three rings. Greet the guest in the audible voice, introduce yourself, and ask how you can help the guest as, “Good (morning/evening), this is Mr./Ms. own_name, how may I help you?” Greet the guest in the audible voice, introduce yourself, and ask how you can help the guest as, “Good (morning/evening), this is Mr./Ms. own_name, how may I help you?” Wait for the guest to respond. Wait for the guest to respond. The guests say that he/she needs an accommodation in your hotel. The guests say that he/she needs an accommodation in your hotel. Tell the guest that it’s your pleasure. Tell the guest that it’s your pleasure. Take a new reservation form. Take a new reservation form. Inform the guest about the types of accommodations in your hotel and their respective charges. Inform the guest about the types of accommodations in your hotel and their respective charges. Ask for the guest’s name, contact number, and type of accommodation the guest wants. Ask for the guest’s name, contact number, and type of accommodation the guest wants. Ask for the guest’s dates of arrival and departure. Ask for the guest’s dates of arrival and departure. Check for availability of the accommodation during those dates. Check for availability of the accommodation during those dates. Briefly describe the amenities the hotel provides to its guests. Briefly describe the amenities the hotel provides to its guests. If the accommodation is available, inform the guest. If the accommodation is available, inform the guest. If exactly the same kind of accommodation is not available, ask the guest if he/she would care for another type of accommodation. If exactly the same kind of accommodation is not available, ask the guest if he/she would care for another type of accommodation. Note down the guest’s requirements related to the accommodation. Note down the guest’s requirements related to the accommodation. Ask the guest if an airport pickup/drop service is required. Ask the guest if an airport pickup/drop service is required. Ask how the guest would settle the bill: by cash, credit, or direct billing. Ask how the guest would settle the bill: by cash, credit, or direct billing. If the guest prefers by cash or by card, then insist to pay the part of cash in advance against booking charges or credit card details of the guest. If the guest prefers by cash or by card, then insist to pay the part of cash in advance against booking charges or credit card details of the guest. Inform about reservation with the guest name, contact number, accommodation type required, payment method, and confirmation number. Inform about reservation with the guest name, contact number, accommodation type required, payment method, and confirmation number. Conclude the conversation as, “Thank you for calling hotel_name, have a nice day!” Conclude the conversation as, “Thank you for calling hotel_name, have a nice day!” The SOP goes as follows − Upon the guest’s arrival, greet the guest. Ask the guest for his/her name politely. Search the reservation record in the PMS. Generate and print a registration card. Handover a GRC to the guest for verifying printed details. Request the guest to show the ID card from an authorized institute. Request to show passport and visa in case of foreigner guest. Request the guest to fill in the following details on the GRC − Salutation Designation Organization Business or Residence Address with City and ZIP Code Purpose of Visit Contact Number in case of Emergency Passport Details Visa Details Salutation Designation Organization Business or Residence Address with City and ZIP Code Purpose of Visit Contact Number in case of Emergency Passport Details Visa Details Inform the guest about any early/late check-out policies. Request the guest to sign on the GRC. Counter-sign the GRC. Update the details on the guest record. Create a guest account. Prepare copies of driving license/passport and visa. Attach them to the GRC and file the entire set. There are manual and automatic wakeup calls. The guest can request for a wakeup call at the front office directly or by calling from his/her own accommodation. The guest can request for a wakeup call at the front office directly or by calling from his/her own accommodation. Ask the guest for a wake-up time and any immediate special request after getting up. Ask the guest for a wake-up time and any immediate special request after getting up. Open the Wakeup Call Register and enter the following information − Salutation Guest Name Accommodation number Wakeup date Wakeup time Any Special immediate request such as tea/coffee, etc. Open the Wakeup Call Register and enter the following information − Salutation Salutation Guest Name Guest Name Accommodation number Accommodation number Wakeup date Wakeup date Wakeup time Wakeup time Any Special immediate request such as tea/coffee, etc. Any Special immediate request such as tea/coffee, etc. Conclude the conversation by greeting the guest again. Conclude the conversation by greeting the guest again. Pass the special request for tea/coffee to the room service staff. Pass the special request for tea/coffee to the room service staff. At the time of wakeup call, follow the given steps − Confirm the current time. Call the guest’s accommodation number on telephone. Greet the guest as per the time and inform about the current time and the progress on guest’s special request. At the time of wakeup call, follow the given steps − Confirm the current time. Confirm the current time. Call the guest’s accommodation number on telephone. Call the guest’s accommodation number on telephone. Greet the guest as per the time and inform about the current time and the progress on guest’s special request. Greet the guest as per the time and inform about the current time and the progress on guest’s special request. Most hotels facilitate their guests to set automatic wakeup call using their phones or televisions. The housekeeper must ensure that the printed instructions about setting an automatic call are kept handy and visible. The guest can set automatic call which is notified at the PBX system and the PMS system. Even if the guest has set up an automatic call, it is the responsibility of the front office staff to give a manual wakeup call to the guest to avoid any chances of inconvenience. The process of checking out generally is initiated by the guest. The guest calls up front office and asks to keep the bill ready. The guest arrives at the front desk. Greet the guest. Print a copy of guest folio. Hand it over to the guest for verification. If there is any discrepancy, assure the guest about its solving. Resolve the discrepancy immediately. Apologize to the guest for inconvenience. From the guest database, ensure the guest’s preference of payment method. Recite it to the guest. Settle the guest account. Print the receipt and give it to the guest. Ask the guest if he/she needs any assistance for luggage. Ask the guest if the transport facility to the airport is required. Greet the guest for giving an opportunity to serve as, “Hope you enjoyed your stay with us. Thank you. Good (morning/afternoon/night). The guests initiate the cancellation of the reserved accommodation. The SOP goes as − Request for the guest’s full name and reservation number. Request for the guest’s full name and reservation number. Search the guest database for the given name and reservation number. Search the guest database for the given name and reservation number. Recite the guest name, accommodation details and the date of reservation. Recite the guest name, accommodation details and the date of reservation. Ask the guest if he/she would like to postpone it. Ask the guest if he/she would like to postpone it. Request the guest for reason behind cancellation. Request the guest for reason behind cancellation. Record the reason in the PMS. Record the reason in the PMS. If the cancellation is being done by a person other than the guest, record the person’s name, contact number, and relation with the guest for information. If the cancellation is being done by a person other than the guest, record the person’s name, contact number, and relation with the guest for information. Inform the caller about any cancellation charges applicable according to the hotel policies. Inform the caller about any cancellation charges applicable according to the hotel policies. Cancel the reservation in the PMS. Cancel the reservation in the PMS. Inform the guest about e-mail for cancellation charges. Send the cancellation charges plus cancellation number to the guest by e-mail. Inform the guest about e-mail for cancellation charges. Send the cancellation charges plus cancellation number to the guest by e-mail. The front office staff needs to manage at least two sets of the keys. The number of sets may vary according to the guest policy. Accommodation numbers are not written on the keys, which creates problems when the keys are misplaced within or around the premises. Request for the guest’s last name and accommodation number. Request for the guest’s last name and accommodation number. Check the information told by the guest against the one recorded in PMS. Check the information told by the guest against the one recorded in PMS. If there is any deviation, request the guest to provide photo ID card. If there is any deviation, request the guest to provide photo ID card. Do not give away the accommodation key without proper authentication. Do not give away the accommodation key without proper authentication. If the doubt about the guest arises and the guest refuses to cooperate, then inform the front office manager immediately. If the doubt about the guest arises and the guest refuses to cooperate, then inform the front office manager immediately. If any other superior front office staff member recognizes the guest, then you can give away the duplicate key. If any other superior front office staff member recognizes the guest, then you can give away the duplicate key. If the guest has lost the key and needs a new one, then ascertain that the guest has lost it. If the guest has lost the key and needs a new one, then ascertain that the guest has lost it. In the above case, program a new key with the same code. In the above case, program a new key with the same code. Present the newly created key to the guest. Present the newly created key to the guest. You must not issue accommodation keys to any person that claims to be sent by the guest for getting the keys. Yet, you can give them to a non-guest, if the guest has sent the person with a written authority letter addressed to the front office team. In such case, confirm by calling the guest and accompany the non-guest to the accommodation. You must not issue accommodation keys to any person that claims to be sent by the guest for getting the keys. Yet, you can give them to a non-guest, if the guest has sent the person with a written authority letter addressed to the front office team. In such case, confirm by calling the guest and accompany the non-guest to the accommodation. The authorized staff on duty is allowed to access the occupied guest accommodation for the purpose of professional work. For example, the keys can be given for preparing vacated accommodation, laundry staff, mini-bar staff, and bell-boy to take out the guest luggage. One thing for sure, always try to solve the guest’s accommodation problem as far as possible. Try selling hotel service by giving options than plainly denying to what the guest wants. There are a number of reasons why a reservation staff needs to turn down the reservation request. These are few important ones − The hotel is fully booked during busy seasons. Guest is not interested to reserve after knowing rates. The type of accommodation the guest desires is not available. This is how you turn down a reservation gracefully − When the guest calls to enquire, answer the call as, “Good (morning, evening), this is own_name from reservations. How may I help you?” When the guest calls to enquire, answer the call as, “Good (morning, evening), this is own_name from reservations. How may I help you?” The guest says he/she would like to reserve an accommodation. The guest says he/she would like to reserve an accommodation. Reply as, “Certainly (Sir/Madam). May I request you for your name, mobile number and email ID please?” Reply as, “Certainly (Sir/Madam). May I request you for your name, mobile number and email ID please?” The guest tells the same. The guest tells the same. Further ask, “And your company/travel agency name is?” Further ask, “And your company/travel agency name is?” The guest replies, “I am from (Company/TA name)”. The guest replies, “I am from (Company/TA name)”. Ask the guest about check-in and check-out dates required for reservation. Ask the guest about check-in and check-out dates required for reservation. Request the guest to hold the line till you search for availability of the desired accommodation. Request the guest to hold the line till you search for availability of the desired accommodation. Inform the guest approximately how much time you would take to find out. Inform the guest approximately how much time you would take to find out. Put the call on hold and check availability. Put the call on hold and check availability. Convey the non-availability of the desired type of accommodation to the guest politely as, “Sorry sir/madam, “(all the accommodations are occupied/the desired type of accommodation is not available)”. Convey the non-availability of the desired type of accommodation to the guest politely as, “Sorry sir/madam, “(all the accommodations are occupied/the desired type of accommodation is not available)”. Suggest the guest about a nearby sister-concern hotel, if any. Suggest the guest about a nearby sister-concern hotel, if any. Suggest the guest to take other similar kind of accommodation by describing its amenities. Suggest the guest to take other similar kind of accommodation by describing its amenities. If the guest doesn’t agree to it, turn away politely as, “Sorry sir, then we don’t have any other available accommodation.” If the guest doesn’t agree to it, turn away politely as, “Sorry sir, then we don’t have any other available accommodation.” Record the guest data in the PMS along with the ‘Turn away’ reason. Record the guest data in the PMS along with the ‘Turn away’ reason. Hotel business is of a kind that needs to provide a myriad range of services to its guests such as food, accommodation, transport, recreational services, and so on. Since the front office contributes major portion in coordinating the services requested by the guests, it needs a system that can help the front office staff to sell services and track them seamlessly and simultaneously. The front office information system includes mainly the property management system. Let us see, what PMS is and how useful it is for handling hotel management functions smoothly. A Property Management System (PMS) is a software system employed to handle basic objectives of all the departments in the hotel business and coordinate functions between them for optimum business outcomes. A PMS is required for the hotel staff for the following reasons − It integrates all critical operations of the hotel on one platform. It integrates all critical operations of the hotel on one platform. It provides real-time information on accommodations, reservations, restaurants, spas, bars, and about every working arm of the hotel. It provides real-time information on accommodations, reservations, restaurants, spas, bars, and about every working arm of the hotel. It provides highly accurate information which is helpful for the management to plan new goals and handle the investments in a better way. It provides highly accurate information which is helpful for the management to plan new goals and handle the investments in a better way. It boosts the efficiency of the front office staff and in turn maximizes the performance of the hotel business. It boosts the efficiency of the front office staff and in turn maximizes the performance of the hotel business. It simplifies the time-taking or complex operations otherwise done manually. It simplifies the time-taking or complex operations otherwise done manually. It works for the convenience of the hotel staff, managing body, as well as the guests. It works for the convenience of the hotel staff, managing body, as well as the guests. There are two basic types of PMS − Local PMS − They have large technical requirements such as workstation, Computer/workstation, Data server, Terminal servers, Operating system, Network cards, and Removable back-up systems. Local PMS − They have large technical requirements such as workstation, Computer/workstation, Data server, Terminal servers, Operating system, Network cards, and Removable back-up systems. Cloud-based PMS − They mainly need computers/workstation and Internet connection. Cloud-based PMS − They mainly need computers/workstation and Internet connection. Availing the PMS Owner needs to purchase the PMS hardware and software. Owner needs to take subscription from a PMS vendor. Requirement of Internet Connection No Yes, a reliable high speed connection is mandatory. System and Access PMS software and data reside on a server to which multiple terminals are connected. The PMS is accessed from a program installed on each terminal. PMS software and data reside on a shared server at the PMS vendor’s data center. Users access the system through a Web browser from anywhere, anytime. Requirement of On-site IT expertise Yes No Advantages Does not rely on an Internet connection. Reduces concerns about online data security. Robust functionality for vast amount of data. Less costs of hardware or IT. No technical and data security responsibility on owner. Affordable subscription pricing. Simple, quick set-up. Easy access from anywhere, anytime. Automatic data back-up. Integrated Web bookings. Free system upgrades. Scalable and adaptable. Disadvantages Requires complex and expensive hardware. Unreachable from remote areas. Expensive and complicated to maintain and upgrade. Time-consuming, software installation and training. Additional costs and hardware needed for enabling web-based features Responsibility of system and data security is owner’s headache. On-site IT expertise is required. Not suitable for properties without a reliable Internet connection. High concerns over online security. Mark on Timeline It is a traditional solution. It is a contemporary solution. Pricing Capital expenditure and operational expenditure both; for hardware, software and its updates, and IT expert’s charges. Operational expenses for renewing subscription. Some popular PMS: Autoclerk, Skyware MSICloud, CloudPM, eZee Frontdesk, Hotelogix, Hetello, Hoteliga, OpenHotel, OPERA PMS, are to name a few. A PMS takes care of each department in the hotel. These are the commonly available features among PMS − Reservation Registration Accommodation status Guest and non-guest accounts Cash handling Night auditing Reports Guest database for market segmentation Guest history Yield management Travel agents information as clients Reports for goals Performance evaluation by comparative analysis Lost and found Accommodation status Laundry charges POS sales Material inventory Periodic sales reports Standard recipes Individual staff member’s records regarding shifts, attendance, and appraisals. Account payables and receivables Payroll Balance sheet Profit/Loss reports Outgoing and incoming call records with date, time, place, duration, and charges. The following concerns are considered while selecting an appropriate PMS − Size of the property: The number of accommodations Number of locations Number of employees Property service policies Budget for technical resources and training Nearest future growth User-friendly design that fosters intuitive navigation through logical order of tasks. Training expertise and time period required to train the staff. Hotel’s online presence. Guest-oriented functionality. Scalability. 127 Lectures 16.5 hours Joseph Delgadillo 131 Lectures 12.5 hours Sandra L 55 Lectures 11 hours Emenwa Global, Ejike IfeanyiChukwu 107 Lectures 12.5 hours Code And Create 103 Lectures 16.5 hours Nick O Print Add Notes Bookmark this page
[ { "code": null, "e": 2436, "s": 1990, "text": "Every multi-departmental physical business needs to have a front office or reception to receive the visitors. Front Office Department is the face and as well as the voice of a business. Regardless of the star rating of the hotel or the hotel type, the hotel has a front office as its most visible department. For a business such as hospitality, the front office department comes with an aspect of elevating customer experience with the business." }, { "code": null, "e": 2545, "s": 2436, "text": "Front Office department is a common link between the customers and the business. Let us learn more about it." }, { "code": null, "e": 2746, "s": 2545, "text": "It is the one of the many departments of the hotel business which directly interacts with the customers when they first arrive at the hotel. The staff of this department is very visible to the guests." }, { "code": null, "e": 2946, "s": 2746, "text": "Front office staff handles the transactions between the hotel and its guests. The staff receives the guests, handles their requests, and strikes the first impression about the hotel into their minds." }, { "code": null, "e": 2981, "s": 2946, "text": "Front office department includes −" }, { "code": null, "e": 2992, "s": 2981, "text": "Front Desk" }, { "code": null, "e": 3011, "s": 2992, "text": "Uniformed services" }, { "code": null, "e": 3022, "s": 3011, "text": "Concierges" }, { "code": null, "e": 3053, "s": 3022, "text": "Front Office Accounting System" }, { "code": null, "e": 3140, "s": 3053, "text": "Private Branch Exchange (PBX), a private telephone network used within an organization" }, { "code": null, "e": 3213, "s": 3140, "text": "Following are the most basic responsibilities a front office can handle." }, { "code": null, "e": 3237, "s": 3213, "text": "Creating guest database" }, { "code": null, "e": 3261, "s": 3237, "text": "Handling guest accounts" }, { "code": null, "e": 3288, "s": 3261, "text": "Coordinating guest service" }, { "code": null, "e": 3313, "s": 3288, "text": "Trying to sell a service" }, { "code": null, "e": 3341, "s": 3313, "text": "Ensuring guest satisfaction" }, { "code": null, "e": 3385, "s": 3341, "text": "Handling in-house communication through PBX" }, { "code": null, "e": 3439, "s": 3385, "text": "There are two categories of Front Office Operations −" }, { "code": null, "e": 3620, "s": 3439, "text": "These operations are visible to the guests of the hotel. The guests can interact and see these operations, hence, the name Front-House operations. Few of these operations include −" }, { "code": null, "e": 3688, "s": 3620, "text": "Interacting with the guests to handle request for an accommodation." }, { "code": null, "e": 3755, "s": 3688, "text": "Checking accommodation availability and assigning it to the guest." }, { "code": null, "e": 3811, "s": 3755, "text": "Collecting detail information while guest registration." }, { "code": null, "e": 3869, "s": 3811, "text": "Creating a guest’s account with the FO accounting system." }, { "code": null, "e": 3910, "s": 3869, "text": "Issuing accommodation keys to the guest." }, { "code": null, "e": 3959, "s": 3910, "text": "Settling guest payment at the time of check-out." }, { "code": null, "e": 4128, "s": 3959, "text": "Front Office staff conducts these operations in the absence of the guests or when the guest’s involvement is not required. These operations involve activities such as −" }, { "code": null, "e": 4199, "s": 4128, "text": "Determining the type of guest (fresh/repeat) by checking the database." }, { "code": null, "e": 4274, "s": 4199, "text": "Ensuring preferences of the guest to give a personal touch to the service." }, { "code": null, "e": 4330, "s": 4274, "text": "Maintaining guest’s account with the accounting system." }, { "code": null, "e": 4358, "s": 4330, "text": "Preparing the guest’s bill." }, { "code": null, "e": 4404, "s": 4358, "text": "Collecting the balance amount of guest bills." }, { "code": null, "e": 4424, "s": 4404, "text": "Generating reports." }, { "code": null, "e": 4527, "s": 4424, "text": "Generally, a guest’s interaction with the hotel is divided into the following four sequential phases −" }, { "code": null, "e": 4887, "s": 4527, "text": "It is the stage when the customer is planning to avail an accommodation in the hotel. In this first stage, the customer or the prospective guest enquires about the availability of the desired type of accommodation and its amenities via telephonic call or an e-mail. The customer also tries to find out more information about the hotel by visiting its website." }, { "code": null, "e": 5067, "s": 4887, "text": "At the hotel end, the front office accounting system captures the guest’s information such as name, age, contact numbers, probable duration of stay for room reservation and so on." }, { "code": null, "e": 5663, "s": 5067, "text": "The front office reception staff receives the guest in the reception. The porters bring in the guest luggage. For the guest with confirmed reservation, the front office clerk hands over a Guest Registration Card (GRC) to the guest and requests the guest to fill in personal information regarding the stay in the hotel. The clerk then registers the guest in the database thereby creating a guest record and a guest account along with it. Later, the clerk hands over a welcome kit and keys of the accommodation. After the procedure of registration, the guest can start occupying the accommodation." }, { "code": null, "e": 6165, "s": 5663, "text": "During occupancy, a front office accounting system is responsible for tracking guest charges against his/her purchases from the hotel restaurants, room service, bar, or any outgoing telephone calls made via the hotel’s communication systems. The front office staff is responsible to manage and issue the right keys of the accommodations to the right guests. On guests’ request, the staff also makes arrangement for transportation, babysitting, or local touring while the guest is staying in the hotel." }, { "code": null, "e": 6471, "s": 6165, "text": "During guest departure, the front office accounting system ensures payment for goods and services provided. If a guest’s bill is not completely paid, the balance is transferred from guest to non-guest records. When this occurs, collection becomes the responsibility of the back office accounting division." }, { "code": null, "e": 6717, "s": 6471, "text": "At the time of guest departure, the front office staff thanks the guest for giving an opportunity to serve and arrange for handling luggage. In addition, if the guest requires airport or other drop service, the front office bell desk fulfils it." }, { "code": null, "e": 6799, "s": 6717, "text": "Following are some common terms used in relation to the front office department −" }, { "code": null, "e": 6819, "s": 6799, "text": "Account receivables" }, { "code": null, "e": 6966, "s": 6819, "text": "The amount of money an organization has the right to receive within some specified period (say 30 days) against the delivery of products/services." }, { "code": null, "e": 6976, "s": 6966, "text": "Bell desk" }, { "code": null, "e": 7048, "s": 6976, "text": "An extension of front desk that deals with personalized guest services." }, { "code": null, "e": 7069, "s": 7048, "text": "Cancellation charges" }, { "code": null, "e": 7200, "s": 7069, "text": "They are the charges borne by the guest on cancellation of a confirmed reservation or for not showing-up on confirmed reservation." }, { "code": null, "e": 7210, "s": 7200, "text": "Concierge" }, { "code": null, "e": 7304, "s": 7210, "text": "Information desk that assists guests for transportation, booking of events outside the hotel." }, { "code": null, "e": 7308, "s": 7304, "text": "GRC" }, { "code": null, "e": 7419, "s": 7308, "text": "Guest Registration Card, which the guest needs to fill in with personal formation at the time of registration." }, { "code": null, "e": 7425, "s": 7419, "text": "Guest" }, { "code": null, "e": 7470, "s": 7425, "text": "Customer of the hotel business being served." }, { "code": null, "e": 7477, "s": 7470, "text": "IP-PBX" }, { "code": null, "e": 7575, "s": 7477, "text": "Internet Protocol Private Branch Exchange, where internet protocol is used for call transmission." }, { "code": null, "e": 7580, "s": 7575, "text": "MICE" }, { "code": null, "e": 7644, "s": 7580, "text": "Acronym for Meetings, Incentives, Conferences, and Exhibitions." }, { "code": null, "e": 7654, "s": 7644, "text": "Non-guest" }, { "code": null, "e": 7715, "s": 7654, "text": "Customer of a hotel business not being served at the moment." }, { "code": null, "e": 7723, "s": 7715, "text": "No-show" }, { "code": null, "e": 7798, "s": 7723, "text": "A guest who has reserved an accommodation neither turns up nor cancels it." }, { "code": null, "e": 7803, "s": 7798, "text": "OHMS" }, { "code": null, "e": 7902, "s": 7803, "text": "Online Hotel Management System, a software system to manage all back-office operations of a hotel." }, { "code": null, "e": 7906, "s": 7902, "text": "PBX" }, { "code": null, "e": 7987, "s": 7906, "text": "Private Branch Exchange, a private network of telephones within an organization." }, { "code": null, "e": 7991, "s": 7987, "text": "POS" }, { "code": null, "e": 8109, "s": 7991, "text": "Acronym for Point of Sale. It is the revenue generating place in the hotel where retail transactions are carried out." }, { "code": null, "e": 8119, "s": 8109, "text": "Rack rate" }, { "code": null, "e": 8189, "s": 8119, "text": "The price at which the hotel rooms are sold before applying discount." }, { "code": null, "e": 8195, "s": 8189, "text": "SMERF" }, { "code": null, "e": 8264, "s": 8195, "text": "Acronym for Social, Military, Educational, Religious, and Fraternal." }, { "code": null, "e": 8278, "s": 8264, "text": "Trial balance" }, { "code": null, "e": 8416, "s": 8278, "text": "It is a report of accounts that represents ending balance of each account in the list. It is prepared at the end of an accounting period." }, { "code": null, "e": 8435, "s": 8416, "text": "Uniformed services" }, { "code": null, "e": 8481, "s": 8435, "text": "Personalized services provided to the guests." }, { "code": null, "e": 8487, "s": 8481, "text": "Valet" }, { "code": null, "e": 8531, "s": 8487, "text": "A male attendant to park and clean the car." }, { "code": null, "e": 8546, "s": 8531, "text": "Whitney System" }, { "code": null, "e": 8598, "s": 8546, "text": "An old reservation system for hotel accommodations." }, { "code": null, "e": 8615, "s": 8598, "text": "Yield Management" }, { "code": null, "e": 8779, "s": 8615, "text": "A variable pricing strategy, based on understanding, anticipating and influencing consumer behavior in order to maximize revenue from a fixed, perishable resource." }, { "code": null, "e": 9117, "s": 8779, "text": "Front office area is commonly termed as ‘Reception’, as it is the place where the guests are received when they arrive at the hotel. It is the first point of interaction between the hotel and the guests. Being the prime interface between the hotel services and the guests, the front office is located near the main entrance of the hotel." }, { "code": null, "e": 9239, "s": 9117, "text": "The front office structure can be viewed in two ways: the physical setup and the operational structure of the department." }, { "code": null, "e": 9468, "s": 9239, "text": "The physical setup includes key-hanging boards, bell desk and guest-mail handling register. The front desk is equipped with various compartments, the computerized property management system, and an in-house communication system." }, { "code": null, "e": 9708, "s": 9468, "text": "The front desk is where the guests temporarily await to find an accommodation or to clear their bill. Hence, it needs to be positioned appropriately such that the staff and the guests can use them conveniently. The front desk needs to be −" }, { "code": null, "e": 9752, "s": 9708, "text": "Positioned at an adequate height and reach." }, { "code": null, "e": 9779, "s": 9752, "text": "An adequately lit-up area." }, { "code": null, "e": 9804, "s": 9779, "text": "Aesthetically furnished." }, { "code": null, "e": 9846, "s": 9804, "text": "Preferably near the hotel lobby and lift." }, { "code": null, "e": 9880, "s": 9846, "text": "Preferably near the sitting area." }, { "code": null, "e": 9962, "s": 9880, "text": "Wide enough to make the staff member communicate with the guests across the desk." }, { "code": null, "e": 10170, "s": 9962, "text": "The front office staff needs to communicate with the staff of the same as well as all other departments of the hotel. This is termed as internal communication. It mostly relies upon the PBX or IP-PBX system." }, { "code": null, "e": 10349, "s": 10170, "text": "When the front office communicates with the potential customers outside the hotel, corporate offices, and other ancillary service providers, then it is an external communication." }, { "code": null, "e": 10596, "s": 10349, "text": "Any formal communication outside the hotel is mostly carried out using e-mails and phone calls. For sending coupons or other promotional material, renewing agreements with travel agents or airlines, the front office staff may opt for postal mail." }, { "code": null, "e": 10884, "s": 10596, "text": "There are lot of staff working under front office manager. The structure of the front office department changes according to the size of the hotel business, physical size of the hotel, and the hotel management policies. Following is the general structure of the front office department −" }, { "code": null, "e": 11097, "s": 10884, "text": "Front office department manager heads the team of staff working on various activities and responsibilities in the front office department. Few prominent activities that the front office staff is involved in are −" }, { "code": null, "e": 11183, "s": 11097, "text": "Reservation − It includes handling request of customers for reserving accommodations." }, { "code": null, "e": 11269, "s": 11183, "text": "Reservation − It includes handling request of customers for reserving accommodations." }, { "code": null, "e": 11426, "s": 11269, "text": "Reception − It includes receiving the guests according to the highest standards and registering them appropriately. It also includes bidding the guests off." }, { "code": null, "e": 11583, "s": 11426, "text": "Reception − It includes receiving the guests according to the highest standards and registering them appropriately. It also includes bidding the guests off." }, { "code": null, "e": 11994, "s": 11583, "text": "Guest Services − They are also known as Uniformed Services. It includes personalized guest services such as −\n\nHandling guest luggage.\nHandling guest mail.\nDelivering newspapers in accommodations.\nPaging the guest inside the hotel (locating the guest in the hotel).\nArranging for a doctor in emergency.\nParking guest’s automobiles.\nArranging for reservations at the places of entertainment outside the hotel.\n\n" }, { "code": null, "e": 12104, "s": 11994, "text": "Guest Services − They are also known as Uniformed Services. It includes personalized guest services such as −" }, { "code": null, "e": 12128, "s": 12104, "text": "Handling guest luggage." }, { "code": null, "e": 12149, "s": 12128, "text": "Handling guest mail." }, { "code": null, "e": 12190, "s": 12149, "text": "Delivering newspapers in accommodations." }, { "code": null, "e": 12259, "s": 12190, "text": "Paging the guest inside the hotel (locating the guest in the hotel)." }, { "code": null, "e": 12296, "s": 12259, "text": "Arranging for a doctor in emergency." }, { "code": null, "e": 12325, "s": 12296, "text": "Parking guest’s automobiles." }, { "code": null, "e": 12402, "s": 12325, "text": "Arranging for reservations at the places of entertainment outside the hotel." }, { "code": null, "e": 12814, "s": 12402, "text": "Accounts − It mainly includes a front office cashier and a Night Auditor. The cashier is responsible for handling guest payments. He typically reports to the accounts manager rather than the front office manager.\nThe night auditor performs the duties of front desk reception as well as accounting partly during the night shift. He needs to report to the heads of both departments, front office, and accounting.\n" }, { "code": null, "e": 13027, "s": 12814, "text": "Accounts − It mainly includes a front office cashier and a Night Auditor. The cashier is responsible for handling guest payments. He typically reports to the accounts manager rather than the front office manager." }, { "code": null, "e": 13225, "s": 13027, "text": "The night auditor performs the duties of front desk reception as well as accounting partly during the night shift. He needs to report to the heads of both departments, front office, and accounting." }, { "code": null, "e": 13333, "s": 13225, "text": "Communication − It involves handling communication among various other departments and guests of the hotel." }, { "code": null, "e": 13441, "s": 13333, "text": "Communication − It involves handling communication among various other departments and guests of the hotel." }, { "code": null, "e": 13549, "s": 13441, "text": "Let us discuss a few prominent ranks in the front office department and their respective responsibilities −" }, { "code": null, "e": 13748, "s": 13549, "text": "In the context of hotel, the term reservation is used for booking a particular accommodation in the hotel by a guest for a period of time. Reservation section does not directly deal with the guests." }, { "code": null, "e": 13816, "s": 13748, "text": "Some important tasks a reservation manager is responsible for are −" }, { "code": null, "e": 13864, "s": 13816, "text": "Having knowledge about the reservation systems." }, { "code": null, "e": 13934, "s": 13864, "text": "Providing and updating information on tours, prices, and itineraries." }, { "code": null, "e": 13970, "s": 13934, "text": "Reviewing daily hotel reservations." }, { "code": null, "e": 14000, "s": 13970, "text": "Preparing occupancy forecast." }, { "code": null, "e": 14043, "s": 14000, "text": "Updating travel agent rates in the system." }, { "code": null, "e": 14097, "s": 14043, "text": "Handling correspondence with outside travel agencies." }, { "code": null, "e": 14146, "s": 14097, "text": "Allocating daily tasks to the reservation staff." }, { "code": null, "e": 14212, "s": 14146, "text": "Ensuring special deals with repeat guests, VIPs, or guest groups." }, { "code": null, "e": 14243, "s": 14212, "text": "Training the staff under hand." }, { "code": null, "e": 14326, "s": 14243, "text": "Following are some prominent roles and responsibilities of the reception manager −" }, { "code": null, "e": 14376, "s": 14326, "text": "Dealing with arrival and departure of the guests." }, { "code": null, "e": 14426, "s": 14376, "text": "Dealing with arrival and departure of the guests." }, { "code": null, "e": 14497, "s": 14426, "text": "Welcoming the guests, escorting them to the room, and seeing them off." }, { "code": null, "e": 14568, "s": 14497, "text": "Welcoming the guests, escorting them to the room, and seeing them off." }, { "code": null, "e": 14633, "s": 14568, "text": "Ensuring professional greeting of clients, visitors, and guests." }, { "code": null, "e": 14698, "s": 14633, "text": "Ensuring professional greeting of clients, visitors, and guests." }, { "code": null, "e": 14760, "s": 14698, "text": "Coordination with housekeeping department for cleaning rooms." }, { "code": null, "e": 14822, "s": 14760, "text": "Coordination with housekeeping department for cleaning rooms." }, { "code": null, "e": 14926, "s": 14822, "text": "Filling registration cards for the guests with reserved accommodation or help the guests to fill it up." }, { "code": null, "e": 15030, "s": 14926, "text": "Filling registration cards for the guests with reserved accommodation or help the guests to fill it up." }, { "code": null, "e": 15092, "s": 15030, "text": "Arranging surprise gift for the guests on their special days." }, { "code": null, "e": 15154, "s": 15092, "text": "Arranging surprise gift for the guests on their special days." }, { "code": null, "e": 15181, "s": 15154, "text": "Training of receptionists." }, { "code": null, "e": 15208, "s": 15181, "text": "Training of receptionists." }, { "code": null, "e": 15266, "s": 15208, "text": "Handling appraisals and performance rewards of the staff." }, { "code": null, "e": 15324, "s": 15266, "text": "Handling appraisals and performance rewards of the staff." }, { "code": null, "e": 15437, "s": 15324, "text": "Reviewing current standards of front office services and procedures, and implementing new practices if required." }, { "code": null, "e": 15550, "s": 15437, "text": "Reviewing current standards of front office services and procedures, and implementing new practices if required." }, { "code": null, "e": 15599, "s": 15550, "text": "Ensuring and Scheduling front office desk staff." }, { "code": null, "e": 15648, "s": 15599, "text": "Ensuring and Scheduling front office desk staff." }, { "code": null, "e": 15709, "s": 15648, "text": "Managing VIP functions and events taking place in the hotel." }, { "code": null, "e": 15770, "s": 15709, "text": "Managing VIP functions and events taking place in the hotel." }, { "code": null, "e": 15802, "s": 15770, "text": "Upgrading software if required." }, { "code": null, "e": 15834, "s": 15802, "text": "Upgrading software if required." }, { "code": null, "e": 15870, "s": 15834, "text": "Updating backup database regularly." }, { "code": null, "e": 15906, "s": 15870, "text": "Updating backup database regularly." }, { "code": null, "e": 15966, "s": 15906, "text": "The responsibilities of the guest service manager include −" }, { "code": null, "e": 16011, "s": 15966, "text": "Handling guest mails, letters, and couriers." }, { "code": null, "e": 16068, "s": 16011, "text": "Ensuring guest messages are delivered at the right time." }, { "code": null, "e": 16168, "s": 16068, "text": "Training the guest service staff such as concierges, bell staff, wallet parking staff, and porters." }, { "code": null, "e": 16233, "s": 16168, "text": "Maintaining guest service suggestion cards and guest complaints." }, { "code": null, "e": 16280, "s": 16233, "text": "Scheduling and appraising guest service staff." }, { "code": null, "e": 16341, "s": 16280, "text": "Ensuring the staff delivers services, accurately and timely." }, { "code": null, "e": 16449, "s": 16341, "text": "This manager works during the night hours. The typical responsibilities of a night audit manager are &mnus;" }, { "code": null, "e": 16584, "s": 16449, "text": "Posting accommodation charges, taxes, and other paid services such as restaurant, Internet charges to each guest's account accurately." }, { "code": null, "e": 16719, "s": 16584, "text": "Posting accommodation charges, taxes, and other paid services such as restaurant, Internet charges to each guest's account accurately." }, { "code": null, "e": 16780, "s": 16719, "text": "Taking the responsibility as a duty manager for night shift." }, { "code": null, "e": 16841, "s": 16780, "text": "Taking the responsibility as a duty manager for night shift." }, { "code": null, "e": 16878, "s": 16841, "text": "Settling guest accounts if required." }, { "code": null, "e": 16915, "s": 16878, "text": "Settling guest accounts if required." }, { "code": null, "e": 16967, "s": 16915, "text": "Authoring security of the hotel during night shift." }, { "code": null, "e": 17019, "s": 16967, "text": "Authoring security of the hotel during night shift." }, { "code": null, "e": 17066, "s": 17019, "text": "The communication manager is responsible for −" }, { "code": null, "e": 17159, "s": 17066, "text": "Keeping in check all communication facilities such as PBX, facsimile, internet in the hotel." }, { "code": null, "e": 17228, "s": 17159, "text": "Training and scheduling telephone operators in case of large hotels." }, { "code": null, "e": 17291, "s": 17228, "text": "Ensuring immediate delivery of fax to the guests, if required." }, { "code": null, "e": 17323, "s": 17291, "text": "Appraising telephone operators." }, { "code": null, "e": 17397, "s": 17323, "text": "Changing the communication systems to the latest technology for easy use." }, { "code": null, "e": 17563, "s": 17397, "text": "Being a part of the service industry, the front office staff needs to have the following qualities and competencies. The front office staff members are required to −" }, { "code": null, "e": 17665, "s": 17563, "text": "Understand their respective roles and responsibilities in the hotel and front office as an operation." }, { "code": null, "e": 17719, "s": 17665, "text": "Equip themselves with basic etiquettes and mannerism." }, { "code": null, "e": 17770, "s": 17719, "text": "Possess pleasant, polite, and cordial personality." }, { "code": null, "e": 17834, "s": 17770, "text": "Wear clean and neat uniform with same accessories and footwear." }, { "code": null, "e": 17918, "s": 17834, "text": "Conduct themselves with professionalism, positive attitude, and cooperative nature." }, { "code": null, "e": 17962, "s": 17918, "text": "Possess extraordinary communication skills." }, { "code": null, "e": 17980, "s": 17962, "text": "Be a team player." }, { "code": null, "e": 18029, "s": 17980, "text": "Possess the ability to tackle tricky situations." }, { "code": null, "e": 18350, "s": 18029, "text": "Reservation of the hotel accommodation is one of the important responsibilities of the front office department. A potential guest contacts a hotel for availability of the desired type of accommodation and any allied services that the hotel offers. The front office department needs to react to the enquiry of the guests." }, { "code": null, "e": 18677, "s": 18350, "text": "For a guest, reservation increases the chances of a better deal for assured accommodation on arrival. For a hotel, reservation can enable a better management of guest experience during usual as well as peak seasons. Reservation procedure varies depending on the size and brand of the hotel and the reservation system employed." }, { "code": null, "e": 18744, "s": 18677, "text": "Let us know the details how the front office handles reservations." }, { "code": null, "e": 18886, "s": 18744, "text": "An efficient and effective reservation system is what adds to the hotel’s profitability. Following are the most popular reservation systems −" }, { "code": null, "e": 19136, "s": 18886, "text": "It was developed in 1940 by Whitney Paper Corporation from New York, hence the name. This is a conventional manual reservation system the hotels used to follow during pre-computer days in the hotels. It contains the following setup for reservation −" }, { "code": null, "e": 19182, "s": 19136, "text": "Slip for request of accommodation reservation" }, { "code": null, "e": 19269, "s": 19182, "text": "Whitney slip that records guest name, accommodation type, number, and duration of stay" }, { "code": null, "e": 19302, "s": 19269, "text": "Temporary/Permanent arrival slip" }, { "code": null, "e": 19313, "s": 19302, "text": "Guest bill" }, { "code": null, "e": 19337, "s": 19313, "text": "Guest registration card" }, { "code": null, "e": 19357, "s": 19337, "text": "Correspondence file" }, { "code": null, "e": 19465, "s": 19357, "text": "Bedroom journal that records daily occupancy of the guest with date, guest name, room type, and room number" }, { "code": null, "e": 19531, "s": 19465, "text": "Let us see how a Whitney slip and the bedroom journal looks like." }, { "code": null, "e": 19697, "s": 19531, "text": "Though this system proved efficient, it generated a lot of paperwork with occasional scope for errors. The drawbacks were overcome by the central reservation system." }, { "code": null, "e": 19822, "s": 19697, "text": "It is a computerized reservation system that reduces paperwork and can handle large amount of reservation data effortlessly." }, { "code": null, "e": 20104, "s": 19822, "text": "In this system, since the guest data and reservation data are stored on the storage disks of the computers, it can be accessed at wish. It is stored in the form of a database of collection of records which can enable searching, adding, removing, or updating any guest related data." }, { "code": null, "e": 20277, "s": 20104, "text": "The computerized reservation system not only helps to make guest reservations but also helps to forecast how many accommodations can be reserved in an upcoming time period." }, { "code": null, "e": 20313, "s": 20277, "text": "This is how a CRS typically works −" }, { "code": null, "e": 20756, "s": 20313, "text": "The guests of hotel sales agents call for checking room availability. It is forwarded to the front office reservation staff. The staff finds out details about the requirement and checks the availability of desired accommodation in the database. According to the reservation policies and procedures, the reservation staff member then notifies or suggests the reception about the accommodation availability and takes further appropriate action." }, { "code": null, "e": 20942, "s": 20756, "text": "The Internet has brought a momentum in the hospitality business as well. It facilitates seamless management of a hotel’s offices located at various places and their various departments." }, { "code": null, "e": 21415, "s": 20942, "text": "The hotel businesses are actively working on the Internet 24 hours a day, seven days a week. The Internet has simplified complex system of reservations. It enables Online Hotel Management Systems (OHMS) such as Hotelogix to help guests reserve accommodation of their choice fast and conveniently. The guests of the hotel can access rate charts, accommodation availability, check-in and check-out timings, details about the restaurants, and so on, at their own convenience." }, { "code": null, "e": 21561, "s": 21415, "text": "People travel for various reasons such as personal as well as for MICE. There are various sources from whom the requests of reservation pour in −" }, { "code": null, "e": 21744, "s": 21561, "text": "Direct Request from Guests − The prospective guests can approach individually to the hotel for reservation of accommodation mostly when they are single travelers or family travelers." }, { "code": null, "e": 21927, "s": 21744, "text": "Direct Request from Guests − The prospective guests can approach individually to the hotel for reservation of accommodation mostly when they are single travelers or family travelers." }, { "code": null, "e": 22031, "s": 21927, "text": "Request from Travel Agent − They can approach the hotel for booking accommodations for group travelers." }, { "code": null, "e": 22135, "s": 22031, "text": "Request from Travel Agent − They can approach the hotel for booking accommodations for group travelers." }, { "code": null, "e": 22271, "s": 22135, "text": "Request from Corporate Agent − An organization can request a hotel to reserve accommodations for their employees, clients, or visitors." }, { "code": null, "e": 22407, "s": 22271, "text": "Request from Corporate Agent − An organization can request a hotel to reserve accommodations for their employees, clients, or visitors." }, { "code": null, "e": 22556, "s": 22407, "text": "Request from Airlines − The airlines can reserve accommodations for their working staff for routine stay as well as in case of flight cancellations." }, { "code": null, "e": 22705, "s": 22556, "text": "Request from Airlines − The airlines can reserve accommodations for their working staff for routine stay as well as in case of flight cancellations." }, { "code": null, "e": 22933, "s": 22705, "text": "Request from Institutions − Various SMERF or NGO institutions request to reserve hotels for sports people, delegations of embassies, or performing-art program groups, workshop groups, and alike who travel to different location." }, { "code": null, "e": 23161, "s": 22933, "text": "Request from Institutions − Various SMERF or NGO institutions request to reserve hotels for sports people, delegations of embassies, or performing-art program groups, workshop groups, and alike who travel to different location." }, { "code": null, "e": 23377, "s": 23161, "text": "The first step in reserving an accommodation is to check if the requested kind of accommodation is available for selling for a specific period of time. It is done by checking forecast boards or computerized systems." }, { "code": null, "e": 23688, "s": 23377, "text": "Reservation of an accommodation is accepted if the desired type of accommodation is available in the hotel for selling. If it is not available during a rush season or if the guest is in urgent need, the staff member suggests for almost similar alternative accommodation by stating its amenities and facilities." }, { "code": null, "e": 23795, "s": 23688, "text": "Reservation is accepted in the following cases in conjunction with the availability of the accommodation −" }, { "code": null, "e": 23826, "s": 23795, "text": "Is the guest new to the hotel?" }, { "code": null, "e": 23910, "s": 23826, "text": "Does the guest have good credentials with the hotel regarding payment and behavior?" }, { "code": null, "e": 23930, "s": 23910, "text": "Is the guest a VIP?" }, { "code": null, "e": 24147, "s": 23930, "text": "Denial of reservation directly means loss of revenue. But there are certain situations when the reservation staff turns down the reservation for the guests or agents. The potential causes of denying reservation are −" }, { "code": null, "e": 24362, "s": 24147, "text": "All accommodations in hotel booked − In such case, the reservation staff refuses the reservation politely and suggests an alternative hotel in the same area or different property of the same owner in a nearby area." }, { "code": null, "e": 24577, "s": 24362, "text": "All accommodations in hotel booked − In such case, the reservation staff refuses the reservation politely and suggests an alternative hotel in the same area or different property of the same owner in a nearby area." }, { "code": null, "e": 24698, "s": 24577, "text": "Requested type of accommodation not available − In such case, the reservation staff suggests an alternate accommodation." }, { "code": null, "e": 24819, "s": 24698, "text": "Requested type of accommodation not available − In such case, the reservation staff suggests an alternate accommodation." }, { "code": null, "e": 25015, "s": 24819, "text": "Guest/Agent blacklisted − Some guests or agents are blacklisted due to their history of payment dues against the hotel. In such case, the reservation clerk seeks for reservation manager’s advice." }, { "code": null, "e": 25211, "s": 25015, "text": "Guest/Agent blacklisted − Some guests or agents are blacklisted due to their history of payment dues against the hotel. In such case, the reservation clerk seeks for reservation manager’s advice." }, { "code": null, "e": 25520, "s": 25211, "text": "Finally, the reservation section of the front office prepares the list of the reservations for the day and sends it to the front desk. The list also contains vital information such as if the guest is new or repeat, guest preferences about room location or décor. The rooms are then prepared by housekeeping." }, { "code": null, "e": 25859, "s": 25520, "text": "This is yet another event when the hotel loses business with a guest. Though the fact is overt loss of revenue, the front office staff must react to it politely and gracefully. The staff member also needs to convey any cancellation charges the guest must pay while cancelling the reservation. Cancellation is done in the following steps −" }, { "code": null, "e": 25931, "s": 25859, "text": "Finding out details of the guest and respective reserved accommodation." }, { "code": null, "e": 25974, "s": 25931, "text": "Verifying charges of cancellation, if any." }, { "code": null, "e": 26022, "s": 25974, "text": "Notifying the guest about cancellation charges." }, { "code": null, "e": 26064, "s": 26022, "text": "Cancelling the reservation in the system." }, { "code": null, "e": 26116, "s": 26064, "text": "Updating the system for accommodation availability." }, { "code": null, "e": 26161, "s": 26116, "text": "Confirming the guest about the cancellation." }, { "code": null, "e": 26282, "s": 26161, "text": "Reservation reports are generated for the sake of helping the management find trends and making forecast about business." }, { "code": null, "e": 26333, "s": 26282, "text": "The reports typically are of the following types −" }, { "code": null, "e": 26350, "s": 26333, "text": "Occupancy report" }, { "code": null, "e": 26373, "s": 26350, "text": "Special arrival report" }, { "code": null, "e": 26397, "s": 26373, "text": "Revenue forecast report" }, { "code": null, "e": 26413, "s": 26397, "text": "Turnaway report" }, { "code": null, "e": 26619, "s": 26413, "text": "Guest registration is nothing but recording the guest’s information for official purposes. At the time of reservation, the front office staff asks the guests to enter their personal information on the GRC." }, { "code": null, "e": 27055, "s": 26619, "text": "Registration activity is mandatory for both; the guest with reserved accommodation as well as for the walk-in guest. During registration, the guest is required to enter important information on the GRC such as guest name, contact number, purpose of stay at the hotel, and passport and visa details in case of foreign guest. It is the responsibility of the front office staff not to reveal the guest information to unauthorized persons." }, { "code": null, "e": 27093, "s": 27055, "text": "Let us learn more about registration." }, { "code": null, "e": 27363, "s": 27093, "text": "This procedure involves the prospective guests enquiring about the availability of desired type of accommodation. Registration can also be conducted in advance before arrival. It can be done via telephonic conversation in case of frequent guests, VIPs, or group guests." }, { "code": null, "e": 27611, "s": 27363, "text": "In case of new walk-in guest, pre-registration is absent as there is no prior interaction between the guest and the hotel. Pre-registration activity accelerates the actual registration process where the desired accommodation is marked as reserved." }, { "code": null, "e": 28091, "s": 27611, "text": "Since terror attacks on 9/11, the hotels are mandatorily verifying guests’ identities. The staff verifies guest’s identity first by politely asking the guest’s name. The staff member then requests to show a photo ID such as driving license or a valid identity card from a well-known organization where the guest is working. If the guests are from a foreign country, the staff requests them to show passport. The staff member is authorized to ask any verifying questions politely." }, { "code": null, "e": 28205, "s": 28091, "text": "The true copies of the passport or ID card are made to verify the guest’s identity and to prepare guest database." }, { "code": null, "e": 28260, "s": 28205, "text": "Following is a typical format of a registration card −" }, { "code": null, "e": 28267, "s": 28260, "text": "Email:" }, { "code": null, "e": 28272, "s": 28267, "text": "Fax:" }, { "code": null, "e": 28286, "s": 28272, "text": "Card Details:" }, { "code": null, "e": 28299, "s": 28286, "text": "Card Number:" }, { "code": null, "e": 28315, "s": 28299, "text": "Date of Expiry:" }, { "code": null, "e": 28533, "s": 28317, "text": "When the guests arrive at the hotel, the front desk staff hands over the GRC to the guest to fill up the information. In case of VIPs, the staff enters the information on the card and receives the guest’s signature." }, { "code": null, "e": 28801, "s": 28533, "text": "The staff then creates a registration record of the guest, countersigns, attaches the true copies of the passport or other ID cards, and files this set in the guest history file. The guest reservation record is created as a registration record in the software system." }, { "code": null, "e": 29089, "s": 28801, "text": "Guests can pay in advance or at the time of checking-out. Those who have paid in advance are put under Paid-In-Advance (PIA) list. There are various modes of payment out of which a mode that guest prefers is recorded at the time of registration. Following payment methods are available −" }, { "code": null, "e": 29155, "s": 29089, "text": "Cash Payment (which also include money order, travelers’ cheque)." }, { "code": null, "e": 29243, "s": 29155, "text": "Credit Card/Debit Card Payment (which are accepted only if the cards have not expired)." }, { "code": null, "e": 29303, "s": 29243, "text": "Cheque Payment (where post-dated cheques are not accepted)." }, { "code": null, "e": 29319, "s": 29303, "text": "Direct Billing." }, { "code": null, "e": 29366, "s": 29319, "text": "Special Payment such as gift card and voucher." }, { "code": null, "e": 29451, "s": 29366, "text": "The guests need to select one of the options of payment at the time of registration." }, { "code": null, "e": 29668, "s": 29451, "text": "The front office staff assigns an accommodation to the guest only when the registration is complete. The staff member records the accommodation number into the PMS and describes about its positive attributes briefly." }, { "code": null, "e": 29744, "s": 29668, "text": "The reservations staff also informs the bell-boy to take the guest luggage." }, { "code": null, "e": 29894, "s": 29744, "text": "After the accommodation is assigned, the front office staff gives away the keys or the computerized secret code keys for accessing the accommodation." }, { "code": null, "e": 30275, "s": 29894, "text": "It is a general practice to not to speak anything about the room number or the computerized key loudly while giving it to the guest. The bell attendant then assists the guest with luggage handling to the accommodation and explaining the accommodation features. The attendant then gives the keys to the guest, greets for best stay, and leaves the accommodation by closing the door." }, { "code": null, "e": 30636, "s": 30275, "text": "If the guest is not satisfied with the accommodation for any unsatisfactory or unpleasant reasons, the bell attendant can bring this to the notice of the front desk staff. In addition, if the guest has special requirements such as a cradle for a baby or hot water bag or a shaving kit and alike, the front office staff is obliged to fulfil the request on time." }, { "code": null, "e": 30963, "s": 30636, "text": "Accounting section of any business or organization tracks, records, and manages the financial transactions of the business with its customers and clients. The accounting department handles the financial health and tracks the performance of any business directly. It is helpful for the management to take appropriate decisions." }, { "code": null, "e": 31207, "s": 30963, "text": "When it comes to a hotel business, accounting is managing expenses and revenue. It provides a clear information to the guests thereby avoiding any unpleasant surprises to the guests. Let us know more about the accounts section of front office." }, { "code": null, "e": 31426, "s": 31207, "text": "It is a systematic process in which the front office accounting staff identifies, records, measures, classifies, verifies, summarizes, interprets, organizes, and communicates financial information for a hotel business." }, { "code": null, "e": 31509, "s": 31426, "text": "In the simplest form, a front office account resembles English alphabet ‘Block-T’." }, { "code": null, "e": 31729, "s": 31509, "text": "In the domain of front office accounting, the charges are entered on the left side of the ‘T’. They increase the account balance. The payments are entered on the right side of the ‘T’. They decrease the account balance." }, { "code": null, "e": 31790, "s": 31729, "text": "Net Outstanding Balance = Previous Balance + Debit – Credit\n" }, { "code": null, "e": 31861, "s": 31790, "text": "Where debit increases the outstanding balance and credit decreases it." }, { "code": null, "e": 31939, "s": 31861, "text": "Most of the contemporary hotel businesses employ automated accounting system." }, { "code": null, "e": 31981, "s": 31939, "text": "The objectives of accounting system are −" }, { "code": null, "e": 32049, "s": 31981, "text": "To handle transactions between the guests and the hotel accurately." }, { "code": null, "e": 32109, "s": 32049, "text": "To track the transactions throughout the guest’s occupancy." }, { "code": null, "e": 32146, "s": 32109, "text": "To monitor the guest’s credit limit." }, { "code": null, "e": 32181, "s": 32146, "text": "To avoid possibility of any fraud." }, { "code": null, "e": 32235, "s": 32181, "text": "To organize and report the transactional information." }, { "code": null, "e": 32315, "s": 32235, "text": "There are following typical accounts in hotel business dealing with customers −" }, { "code": null, "e": 32329, "s": 32315, "text": "Guest Account" }, { "code": null, "e": 32355, "s": 32329, "text": "Non-guest or City Account" }, { "code": null, "e": 32374, "s": 32355, "text": "Management Account" }, { "code": null, "e": 32447, "s": 32374, "text": "Here are some prominent differences between a guest and a city account −" }, { "code": null, "e": 32864, "s": 32447, "text": "Some hotels allow the managers to entertain the guests’ queries or grievances, or any possibility of acquiring a business deal over a brief interaction with the guests. For example, if a guest has some problem about the hotel policy, the manager calls the guest for interaction over a coffee or a drink and tries to resolve the same. The expenses towards this interaction are then recorded on the management account." }, { "code": null, "e": 32948, "s": 32864, "text": "A folio is a statement of all transaction that has taken place in a single account." }, { "code": null, "e": 33269, "s": 32948, "text": "The front office staff records all the transactions between the guest and the hotel on the folio. The folio is opened with zero initial balance. The balance in the folio then increases or decreases depending upon the transactions. At the time of check-out, the folio balance must return to zero on settlement of payment." }, { "code": null, "e": 33313, "s": 33269, "text": "There are following major types of folios −" }, { "code": null, "e": 33363, "s": 33313, "text": "Guest − Assigned to charge for individual guests." }, { "code": null, "e": 33413, "s": 33363, "text": "Guest − Assigned to charge for individual guests." }, { "code": null, "e": 33462, "s": 33413, "text": "Master − Assigned charge for group/organization." }, { "code": null, "e": 33511, "s": 33462, "text": "Master − Assigned charge for group/organization." }, { "code": null, "e": 33556, "s": 33511, "text": "Non-guest − Assigned for non-resident guest." }, { "code": null, "e": 33601, "s": 33556, "text": "Non-guest − Assigned for non-resident guest." }, { "code": null, "e": 33682, "s": 33601, "text": "Employee − Assigned for hotel employee to charge against coffee shop privileges." }, { "code": null, "e": 33763, "s": 33682, "text": "Employee − Assigned for hotel employee to charge against coffee shop privileges." }, { "code": null, "e": 33890, "s": 33763, "text": "The process of recording the entries on the folio is called ‘Posting’ of transactions. There are two basic types of postings −" }, { "code": null, "e": 34026, "s": 33890, "text": "Credit − They reduce the guest’s outstanding balance. These entries include complete or partial payment, or adjustments against tokens." }, { "code": null, "e": 34162, "s": 34026, "text": "Credit − They reduce the guest’s outstanding balance. These entries include complete or partial payment, or adjustments against tokens." }, { "code": null, "e": 34351, "s": 34162, "text": "Debit − They increase the outstanding balance in the guest account. Debit entries include charges under restaurant, room-service, health center/spa, laundry, telephone, and transportation." }, { "code": null, "e": 34540, "s": 34351, "text": "Debit − They increase the outstanding balance in the guest account. Debit entries include charges under restaurant, room-service, health center/spa, laundry, telephone, and transportation." }, { "code": null, "e": 34779, "s": 34540, "text": "Vouchers are detailed documentary evidences for a transaction. It transfers the transaction from its source to the front office. Vouchers are used to notify the front office about guest’s purchases or availing of any service at the hotel." }, { "code": null, "e": 34834, "s": 34779, "text": "The following typical vouchers are used in the hotel −" }, { "code": null, "e": 34855, "s": 34834, "text": "Cash Receipt Voucher" }, { "code": null, "e": 34874, "s": 34855, "text": "Commission Voucher" }, { "code": null, "e": 34889, "s": 34874, "text": "Charge Voucher" }, { "code": null, "e": 34908, "s": 34889, "text": "Petty Cash Voucher" }, { "code": null, "e": 34926, "s": 34908, "text": "Allowance Voucher" }, { "code": null, "e": 34959, "s": 34926, "text": "Miscellaneous Charge Order (MCO)" }, { "code": null, "e": 34982, "s": 34959, "text": "Paid-out Voucher (VPO)" }, { "code": null, "e": 34999, "s": 34982, "text": "Transfer voucher" }, { "code": null, "e": 35031, "s": 34999, "text": "Here are some typical vouchers." }, { "code": null, "e": 35117, "s": 35031, "text": "The ledgers are a group of accounts. There are two ledgers the front office handles −" }, { "code": null, "e": 35193, "s": 35117, "text": "Guest ledger − A set of all guest accounts currently residing in the hotel." }, { "code": null, "e": 35269, "s": 35193, "text": "Guest ledger − A set of all guest accounts currently residing in the hotel." }, { "code": null, "e": 35337, "s": 35269, "text": "Non-guest ledger − A set of all unsettled, departed guest accounts." }, { "code": null, "e": 35405, "s": 35337, "text": "Non-guest ledger − A set of all unsettled, departed guest accounts." }, { "code": null, "e": 35537, "s": 35405, "text": "There are two other types of ledgers used in the hotel. Both types of ledgers are used by back office accounting section as given −" }, { "code": null, "e": 35732, "s": 35537, "text": "Receivable ledger − The back office accounting staff mails the bills and statements to the guests after their departure without settling the bills and ensures the payments for services provided." }, { "code": null, "e": 35927, "s": 35732, "text": "Receivable ledger − The back office accounting staff mails the bills and statements to the guests after their departure without settling the bills and ensures the payments for services provided." }, { "code": null, "e": 36077, "s": 35927, "text": "Payable ledger − The staff handles amounts of money paid in advance on behalf of the guest to the hotel for future consumption of goods and services." }, { "code": null, "e": 36227, "s": 36077, "text": "Payable ledger − The staff handles amounts of money paid in advance on behalf of the guest to the hotel for future consumption of goods and services." }, { "code": null, "e": 36283, "s": 36227, "text": "There are various issues regarding account settlement −" }, { "code": null, "e": 36352, "s": 36283, "text": "By Guest − The guest settles own account by cash/credit card/cheque." }, { "code": null, "e": 36453, "s": 36352, "text": "By Organization − The organization settles guest account by transferring money to the hotel account." }, { "code": null, "e": 36513, "s": 36453, "text": "There are following popular methods of account settlement −" }, { "code": null, "e": 36655, "s": 36513, "text": "Account Settlement in Local Currency − A guest can pay in terms of a local currency where the payment is not chargeable with conversion fees." }, { "code": null, "e": 36843, "s": 36655, "text": "Account Settlement in Foreign Currency − If the guest prefers to pay in foreign currency, the service of payment by the bank is chargeable for around 3% to 6% of the total payable amount." }, { "code": null, "e": 37013, "s": 36843, "text": "Account Settlement Using Traveler Check − Travelers’ cheques, the pre-printed cheques in the denominations of major world currencies are a good option to paying by cash." }, { "code": null, "e": 37258, "s": 37013, "text": "Debit Card − Use of magnetic cards for payment against account is most common today. Paying by debit cards is as good as paying by cash as the amount of money is instantly transferred from the guest’s bank account into the hotel’s bank account." }, { "code": null, "e": 37510, "s": 37258, "text": "In case of credit card settlement, the accounting staff mails the charge vouchers signed by guests to the credit card company; preferably within a specified time. The credit card company then settles the guest account by transferring money against it." }, { "code": null, "e": 38010, "s": 37510, "text": "Credit Settlement by Organization − Many national, international, private, or public organizations send their employees or students for attending workshops, seminar, or meetings. Such organizations tie-up with the hotel for paying the bills of their employees on credit. The organizations reserve accommodations depending on the number of room nights (number of rooms × number of nights the representatives are expected to occupy). This is popularly known as account Settlement using Direct Billing." }, { "code": null, "e": 38348, "s": 38010, "text": "In direct billing account settlement, the front office staff verifies guest folios and transfers the guest account to non-guest or city account. The hotel’s back-office accounting verifies the guest folios and is responsible to collect the direct billing amount from a direct billing agency such as embassy, university, or organizations." }, { "code": null, "e": 38543, "s": 38348, "text": "The accounting section also notifies the guests that if the direct billing agency fails or refuses to pay the charges then the guests need to settle the account by paying them from their pocket." }, { "code": null, "e": 38801, "s": 38543, "text": "Combined Account Settlement − A guest can settle account by paying partial amount in cash and remaining amount on credit. The front office staff needs to prepare the supporting document for such kind of payment and hands it over to the back-office accounts." }, { "code": null, "e": 39089, "s": 38801, "text": "Healthy communication in the organization fosters mutual trust and sense of cooperation among the staff members and the guests as well as between the staff members and the management body. Front office communication with other departments can make or break the guests’ stay at the hotel." }, { "code": null, "e": 39307, "s": 39089, "text": "As the front office is responsible to sell the hotel accommodations, it is a major driving force for generating revenue. Hence, communication within and out of front office department needs to be vibrant and positive." }, { "code": null, "e": 39633, "s": 39307, "text": "Front office department is responsible for communicating with all other departments in the hotel as well as different sections within the department. To get the front office and back office jobs done successfully, the front office staff members need to communicate with their peers as well as the colleagues and subordinates." }, { "code": null, "e": 39888, "s": 39633, "text": "Within the department, the staff of front office communicate with each other to provide the best possible guest services such as reserving accommodations, registering guests, managing guest accounts, handling guest mails, and personalized guest services." }, { "code": null, "e": 40038, "s": 39888, "text": "Front office interacts with various departments since the guest inquire about reservation through the entire guest cycle up to the guest’s departure." }, { "code": null, "e": 40113, "s": 40038, "text": "Here is how front office needs to communicate with the other departments −" }, { "code": null, "e": 40403, "s": 40113, "text": "Communication with Human Resource − Front Office department is engaged with the HR department to interview, help shortlist them, and select the most eligible employees. It also contacts the HR department for employee training and induction programs, salaries, leaves, dues, and appraisals." }, { "code": null, "e": 40693, "s": 40403, "text": "Communication with Human Resource − Front Office department is engaged with the HR department to interview, help shortlist them, and select the most eligible employees. It also contacts the HR department for employee training and induction programs, salaries, leaves, dues, and appraisals." }, { "code": null, "e": 41067, "s": 40693, "text": "Communication with Accounts − As front office department handles guest accounts with a complete responsibility, the staff needs to often interact with the back-office accounting colleagues regarding payment settlements or dues of guests or non-guests, discount offers, and coupons settlement. It also needs to sort out and get actual status of night auditing with accounts." }, { "code": null, "e": 41441, "s": 41067, "text": "Communication with Accounts − As front office department handles guest accounts with a complete responsibility, the staff needs to often interact with the back-office accounting colleagues regarding payment settlements or dues of guests or non-guests, discount offers, and coupons settlement. It also needs to sort out and get actual status of night auditing with accounts." }, { "code": null, "e": 42008, "s": 41441, "text": "Communication with Food and Beverage Department − Since front office department is the one where the guests speak about their food and beverage requirements during reservation, the front office needs to communicate with the food and beverage sections frequently.\n\nIt also keeps the track of guest’s purchases from the restaurant, the bar, or coffee shops in the hotel.\nIt conveys special requests of the guest regarding food and beverage to the F&B department.\nIt deals, accepts, and reserves banquet inquiries and coordinates them with the respective departments.\n\n" }, { "code": null, "e": 42271, "s": 42008, "text": "Communication with Food and Beverage Department − Since front office department is the one where the guests speak about their food and beverage requirements during reservation, the front office needs to communicate with the food and beverage sections frequently." }, { "code": null, "e": 42376, "s": 42271, "text": "It also keeps the track of guest’s purchases from the restaurant, the bar, or coffee shops in the hotel." }, { "code": null, "e": 42481, "s": 42376, "text": "It also keeps the track of guest’s purchases from the restaurant, the bar, or coffee shops in the hotel." }, { "code": null, "e": 42573, "s": 42481, "text": "It conveys special requests of the guest regarding food and beverage to the F&B department." }, { "code": null, "e": 42665, "s": 42573, "text": "It conveys special requests of the guest regarding food and beverage to the F&B department." }, { "code": null, "e": 42769, "s": 42665, "text": "It deals, accepts, and reserves banquet inquiries and coordinates them with the respective departments." }, { "code": null, "e": 42873, "s": 42769, "text": "It deals, accepts, and reserves banquet inquiries and coordinates them with the respective departments." }, { "code": null, "e": 43349, "s": 42873, "text": "Communication with Marketing and Sales Department − Sales and Marketing department highly relies upon front office inputs about the guests. The guest history compiled by the front office department is an excellent source for segmenting the customers, prepare customer-oriented packages, and plan and execute the campaigns.\nThe front office staff contacts marketing and sales department in case there is a need to prepare electronic marquees or message boards for promotions.\n" }, { "code": null, "e": 43672, "s": 43349, "text": "Communication with Marketing and Sales Department − Sales and Marketing department highly relies upon front office inputs about the guests. The guest history compiled by the front office department is an excellent source for segmenting the customers, prepare customer-oriented packages, and plan and execute the campaigns." }, { "code": null, "e": 43824, "s": 43672, "text": "The front office staff contacts marketing and sales department in case there is a need to prepare electronic marquees or message boards for promotions." }, { "code": null, "e": 44498, "s": 43824, "text": "Communication with Housekeeping − The front office staff needs to interact with the housekeeping department on the concerns such as −\n\nReadiness of vacated accommodation for selling.\nSecurity of the accommodation.\nGuest’s complaints and requirements about any amenities is initiated at the front desk.\nGuest’s requirement of removing soiled dishes or linen from the accommodation.\nIn addition, the housekeeping department relies upon front office staff for the number of accommodations sold, departures, walk-ins, stay-over guests, and no-shows. Timely distribution of the accommodation sales helps the housekeeping manager to plan employee personal leaves and vacations.\n\n" }, { "code": null, "e": 44632, "s": 44498, "text": "Communication with Housekeeping − The front office staff needs to interact with the housekeeping department on the concerns such as −" }, { "code": null, "e": 44680, "s": 44632, "text": "Readiness of vacated accommodation for selling." }, { "code": null, "e": 44728, "s": 44680, "text": "Readiness of vacated accommodation for selling." }, { "code": null, "e": 44759, "s": 44728, "text": "Security of the accommodation." }, { "code": null, "e": 44790, "s": 44759, "text": "Security of the accommodation." }, { "code": null, "e": 44878, "s": 44790, "text": "Guest’s complaints and requirements about any amenities is initiated at the front desk." }, { "code": null, "e": 44966, "s": 44878, "text": "Guest’s complaints and requirements about any amenities is initiated at the front desk." }, { "code": null, "e": 45045, "s": 44966, "text": "Guest’s requirement of removing soiled dishes or linen from the accommodation." }, { "code": null, "e": 45124, "s": 45045, "text": "Guest’s requirement of removing soiled dishes or linen from the accommodation." }, { "code": null, "e": 45415, "s": 45124, "text": "In addition, the housekeeping department relies upon front office staff for the number of accommodations sold, departures, walk-ins, stay-over guests, and no-shows. Timely distribution of the accommodation sales helps the housekeeping manager to plan employee personal leaves and vacations." }, { "code": null, "e": 45706, "s": 45415, "text": "In addition, the housekeeping department relies upon front office staff for the number of accommodations sold, departures, walk-ins, stay-over guests, and no-shows. Timely distribution of the accommodation sales helps the housekeeping manager to plan employee personal leaves and vacations." }, { "code": null, "e": 46116, "s": 45706, "text": "Communication with Banqueting − The front office and banqueting department needs to interact with each other on the concerns such as −\n\nExpected number of guests to attend the banquet.\nShowing directions of the venue to the unfamiliar banquet guests.\nPosting of daily messages on felt board regarding venue, occasion, hosts and guests.\nSettling of the city account against the banquet service for the guest.\n\n" }, { "code": null, "e": 46251, "s": 46116, "text": "Communication with Banqueting − The front office and banqueting department needs to interact with each other on the concerns such as −" }, { "code": null, "e": 46300, "s": 46251, "text": "Expected number of guests to attend the banquet." }, { "code": null, "e": 46349, "s": 46300, "text": "Expected number of guests to attend the banquet." }, { "code": null, "e": 46415, "s": 46349, "text": "Showing directions of the venue to the unfamiliar banquet guests." }, { "code": null, "e": 46481, "s": 46415, "text": "Showing directions of the venue to the unfamiliar banquet guests." }, { "code": null, "e": 46566, "s": 46481, "text": "Posting of daily messages on felt board regarding venue, occasion, hosts and guests." }, { "code": null, "e": 46651, "s": 46566, "text": "Posting of daily messages on felt board regarding venue, occasion, hosts and guests." }, { "code": null, "e": 46723, "s": 46651, "text": "Settling of the city account against the banquet service for the guest." }, { "code": null, "e": 46795, "s": 46723, "text": "Settling of the city account against the banquet service for the guest." }, { "code": null, "e": 46997, "s": 46795, "text": "A vital link between the prospective guests and the hotel itself is switchboard operator who represents the hotel. When the customers call the hotel, the call first arrives at the switchboard operator." }, { "code": null, "e": 47347, "s": 46997, "text": "Using knowledge of the portfolio, tone of speaking, and the command over language the switchboard operator can handle the influx of the calls. The operator represents the competency of the hotel in the market while speaking with the customers. Generally, the switchboard operator greets the guests and transfers their call to appropriate department." }, { "code": null, "e": 47720, "s": 47347, "text": "There are two schools of thoughts regarding the area where a switchboard operator should work. Some experts say that they should be visible and some expert advice to assign a separate aloof place for them in the hotel. Today, the task of a switchboard operator for transferring the incoming calls to various departments is computerized and requires less human involvement." }, { "code": null, "e": 47965, "s": 47720, "text": "The switchboard operators are informed not to transfer any call to the executive chef or to the banquet manager during busy work hours. Hence, the operator needs to take the message accurately and pass them on to the respective persons on time." }, { "code": null, "e": 48132, "s": 47965, "text": "Communication necessarily is about verbal language as well as body language. Here are some common Do’s and Don’ts the front office staff follows while communicating −" }, { "code": null, "e": 48175, "s": 48132, "text": "Always present yourself with a warm smile." }, { "code": null, "e": 48218, "s": 48175, "text": "Always present yourself with a warm smile." }, { "code": null, "e": 48278, "s": 48218, "text": "Always stand and walk erect which reflects your confidence." }, { "code": null, "e": 48338, "s": 48278, "text": "Always stand and walk erect which reflects your confidence." }, { "code": null, "e": 48505, "s": 48338, "text": "Get hold on to your domain subject. Try to know more about your portfolio. This saves you from the embarrassing situations when you are expected to answer the guests." }, { "code": null, "e": 48672, "s": 48505, "text": "Get hold on to your domain subject. Try to know more about your portfolio. This saves you from the embarrassing situations when you are expected to answer the guests." }, { "code": null, "e": 48742, "s": 48672, "text": "Before you start speaking, find out important points about the issue." }, { "code": null, "e": 48812, "s": 48742, "text": "Before you start speaking, find out important points about the issue." }, { "code": null, "e": 48836, "s": 48812, "text": "Speak in audible voice." }, { "code": null, "e": 48860, "s": 48836, "text": "Speak in audible voice." }, { "code": null, "e": 48893, "s": 48860, "text": "Use simple and correct language." }, { "code": null, "e": 48926, "s": 48893, "text": "Use simple and correct language." }, { "code": null, "e": 48977, "s": 48926, "text": "Use a language that can be understood by everyone." }, { "code": null, "e": 49028, "s": 48977, "text": "Use a language that can be understood by everyone." }, { "code": null, "e": 49138, "s": 49028, "text": "If you need to talk to your colleague in the presence of guest, talk in a standard language of communication." }, { "code": null, "e": 49248, "s": 49138, "text": "If you need to talk to your colleague in the presence of guest, talk in a standard language of communication." }, { "code": null, "e": 49376, "s": 49248, "text": "Speak only if it is going to be useful to the guests and colleagues. Always speak by maintaining eye contact with the listener." }, { "code": null, "e": 49504, "s": 49376, "text": "Speak only if it is going to be useful to the guests and colleagues. Always speak by maintaining eye contact with the listener." }, { "code": null, "e": 49613, "s": 49504, "text": "In case your conversation is interrupted, continue it with a short recap of what has been already discussed." }, { "code": null, "e": 49722, "s": 49613, "text": "In case your conversation is interrupted, continue it with a short recap of what has been already discussed." }, { "code": null, "e": 49828, "s": 49722, "text": "While you listen, always pay undivided attention to the speaker. Communicate to understand; not to react." }, { "code": null, "e": 49934, "s": 49828, "text": "While you listen, always pay undivided attention to the speaker. Communicate to understand; not to react." }, { "code": null, "e": 50021, "s": 49934, "text": "If the guest asks you to arrange for too many things, then repeat them for confirming." }, { "code": null, "e": 50108, "s": 50021, "text": "If the guest asks you to arrange for too many things, then repeat them for confirming." }, { "code": null, "e": 50205, "s": 50108, "text": "Ask politely if you have missed to hear any point the guest or the colleague is putting forward." }, { "code": null, "e": 50302, "s": 50205, "text": "Ask politely if you have missed to hear any point the guest or the colleague is putting forward." }, { "code": null, "e": 50423, "s": 50302, "text": "Do not use jargon or words such as “hmm-hmm”, “yep”, and alike. Instead, use “perfect”, “absolutely”, and similar words." }, { "code": null, "e": 50544, "s": 50423, "text": "Do not use jargon or words such as “hmm-hmm”, “yep”, and alike. Instead, use “perfect”, “absolutely”, and similar words." }, { "code": null, "e": 50606, "s": 50544, "text": "Do not speak too fast, too slow, or in too low or high voice." }, { "code": null, "e": 50668, "s": 50606, "text": "Do not speak too fast, too slow, or in too low or high voice." }, { "code": null, "e": 50698, "s": 50668, "text": "Do not interrupt the speaker." }, { "code": null, "e": 50728, "s": 50698, "text": "Do not interrupt the speaker." }, { "code": null, "e": 50821, "s": 50728, "text": "Do not speak with the colleagues, if it is not related to the business during working hours." }, { "code": null, "e": 50914, "s": 50821, "text": "Do not speak with the colleagues, if it is not related to the business during working hours." }, { "code": null, "e": 50946, "s": 50914, "text": "Do not speak under assumptions." }, { "code": null, "e": 50978, "s": 50946, "text": "Do not speak under assumptions." }, { "code": null, "e": 51035, "s": 50978, "text": "Do not hastily arrive at the conclusion unless you know." }, { "code": null, "e": 51092, "s": 51035, "text": "Do not hastily arrive at the conclusion unless you know." }, { "code": null, "e": 51128, "s": 51092, "text": "Do not run around the area of work." }, { "code": null, "e": 51164, "s": 51128, "text": "Do not run around the area of work." }, { "code": null, "e": 51208, "s": 51164, "text": "Do not appear harsh with your subordinates." }, { "code": null, "e": 51252, "s": 51208, "text": "Do not appear harsh with your subordinates." }, { "code": null, "e": 51282, "s": 51252, "text": "Do not appear untidy on work." }, { "code": null, "e": 51312, "s": 51282, "text": "Do not appear untidy on work." }, { "code": null, "e": 51426, "s": 51312, "text": "Front office communication not only includes verbal or textual communication but also body language of the staff." }, { "code": null, "e": 51501, "s": 51426, "text": "Following are some essential attributes the front office staff must have −" }, { "code": null, "e": 51541, "s": 51501, "text": "Pleasant, sturdy, and agile personality" }, { "code": null, "e": 51580, "s": 51541, "text": "High sense of good conduct and hygiene" }, { "code": null, "e": 51625, "s": 51580, "text": "Ability to solve problems and decide quickly" }, { "code": null, "e": 51638, "s": 51625, "text": "Salesmanship" }, { "code": null, "e": 51648, "s": 51638, "text": "Integrity" }, { "code": null, "e": 51660, "s": 51648, "text": "Punctuality" }, { "code": null, "e": 51697, "s": 51660, "text": "Knowledge of etiquettes, and manners" }, { "code": null, "e": 51719, "s": 51697, "text": "Command over language" }, { "code": null, "e": 51747, "s": 51719, "text": "Confident yet polite nature" }, { "code": null, "e": 51790, "s": 51747, "text": "Capacity to tackle situations of emergency" }, { "code": null, "e": 51812, "s": 51790, "text": "Integrity and honesty" }, { "code": null, "e": 52181, "s": 51812, "text": "Auditing is nothing but conducting financial inspection of the organization. For a hotel business, the finance management starts at the front office. Accurate posting of transactions on the guest folios start at the front office, which is further carried to the back-office accounting department. The guest accounts are counterchecked on a daily basis during auditing." }, { "code": null, "e": 52324, "s": 52181, "text": "Experts recommend the hotel management team to go through the night audit reports daily to get an insight of the hotel occupancy and finances." }, { "code": null, "e": 52386, "s": 52324, "text": "Let us see what night auditing is and details about the same." }, { "code": null, "e": 52519, "s": 52386, "text": "It is the process of auditing where the night auditor reviews all financial activities of the hotel that has taken place in one day." }, { "code": null, "e": 52835, "s": 52519, "text": "The auditing process for the day is generally conducted at the end of the day during the following night, hence the name ‘Night Audit’. It can be performed by the conventional method of using papers, receipts, vouchers, coupons, and files. But performing audit using modern PMS systems is easy, fast, and efficient." }, { "code": null, "e": 52912, "s": 52835, "text": "The night auditor performs the following steps during night audit activity −" }, { "code": null, "e": 52948, "s": 52912, "text": "Posting accommodation and tax charg" }, { "code": null, "e": 52996, "s": 52948, "text": "Accumulating guest service charges and payments" }, { "code": null, "e": 53049, "s": 52996, "text": "Settling financial activities of various departments" }, { "code": null, "e": 53082, "s": 53049, "text": "Settling the account receivables" }, { "code": null, "e": 53120, "s": 53082, "text": "Running the trial balance for the day" }, { "code": null, "e": 53153, "s": 53120, "text": "Preparing the night audit report" }, { "code": null, "e": 53492, "s": 53153, "text": "The objective of night audit is to evaluate the hotel’s financial activities. Night audit not only reviews guest accounts by checking credits and debits but also tracks the credit limits of the guests and tallies projected and actual sales from various departments. Night audit reviews daily cash flow into and out of the hotel’s account." }, { "code": null, "e": 53716, "s": 53492, "text": "Night audit has a large significance in hotel business operations. The management body refers night audit report to plan future goals and control the expenses. The managers can react immediately on the acquired information." }, { "code": null, "e": 53831, "s": 53716, "text": "Apart from the basic audit activities listed above, the night auditor carries out the following responsibilities −" }, { "code": null, "e": 53864, "s": 53831, "text": "Taking over from the last shift." }, { "code": null, "e": 53928, "s": 53864, "text": "Checking-in or checking-out the guests after 11:00 pm at night." }, { "code": null, "e": 53952, "s": 53928, "text": "Registering the guests." }, { "code": null, "e": 54010, "s": 53952, "text": "Allocating accommodations to the newly checked-in guests." }, { "code": null, "e": 54069, "s": 54010, "text": "Settling transactions in the newly created guest accounts." }, { "code": null, "e": 54093, "s": 54069, "text": "Verifying guest folios." }, { "code": null, "e": 54123, "s": 54093, "text": "Verifying room status report." }, { "code": null, "e": 54177, "s": 54123, "text": "Balancing all paperwork with the accounts in the PMS." }, { "code": null, "e": 54224, "s": 54177, "text": "Remaining liable for security of the premises." }, { "code": null, "e": 54259, "s": 54224, "text": "Handling guest accommodation keys." }, { "code": null, "e": 54303, "s": 54259, "text": "Taking backup of the PMS generated reports." }, { "code": null, "e": 54364, "s": 54303, "text": "Preparing lists of expected guest arrivals for the next day." }, { "code": null, "e": 54404, "s": 54364, "text": "Closing financial activities for a day." }, { "code": null, "e": 54452, "s": 54404, "text": "Starting financial activities for the next day." }, { "code": null, "e": 54491, "s": 54452, "text": "Receiving and recording bank deposits." }, { "code": null, "e": 54651, "s": 54491, "text": "Today, the PMS helps night auditors to a great extent in auditing and generating accurate reports. Here are some typical reports generated during night audit −" }, { "code": null, "e": 54924, "s": 54651, "text": "Night Audit Accommodation Report − It gives a snapshot of the days when accommodations are occupied, the days when the accommodations are available, check-ins, check-outs, no-shows, and cancellations. This report can show further details for any of the items listed above." }, { "code": null, "e": 55197, "s": 54924, "text": "Night Audit Accommodation Report − It gives a snapshot of the days when accommodations are occupied, the days when the accommodations are available, check-ins, check-outs, no-shows, and cancellations. This report can show further details for any of the items listed above." }, { "code": null, "e": 55293, "s": 55197, "text": "Night Audit Counter Report − It gives details on cash and credit card receipts and withdrawals." }, { "code": null, "e": 55389, "s": 55293, "text": "Night Audit Counter Report − It gives details on cash and credit card receipts and withdrawals." }, { "code": null, "e": 55682, "s": 55389, "text": "Night Audit Revenue Report − It delivers information on accommodation revenue, cancellation and no show revenue, and other POS revenue. Revenue generated through various agencies and bodies such as travel agents, corporate organizations, internet booking. etc., is also listed in this report." }, { "code": null, "e": 55975, "s": 55682, "text": "Night Audit Revenue Report − It delivers information on accommodation revenue, cancellation and no show revenue, and other POS revenue. Revenue generated through various agencies and bodies such as travel agents, corporate organizations, internet booking. etc., is also listed in this report." }, { "code": null, "e": 56121, "s": 55975, "text": "Night Audit Tax Report − Contains all the tax information on reservation revenue and other POS revenues such as VAT, luxury tax, and service tax." }, { "code": null, "e": 56267, "s": 56121, "text": "Night Audit Tax Report − Contains all the tax information on reservation revenue and other POS revenues such as VAT, luxury tax, and service tax." }, { "code": null, "e": 56606, "s": 56267, "text": "Cashier’s report − It is the detailed list of cashier activity of cash influx and out flux, credit cards, and PMS totals. Cashier’s report is very important part of the financial control system of a hotel. The front office manager reviews the night audit and looks for any divergences between the actual amount received and the PMS total." }, { "code": null, "e": 56945, "s": 56606, "text": "Cashier’s report − It is the detailed list of cashier activity of cash influx and out flux, credit cards, and PMS totals. Cashier’s report is very important part of the financial control system of a hotel. The front office manager reviews the night audit and looks for any divergences between the actual amount received and the PMS total." }, { "code": null, "e": 57201, "s": 56945, "text": "Manager’s Report − It is a statistical list of previous day’s occupancy. It includes details about available accommodations, occupied accommodations, sold and vacated accommodations, rack-rate, number of guests in the hotel, number of no-shows, and so on." }, { "code": null, "e": 57457, "s": 57201, "text": "Manager’s Report − It is a statistical list of previous day’s occupancy. It includes details about available accommodations, occupied accommodations, sold and vacated accommodations, rack-rate, number of guests in the hotel, number of no-shows, and so on." }, { "code": null, "e": 57792, "s": 57457, "text": "General Manager’s Report − Each department in the hotel is required to send daily sales report to the front office. Using their information, a departmental total report is generated for the general manager’s assessment. The General Manager determines the profit-generating departments and evaluates the success of sales and marketing." }, { "code": null, "e": 58127, "s": 57792, "text": "General Manager’s Report − Each department in the hotel is required to send daily sales report to the front office. Using their information, a departmental total report is generated for the general manager’s assessment. The General Manager determines the profit-generating departments and evaluates the success of sales and marketing." }, { "code": null, "e": 58256, "s": 58127, "text": "High Balance Report − This is a detailed report about the guests who have exceeded the credit limit set by the hotel management." }, { "code": null, "e": 58385, "s": 58256, "text": "High Balance Report − This is a detailed report about the guests who have exceeded the credit limit set by the hotel management." }, { "code": null, "e": 58525, "s": 58385, "text": "Ledger Balance Summary Report − It displays the opening and closing balances for the Advance Deposit Ledger, Guest Ledger, and City Ledger." }, { "code": null, "e": 58665, "s": 58525, "text": "Ledger Balance Summary Report − It displays the opening and closing balances for the Advance Deposit Ledger, Guest Ledger, and City Ledger." }, { "code": null, "e": 58812, "s": 58665, "text": "Room Rate Audit Report − It lists all rates that are applied to each guest and the difference from the rack rate with the predetermined rack code." }, { "code": null, "e": 58959, "s": 58812, "text": "Room Rate Audit Report − It lists all rates that are applied to each guest and the difference from the rack rate with the predetermined rack code." }, { "code": null, "e": 59012, "s": 58959, "text": "Here are some formulae used to balance night audit −" }, { "code": null, "e": 59056, "s": 59012, "text": "The formula for balancing bank deposit is −" }, { "code": null, "e": 59156, "s": 59056, "text": "Total Bank Deposits\n - Total Cash Sales\n - Credit card received A/R\n – Cash received A/R\n= 0\n" }, { "code": null, "e": 59200, "s": 59156, "text": "The formula for balancing guest ledger is −" }, { "code": null, "e": 59331, "s": 59200, "text": "Total Revenue\n - Paid-outs and non-collect sales\n= Daily revenue\n - Total cash income\n - Today’s outstanding A/R income\n= 0\n" }, { "code": null, "e": 59374, "s": 59331, "text": "The formula for balancing city ledger is −" }, { "code": null, "e": 59563, "s": 59374, "text": "Yesterday's outstanding A/R\n + Today's outstanding A/R income\n= Total outstanding A/R\n - Credit card received and applied to A/R\n – Cash received and applied to A/R\n= balance of A/R\n" }, { "code": null, "e": 59840, "s": 59563, "text": "In any business organization, common procedures occur in sequence. They are linear. In addition, some procedures also repeat over a time. The organization needs to find out such linear and repeating procedures to compile them into sets of Standard Operating Procedures (SOPs)." }, { "code": null, "e": 59995, "s": 59840, "text": "These procedures when compiled step by step, can prove to be an excellent learning material for training the newly joined staff in a short period of time." }, { "code": null, "e": 60066, "s": 59995, "text": "Let us learn about a few SOPs followed in the front office department." }, { "code": null, "e": 60189, "s": 60066, "text": "This is a procedure followed by the bell desk staff at the time of the guest’s arrival and departure. It goes as follows −" }, { "code": null, "e": 60237, "s": 60189, "text": "As a bellboy look for the new arrival of guest." }, { "code": null, "e": 60284, "s": 60237, "text": "The guest vehicle stops at the hotel entrance." }, { "code": null, "e": 60320, "s": 60284, "text": "Go ahead and open the vehicle door." }, { "code": null, "e": 60424, "s": 60320, "text": "Greet the guest as, \"Welcome to (hotel_name), I am (own_name). Do you need any help with your luggage?\"" }, { "code": null, "e": 60496, "s": 60424, "text": "Help the elderly/disables guests to get out of the vehicle if required." }, { "code": null, "e": 60571, "s": 60496, "text": "Take the luggage in charge and ensure that nothing is left in the vehicle." }, { "code": null, "e": 60639, "s": 60571, "text": "Ask the guest’s name politely as, \"May I know your name Sir/Madam?\"" }, { "code": null, "e": 60676, "s": 60639, "text": "Tag the luggage with the guest name." }, { "code": null, "e": 60733, "s": 60676, "text": "Ask if anything fragile or perishable is in the luggage." }, { "code": null, "e": 60774, "s": 60733, "text": "Add this information on the luggage tag." }, { "code": null, "e": 60823, "s": 60774, "text": "Inform the guest that their luggage is with you." }, { "code": null, "e": 60864, "s": 60823, "text": "Escort the guest to the hotel reception." }, { "code": null, "e": 60928, "s": 60864, "text": "Inform the guest that you will be taking care of their luggage." }, { "code": null, "e": 61020, "s": 60928, "text": "With the other front office staff, find out the accommodation number allotted to the guest." }, { "code": null, "e": 61071, "s": 61020, "text": "Write the accommodation number on the luggage tag." }, { "code": null, "e": 61128, "s": 61071, "text": "Confirm if the guest registration formality is complete." }, { "code": null, "e": 61202, "s": 61128, "text": "If the room is ready, take the luggage to the room by the staff elevator." }, { "code": null, "e": 61241, "s": 61202, "text": "Place the luggage on the luggage rack." }, { "code": null, "e": 61308, "s": 61241, "text": "If the room is not ready, then take the luggage to the store room." }, { "code": null, "e": 61368, "s": 61308, "text": "Record the luggage details into the Daily Luggage Register." }, { "code": null, "e": 61453, "s": 61368, "text": "Inform the guest that you are going to guest’s accommodation to collect the luggage." }, { "code": null, "e": 61538, "s": 61453, "text": "Inform the guest that you are going to guest’s accommodation to collect the luggage." }, { "code": null, "e": 61683, "s": 61538, "text": "Have an informal conversation with the guest as, \"Mr./Ms. (Guest_Name), I hope you enjoyed your stay with us. Do you need an airport transport?\"" }, { "code": null, "e": 61828, "s": 61683, "text": "Have an informal conversation with the guest as, \"Mr./Ms. (Guest_Name), I hope you enjoyed your stay with us. Do you need an airport transport?\"" }, { "code": null, "e": 61869, "s": 61828, "text": "Collect the luggage from the guest room." }, { "code": null, "e": 61910, "s": 61869, "text": "Collect the luggage from the guest room." }, { "code": null, "e": 62138, "s": 61910, "text": "If the guest needs to store the luggage for long term, tag the luggage with the guest name, accommodation number, date and time of collection, contact number, and receive the guest’s signature on long-term luggage request form." }, { "code": null, "e": 62366, "s": 62138, "text": "If the guest needs to store the luggage for long term, tag the luggage with the guest name, accommodation number, date and time of collection, contact number, and receive the guest’s signature on long-term luggage request form." }, { "code": null, "e": 62437, "s": 62366, "text": "Ensure with the guest that nothing perishable is there in the luggage." }, { "code": null, "e": 62508, "s": 62437, "text": "Ensure with the guest that nothing perishable is there in the luggage." }, { "code": null, "e": 62560, "s": 62508, "text": "Store the luggage on the designated departure area." }, { "code": null, "e": 62612, "s": 62560, "text": "Store the luggage on the designated departure area." }, { "code": null, "e": 62712, "s": 62612, "text": "If the guest is leaving the hotel immediately after check-out, then bring the luggage to the lobby." }, { "code": null, "e": 62812, "s": 62712, "text": "If the guest is leaving the hotel immediately after check-out, then bring the luggage to the lobby." }, { "code": null, "e": 62889, "s": 62812, "text": "If a transport vehicle is ready to go then place the luggage in the vehicle." }, { "code": null, "e": 62966, "s": 62889, "text": "If a transport vehicle is ready to go then place the luggage in the vehicle." }, { "code": null, "e": 63014, "s": 62966, "text": "Request the guest to verify the loaded luggage." }, { "code": null, "e": 63062, "s": 63014, "text": "Request the guest to verify the loaded luggage." }, { "code": null, "e": 63140, "s": 63062, "text": "Update the departure luggage movement on the Daily Luggage movement register." }, { "code": null, "e": 63218, "s": 63140, "text": "Update the departure luggage movement on the Daily Luggage movement register." }, { "code": null, "e": 63244, "s": 63218, "text": "The SOP goes as follows −" }, { "code": null, "e": 63286, "s": 63244, "text": "Pick up the incoming call in three rings." }, { "code": null, "e": 63328, "s": 63286, "text": "Pick up the incoming call in three rings." }, { "code": null, "e": 63497, "s": 63328, "text": "Greet the guest in the audible voice, introduce yourself, and ask how you can help the guest as, “Good (morning/evening), this is Mr./Ms. own_name, how may I help you?”" }, { "code": null, "e": 63666, "s": 63497, "text": "Greet the guest in the audible voice, introduce yourself, and ask how you can help the guest as, “Good (morning/evening), this is Mr./Ms. own_name, how may I help you?”" }, { "code": null, "e": 63697, "s": 63666, "text": "Wait for the guest to respond." }, { "code": null, "e": 63728, "s": 63697, "text": "Wait for the guest to respond." }, { "code": null, "e": 63793, "s": 63728, "text": "The guests say that he/she needs an accommodation in your hotel." }, { "code": null, "e": 63858, "s": 63793, "text": "The guests say that he/she needs an accommodation in your hotel." }, { "code": null, "e": 63898, "s": 63858, "text": "Tell the guest that it’s your pleasure." }, { "code": null, "e": 63938, "s": 63898, "text": "Tell the guest that it’s your pleasure." }, { "code": null, "e": 63967, "s": 63938, "text": "Take a new reservation form." }, { "code": null, "e": 63996, "s": 63967, "text": "Take a new reservation form." }, { "code": null, "e": 64091, "s": 63996, "text": "Inform the guest about the types of accommodations in your hotel and their respective charges." }, { "code": null, "e": 64186, "s": 64091, "text": "Inform the guest about the types of accommodations in your hotel and their respective charges." }, { "code": null, "e": 64271, "s": 64186, "text": "Ask for the guest’s name, contact number, and type of accommodation the guest wants." }, { "code": null, "e": 64356, "s": 64271, "text": "Ask for the guest’s name, contact number, and type of accommodation the guest wants." }, { "code": null, "e": 64408, "s": 64356, "text": "Ask for the guest’s dates of arrival and departure." }, { "code": null, "e": 64460, "s": 64408, "text": "Ask for the guest’s dates of arrival and departure." }, { "code": null, "e": 64524, "s": 64460, "text": "Check for availability of the accommodation during those dates." }, { "code": null, "e": 64588, "s": 64524, "text": "Check for availability of the accommodation during those dates." }, { "code": null, "e": 64653, "s": 64588, "text": "Briefly describe the amenities the hotel provides to its guests." }, { "code": null, "e": 64718, "s": 64653, "text": "Briefly describe the amenities the hotel provides to its guests." }, { "code": null, "e": 64771, "s": 64718, "text": "If the accommodation is available, inform the guest." }, { "code": null, "e": 64824, "s": 64771, "text": "If the accommodation is available, inform the guest." }, { "code": null, "e": 64954, "s": 64824, "text": "If exactly the same kind of accommodation is not available, ask the guest if he/she would care for another type of accommodation." }, { "code": null, "e": 65084, "s": 64954, "text": "If exactly the same kind of accommodation is not available, ask the guest if he/she would care for another type of accommodation." }, { "code": null, "e": 65149, "s": 65084, "text": "Note down the guest’s requirements related to the accommodation." }, { "code": null, "e": 65214, "s": 65149, "text": "Note down the guest’s requirements related to the accommodation." }, { "code": null, "e": 65275, "s": 65214, "text": "Ask the guest if an airport pickup/drop service is required." }, { "code": null, "e": 65336, "s": 65275, "text": "Ask the guest if an airport pickup/drop service is required." }, { "code": null, "e": 65413, "s": 65336, "text": "Ask how the guest would settle the bill: by cash, credit, or direct billing." }, { "code": null, "e": 65490, "s": 65413, "text": "Ask how the guest would settle the bill: by cash, credit, or direct billing." }, { "code": null, "e": 65639, "s": 65490, "text": "If the guest prefers by cash or by card, then insist to pay the part of cash in advance against booking charges or credit card details of the guest." }, { "code": null, "e": 65788, "s": 65639, "text": "If the guest prefers by cash or by card, then insist to pay the part of cash in advance against booking charges or credit card details of the guest." }, { "code": null, "e": 65920, "s": 65788, "text": "Inform about reservation with the guest name, contact number, accommodation type required, payment method, and confirmation number." }, { "code": null, "e": 66052, "s": 65920, "text": "Inform about reservation with the guest name, contact number, accommodation type required, payment method, and confirmation number." }, { "code": null, "e": 66135, "s": 66052, "text": "Conclude the conversation as, “Thank you for calling hotel_name, have a nice day!”" }, { "code": null, "e": 66218, "s": 66135, "text": "Conclude the conversation as, “Thank you for calling hotel_name, have a nice day!”" }, { "code": null, "e": 66244, "s": 66218, "text": "The SOP goes as follows −" }, { "code": null, "e": 66287, "s": 66244, "text": "Upon the guest’s arrival, greet the guest." }, { "code": null, "e": 66328, "s": 66287, "text": "Ask the guest for his/her name politely." }, { "code": null, "e": 66370, "s": 66328, "text": "Search the reservation record in the PMS." }, { "code": null, "e": 66410, "s": 66370, "text": "Generate and print a registration card." }, { "code": null, "e": 66469, "s": 66410, "text": "Handover a GRC to the guest for verifying printed details." }, { "code": null, "e": 66537, "s": 66469, "text": "Request the guest to show the ID card from an authorized institute." }, { "code": null, "e": 66599, "s": 66537, "text": "Request to show passport and visa in case of foreigner guest." }, { "code": null, "e": 66838, "s": 66599, "text": "Request the guest to fill in the following details on the GRC −\n\nSalutation\nDesignation\nOrganization\nBusiness or Residence Address with City and ZIP Code\nPurpose of Visit\nContact Number in case of Emergency\nPassport Details\nVisa Details\n\n" }, { "code": null, "e": 66849, "s": 66838, "text": "Salutation" }, { "code": null, "e": 66861, "s": 66849, "text": "Designation" }, { "code": null, "e": 66874, "s": 66861, "text": "Organization" }, { "code": null, "e": 66927, "s": 66874, "text": "Business or Residence Address with City and ZIP Code" }, { "code": null, "e": 66944, "s": 66927, "text": "Purpose of Visit" }, { "code": null, "e": 66980, "s": 66944, "text": "Contact Number in case of Emergency" }, { "code": null, "e": 66997, "s": 66980, "text": "Passport Details" }, { "code": null, "e": 67010, "s": 66997, "text": "Visa Details" }, { "code": null, "e": 67068, "s": 67010, "text": "Inform the guest about any early/late check-out policies." }, { "code": null, "e": 67106, "s": 67068, "text": "Request the guest to sign on the GRC." }, { "code": null, "e": 67128, "s": 67106, "text": "Counter-sign the GRC." }, { "code": null, "e": 67168, "s": 67128, "text": "Update the details on the guest record." }, { "code": null, "e": 67192, "s": 67168, "text": "Create a guest account." }, { "code": null, "e": 67245, "s": 67192, "text": "Prepare copies of driving license/passport and visa." }, { "code": null, "e": 67293, "s": 67245, "text": "Attach them to the GRC and file the entire set." }, { "code": null, "e": 67338, "s": 67293, "text": "There are manual and automatic wakeup calls." }, { "code": null, "e": 67453, "s": 67338, "text": "The guest can request for a wakeup call at the front office directly or by calling from his/her own accommodation." }, { "code": null, "e": 67568, "s": 67453, "text": "The guest can request for a wakeup call at the front office directly or by calling from his/her own accommodation." }, { "code": null, "e": 67653, "s": 67568, "text": "Ask the guest for a wake-up time and any immediate special request after getting up." }, { "code": null, "e": 67738, "s": 67653, "text": "Ask the guest for a wake-up time and any immediate special request after getting up." }, { "code": null, "e": 67931, "s": 67738, "text": "Open the Wakeup Call Register and enter the following information −\n\nSalutation\nGuest Name\nAccommodation number\nWakeup date\nWakeup time\nAny Special immediate request such as tea/coffee, etc.\n\n" }, { "code": null, "e": 67999, "s": 67931, "text": "Open the Wakeup Call Register and enter the following information −" }, { "code": null, "e": 68010, "s": 67999, "text": "Salutation" }, { "code": null, "e": 68021, "s": 68010, "text": "Salutation" }, { "code": null, "e": 68032, "s": 68021, "text": "Guest Name" }, { "code": null, "e": 68043, "s": 68032, "text": "Guest Name" }, { "code": null, "e": 68064, "s": 68043, "text": "Accommodation number" }, { "code": null, "e": 68085, "s": 68064, "text": "Accommodation number" }, { "code": null, "e": 68097, "s": 68085, "text": "Wakeup date" }, { "code": null, "e": 68109, "s": 68097, "text": "Wakeup date" }, { "code": null, "e": 68121, "s": 68109, "text": "Wakeup time" }, { "code": null, "e": 68133, "s": 68121, "text": "Wakeup time" }, { "code": null, "e": 68188, "s": 68133, "text": "Any Special immediate request such as tea/coffee, etc." }, { "code": null, "e": 68243, "s": 68188, "text": "Any Special immediate request such as tea/coffee, etc." }, { "code": null, "e": 68298, "s": 68243, "text": "Conclude the conversation by greeting the guest again." }, { "code": null, "e": 68353, "s": 68298, "text": "Conclude the conversation by greeting the guest again." }, { "code": null, "e": 68420, "s": 68353, "text": "Pass the special request for tea/coffee to the room service staff." }, { "code": null, "e": 68487, "s": 68420, "text": "Pass the special request for tea/coffee to the room service staff." }, { "code": null, "e": 68732, "s": 68487, "text": "At the time of wakeup call, follow the given steps −\n\nConfirm the current time.\nCall the guest’s accommodation number on telephone.\nGreet the guest as per the time and inform about the current time and the progress on guest’s special request.\n\n" }, { "code": null, "e": 68785, "s": 68732, "text": "At the time of wakeup call, follow the given steps −" }, { "code": null, "e": 68811, "s": 68785, "text": "Confirm the current time." }, { "code": null, "e": 68837, "s": 68811, "text": "Confirm the current time." }, { "code": null, "e": 68889, "s": 68837, "text": "Call the guest’s accommodation number on telephone." }, { "code": null, "e": 68941, "s": 68889, "text": "Call the guest’s accommodation number on telephone." }, { "code": null, "e": 69052, "s": 68941, "text": "Greet the guest as per the time and inform about the current time and the progress on guest’s special request." }, { "code": null, "e": 69163, "s": 69052, "text": "Greet the guest as per the time and inform about the current time and the progress on guest’s special request." }, { "code": null, "e": 69381, "s": 69163, "text": "Most hotels facilitate their guests to set automatic wakeup call using their phones or televisions. The housekeeper must ensure that the printed instructions about setting an automatic call are kept handy and visible." }, { "code": null, "e": 69650, "s": 69381, "text": "The guest can set automatic call which is notified at the PBX system and the PMS system. Even if the guest has set up an automatic call, it is the responsibility of the front office staff to give a manual wakeup call to the guest to avoid any chances of inconvenience." }, { "code": null, "e": 69780, "s": 69650, "text": "The process of checking out generally is initiated by the guest. The guest calls up front office and asks to keep the bill ready." }, { "code": null, "e": 69817, "s": 69780, "text": "The guest arrives at the front desk." }, { "code": null, "e": 69834, "s": 69817, "text": "Greet the guest." }, { "code": null, "e": 69863, "s": 69834, "text": "Print a copy of guest folio." }, { "code": null, "e": 69907, "s": 69863, "text": "Hand it over to the guest for verification." }, { "code": null, "e": 69972, "s": 69907, "text": "If there is any discrepancy, assure the guest about its solving." }, { "code": null, "e": 70009, "s": 69972, "text": "Resolve the discrepancy immediately." }, { "code": null, "e": 70051, "s": 70009, "text": "Apologize to the guest for inconvenience." }, { "code": null, "e": 70149, "s": 70051, "text": "From the guest database, ensure the guest’s preference of payment method. Recite it to the guest." }, { "code": null, "e": 70175, "s": 70149, "text": "Settle the guest account." }, { "code": null, "e": 70219, "s": 70175, "text": "Print the receipt and give it to the guest." }, { "code": null, "e": 70277, "s": 70219, "text": "Ask the guest if he/she needs any assistance for luggage." }, { "code": null, "e": 70345, "s": 70277, "text": "Ask the guest if the transport facility to the airport is required." }, { "code": null, "e": 70480, "s": 70345, "text": "Greet the guest for giving an opportunity to serve as, “Hope you enjoyed your stay with us. Thank you. Good (morning/afternoon/night)." }, { "code": null, "e": 70566, "s": 70480, "text": "The guests initiate the cancellation of the reserved accommodation. The SOP goes as −" }, { "code": null, "e": 70624, "s": 70566, "text": "Request for the guest’s full name and reservation number." }, { "code": null, "e": 70682, "s": 70624, "text": "Request for the guest’s full name and reservation number." }, { "code": null, "e": 70751, "s": 70682, "text": "Search the guest database for the given name and reservation number." }, { "code": null, "e": 70820, "s": 70751, "text": "Search the guest database for the given name and reservation number." }, { "code": null, "e": 70894, "s": 70820, "text": "Recite the guest name, accommodation details and the date of reservation." }, { "code": null, "e": 70968, "s": 70894, "text": "Recite the guest name, accommodation details and the date of reservation." }, { "code": null, "e": 71019, "s": 70968, "text": "Ask the guest if he/she would like to postpone it." }, { "code": null, "e": 71070, "s": 71019, "text": "Ask the guest if he/she would like to postpone it." }, { "code": null, "e": 71120, "s": 71070, "text": "Request the guest for reason behind cancellation." }, { "code": null, "e": 71170, "s": 71120, "text": "Request the guest for reason behind cancellation." }, { "code": null, "e": 71200, "s": 71170, "text": "Record the reason in the PMS." }, { "code": null, "e": 71230, "s": 71200, "text": "Record the reason in the PMS." }, { "code": null, "e": 71385, "s": 71230, "text": "If the cancellation is being done by a person other than the guest, record the person’s name, contact number, and relation with the guest for information." }, { "code": null, "e": 71540, "s": 71385, "text": "If the cancellation is being done by a person other than the guest, record the person’s name, contact number, and relation with the guest for information." }, { "code": null, "e": 71633, "s": 71540, "text": "Inform the caller about any cancellation charges applicable according to the hotel policies." }, { "code": null, "e": 71726, "s": 71633, "text": "Inform the caller about any cancellation charges applicable according to the hotel policies." }, { "code": null, "e": 71761, "s": 71726, "text": "Cancel the reservation in the PMS." }, { "code": null, "e": 71796, "s": 71761, "text": "Cancel the reservation in the PMS." }, { "code": null, "e": 71931, "s": 71796, "text": "Inform the guest about e-mail for cancellation charges. Send the cancellation charges plus cancellation number to the guest by e-mail." }, { "code": null, "e": 72066, "s": 71931, "text": "Inform the guest about e-mail for cancellation charges. Send the cancellation charges plus cancellation number to the guest by e-mail." }, { "code": null, "e": 72328, "s": 72066, "text": "The front office staff needs to manage at least two sets of the keys. The number of sets may vary according to the guest policy. Accommodation numbers are not written on the keys, which creates problems when the keys are misplaced within or around the premises." }, { "code": null, "e": 72388, "s": 72328, "text": "Request for the guest’s last name and accommodation number." }, { "code": null, "e": 72448, "s": 72388, "text": "Request for the guest’s last name and accommodation number." }, { "code": null, "e": 72521, "s": 72448, "text": "Check the information told by the guest against the one recorded in PMS." }, { "code": null, "e": 72594, "s": 72521, "text": "Check the information told by the guest against the one recorded in PMS." }, { "code": null, "e": 72665, "s": 72594, "text": "If there is any deviation, request the guest to provide photo ID card." }, { "code": null, "e": 72736, "s": 72665, "text": "If there is any deviation, request the guest to provide photo ID card." }, { "code": null, "e": 72806, "s": 72736, "text": "Do not give away the accommodation key without proper authentication." }, { "code": null, "e": 72876, "s": 72806, "text": "Do not give away the accommodation key without proper authentication." }, { "code": null, "e": 72998, "s": 72876, "text": "If the doubt about the guest arises and the guest refuses to cooperate, then inform the front office manager immediately." }, { "code": null, "e": 73120, "s": 72998, "text": "If the doubt about the guest arises and the guest refuses to cooperate, then inform the front office manager immediately." }, { "code": null, "e": 73232, "s": 73120, "text": "If any other superior front office staff member recognizes the guest, then you can give away the duplicate key." }, { "code": null, "e": 73344, "s": 73232, "text": "If any other superior front office staff member recognizes the guest, then you can give away the duplicate key." }, { "code": null, "e": 73438, "s": 73344, "text": "If the guest has lost the key and needs a new one, then ascertain that the guest has lost it." }, { "code": null, "e": 73532, "s": 73438, "text": "If the guest has lost the key and needs a new one, then ascertain that the guest has lost it." }, { "code": null, "e": 73589, "s": 73532, "text": "In the above case, program a new key with the same code." }, { "code": null, "e": 73646, "s": 73589, "text": "In the above case, program a new key with the same code." }, { "code": null, "e": 73690, "s": 73646, "text": "Present the newly created key to the guest." }, { "code": null, "e": 73734, "s": 73690, "text": "Present the newly created key to the guest." }, { "code": null, "e": 74077, "s": 73734, "text": "You must not issue accommodation keys to any person that claims to be sent by the guest for getting the keys. Yet, you can give them to a non-guest, if the guest has sent the person with a written authority letter addressed to the front office team. In such case, confirm by calling the guest and accompany the non-guest to the accommodation." }, { "code": null, "e": 74420, "s": 74077, "text": "You must not issue accommodation keys to any person that claims to be sent by the guest for getting the keys. Yet, you can give them to a non-guest, if the guest has sent the person with a written authority letter addressed to the front office team. In such case, confirm by calling the guest and accompany the non-guest to the accommodation." }, { "code": null, "e": 74541, "s": 74420, "text": "The authorized staff on duty is allowed to access the occupied guest accommodation for the purpose of professional work." }, { "code": null, "e": 74688, "s": 74541, "text": "For example, the keys can be given for preparing vacated accommodation, laundry staff, mini-bar staff, and bell-boy to take out the guest luggage." }, { "code": null, "e": 74872, "s": 74688, "text": "One thing for sure, always try to solve the guest’s accommodation problem as far as possible. Try selling hotel service by giving options than plainly denying to what the guest wants." }, { "code": null, "e": 75001, "s": 74872, "text": "There are a number of reasons why a reservation staff needs to turn down the reservation request. These are few important ones −" }, { "code": null, "e": 75048, "s": 75001, "text": "The hotel is fully booked during busy seasons." }, { "code": null, "e": 75104, "s": 75048, "text": "Guest is not interested to reserve after knowing rates." }, { "code": null, "e": 75166, "s": 75104, "text": "The type of accommodation the guest desires is not available." }, { "code": null, "e": 75219, "s": 75166, "text": "This is how you turn down a reservation gracefully −" }, { "code": null, "e": 75355, "s": 75219, "text": "When the guest calls to enquire, answer the call as, “Good (morning, evening), this is own_name from reservations. How may I help you?”" }, { "code": null, "e": 75491, "s": 75355, "text": "When the guest calls to enquire, answer the call as, “Good (morning, evening), this is own_name from reservations. How may I help you?”" }, { "code": null, "e": 75553, "s": 75491, "text": "The guest says he/she would like to reserve an accommodation." }, { "code": null, "e": 75615, "s": 75553, "text": "The guest says he/she would like to reserve an accommodation." }, { "code": null, "e": 75718, "s": 75615, "text": "Reply as, “Certainly (Sir/Madam). May I request you for your name, mobile number and email ID please?”" }, { "code": null, "e": 75821, "s": 75718, "text": "Reply as, “Certainly (Sir/Madam). May I request you for your name, mobile number and email ID please?”" }, { "code": null, "e": 75847, "s": 75821, "text": "The guest tells the same." }, { "code": null, "e": 75873, "s": 75847, "text": "The guest tells the same." }, { "code": null, "e": 75928, "s": 75873, "text": "Further ask, “And your company/travel agency name is?”" }, { "code": null, "e": 75983, "s": 75928, "text": "Further ask, “And your company/travel agency name is?”" }, { "code": null, "e": 76033, "s": 75983, "text": "The guest replies, “I am from (Company/TA name)”." }, { "code": null, "e": 76083, "s": 76033, "text": "The guest replies, “I am from (Company/TA name)”." }, { "code": null, "e": 76158, "s": 76083, "text": "Ask the guest about check-in and check-out dates required for reservation." }, { "code": null, "e": 76233, "s": 76158, "text": "Ask the guest about check-in and check-out dates required for reservation." }, { "code": null, "e": 76331, "s": 76233, "text": "Request the guest to hold the line till you search for availability of the desired accommodation." }, { "code": null, "e": 76429, "s": 76331, "text": "Request the guest to hold the line till you search for availability of the desired accommodation." }, { "code": null, "e": 76502, "s": 76429, "text": "Inform the guest approximately how much time you would take to find out." }, { "code": null, "e": 76575, "s": 76502, "text": "Inform the guest approximately how much time you would take to find out." }, { "code": null, "e": 76620, "s": 76575, "text": "Put the call on hold and check availability." }, { "code": null, "e": 76665, "s": 76620, "text": "Put the call on hold and check availability." }, { "code": null, "e": 76866, "s": 76665, "text": "Convey the non-availability of the desired type of accommodation to the guest politely as, “Sorry sir/madam, “(all the accommodations are occupied/the desired type of accommodation is not available)”." }, { "code": null, "e": 77067, "s": 76866, "text": "Convey the non-availability of the desired type of accommodation to the guest politely as, “Sorry sir/madam, “(all the accommodations are occupied/the desired type of accommodation is not available)”." }, { "code": null, "e": 77130, "s": 77067, "text": "Suggest the guest about a nearby sister-concern hotel, if any." }, { "code": null, "e": 77193, "s": 77130, "text": "Suggest the guest about a nearby sister-concern hotel, if any." }, { "code": null, "e": 77284, "s": 77193, "text": "Suggest the guest to take other similar kind of accommodation by describing its amenities." }, { "code": null, "e": 77375, "s": 77284, "text": "Suggest the guest to take other similar kind of accommodation by describing its amenities." }, { "code": null, "e": 77499, "s": 77375, "text": "If the guest doesn’t agree to it, turn away politely as, “Sorry sir, then we don’t have any other available accommodation.”" }, { "code": null, "e": 77623, "s": 77499, "text": "If the guest doesn’t agree to it, turn away politely as, “Sorry sir, then we don’t have any other available accommodation.”" }, { "code": null, "e": 77691, "s": 77623, "text": "Record the guest data in the PMS along with the ‘Turn away’ reason." }, { "code": null, "e": 77759, "s": 77691, "text": "Record the guest data in the PMS along with the ‘Turn away’ reason." }, { "code": null, "e": 78145, "s": 77759, "text": "Hotel business is of a kind that needs to provide a myriad range of services to its guests such as food, accommodation, transport, recreational services, and so on. Since the front office contributes major portion in coordinating the services requested by the guests, it needs a system that can help the front office staff to sell services and track them seamlessly and simultaneously." }, { "code": null, "e": 78324, "s": 78145, "text": "The front office information system includes mainly the property management system. Let us see, what PMS is and how useful it is for handling hotel management functions smoothly." }, { "code": null, "e": 78530, "s": 78324, "text": "A Property Management System (PMS) is a software system employed to handle basic objectives of all the departments in the hotel business and coordinate functions between them for optimum business outcomes." }, { "code": null, "e": 78596, "s": 78530, "text": "A PMS is required for the hotel staff for the following reasons −" }, { "code": null, "e": 78664, "s": 78596, "text": "It integrates all critical operations of the hotel on one platform." }, { "code": null, "e": 78732, "s": 78664, "text": "It integrates all critical operations of the hotel on one platform." }, { "code": null, "e": 78866, "s": 78732, "text": "It provides real-time information on accommodations, reservations, restaurants, spas, bars, and about every working arm of the hotel." }, { "code": null, "e": 79000, "s": 78866, "text": "It provides real-time information on accommodations, reservations, restaurants, spas, bars, and about every working arm of the hotel." }, { "code": null, "e": 79138, "s": 79000, "text": "It provides highly accurate information which is helpful for the management to plan new goals and handle the investments in a better way." }, { "code": null, "e": 79276, "s": 79138, "text": "It provides highly accurate information which is helpful for the management to plan new goals and handle the investments in a better way." }, { "code": null, "e": 79388, "s": 79276, "text": "It boosts the efficiency of the front office staff and in turn maximizes the performance of the hotel business." }, { "code": null, "e": 79500, "s": 79388, "text": "It boosts the efficiency of the front office staff and in turn maximizes the performance of the hotel business." }, { "code": null, "e": 79577, "s": 79500, "text": "It simplifies the time-taking or complex operations otherwise done manually." }, { "code": null, "e": 79654, "s": 79577, "text": "It simplifies the time-taking or complex operations otherwise done manually." }, { "code": null, "e": 79741, "s": 79654, "text": "It works for the convenience of the hotel staff, managing body, as well as the guests." }, { "code": null, "e": 79828, "s": 79741, "text": "It works for the convenience of the hotel staff, managing body, as well as the guests." }, { "code": null, "e": 79863, "s": 79828, "text": "There are two basic types of PMS −" }, { "code": null, "e": 80052, "s": 79863, "text": "Local PMS − They have large technical requirements such as workstation, Computer/workstation, Data server, Terminal servers, Operating system, Network cards, and Removable back-up systems." }, { "code": null, "e": 80241, "s": 80052, "text": "Local PMS − They have large technical requirements such as workstation, Computer/workstation, Data server, Terminal servers, Operating system, Network cards, and Removable back-up systems." }, { "code": null, "e": 80323, "s": 80241, "text": "Cloud-based PMS − They mainly need computers/workstation and Internet connection." }, { "code": null, "e": 80405, "s": 80323, "text": "Cloud-based PMS − They mainly need computers/workstation and Internet connection." }, { "code": null, "e": 80422, "s": 80405, "text": "Availing the PMS" }, { "code": null, "e": 80477, "s": 80422, "text": "Owner needs to purchase the PMS hardware and software." }, { "code": null, "e": 80529, "s": 80477, "text": "Owner needs to take subscription from a PMS vendor." }, { "code": null, "e": 80564, "s": 80529, "text": "Requirement of Internet Connection" }, { "code": null, "e": 80567, "s": 80564, "text": "No" }, { "code": null, "e": 80619, "s": 80567, "text": "Yes, a reliable high speed connection is mandatory." }, { "code": null, "e": 80637, "s": 80619, "text": "System and Access" }, { "code": null, "e": 80721, "s": 80637, "text": "PMS software and data reside on a server to which multiple terminals are connected." }, { "code": null, "e": 80784, "s": 80721, "text": "The PMS is accessed from a program installed on each terminal." }, { "code": null, "e": 80865, "s": 80784, "text": "PMS software and data reside on a shared server at the PMS vendor’s data center." }, { "code": null, "e": 80935, "s": 80865, "text": "Users access the system through a Web browser from anywhere, anytime." }, { "code": null, "e": 80971, "s": 80935, "text": "Requirement of On-site IT expertise" }, { "code": null, "e": 80975, "s": 80971, "text": "Yes" }, { "code": null, "e": 80978, "s": 80975, "text": "No" }, { "code": null, "e": 80989, "s": 80978, "text": "Advantages" }, { "code": null, "e": 81030, "s": 80989, "text": "Does not rely on an Internet connection." }, { "code": null, "e": 81075, "s": 81030, "text": "Reduces concerns about online data security." }, { "code": null, "e": 81121, "s": 81075, "text": "Robust functionality for vast amount of data." }, { "code": null, "e": 81151, "s": 81121, "text": "Less costs of hardware or IT." }, { "code": null, "e": 81207, "s": 81151, "text": "No technical and data security responsibility on owner." }, { "code": null, "e": 81240, "s": 81207, "text": "Affordable subscription pricing." }, { "code": null, "e": 81262, "s": 81240, "text": "Simple, quick set-up." }, { "code": null, "e": 81298, "s": 81262, "text": "Easy access from anywhere, anytime." }, { "code": null, "e": 81322, "s": 81298, "text": "Automatic data back-up." }, { "code": null, "e": 81347, "s": 81322, "text": "Integrated Web bookings." }, { "code": null, "e": 81369, "s": 81347, "text": "Free system upgrades." }, { "code": null, "e": 81393, "s": 81369, "text": "Scalable and adaptable." }, { "code": null, "e": 81407, "s": 81393, "text": "Disadvantages" }, { "code": null, "e": 81448, "s": 81407, "text": "Requires complex and expensive hardware." }, { "code": null, "e": 81479, "s": 81448, "text": "Unreachable from remote areas." }, { "code": null, "e": 81530, "s": 81479, "text": "Expensive and complicated to maintain and upgrade." }, { "code": null, "e": 81582, "s": 81530, "text": "Time-consuming, software installation and training." }, { "code": null, "e": 81651, "s": 81582, "text": "Additional costs and hardware needed for enabling web-based features" }, { "code": null, "e": 81715, "s": 81651, "text": "Responsibility of system and data security is owner’s headache." }, { "code": null, "e": 81749, "s": 81715, "text": "On-site IT expertise is required." }, { "code": null, "e": 81817, "s": 81749, "text": "Not suitable for properties without a reliable Internet connection." }, { "code": null, "e": 81853, "s": 81817, "text": "High concerns over online security." }, { "code": null, "e": 81870, "s": 81853, "text": "Mark on Timeline" }, { "code": null, "e": 81900, "s": 81870, "text": "It is a traditional solution." }, { "code": null, "e": 81931, "s": 81900, "text": "It is a contemporary solution." }, { "code": null, "e": 81939, "s": 81931, "text": "Pricing" }, { "code": null, "e": 82058, "s": 81939, "text": "Capital expenditure and operational expenditure both; for hardware, software and its updates, and IT expert’s charges." }, { "code": null, "e": 82106, "s": 82058, "text": "Operational expenses for renewing subscription." }, { "code": null, "e": 82249, "s": 82106, "text": "Some popular PMS: Autoclerk, Skyware MSICloud, CloudPM, eZee Frontdesk, Hotelogix, Hetello, Hoteliga, OpenHotel, OPERA PMS, are to name a few." }, { "code": null, "e": 82353, "s": 82249, "text": "A PMS takes care of each department in the hotel. These are the commonly available features among PMS −" }, { "code": null, "e": 82365, "s": 82353, "text": "Reservation" }, { "code": null, "e": 82378, "s": 82365, "text": "Registration" }, { "code": null, "e": 82399, "s": 82378, "text": "Accommodation status" }, { "code": null, "e": 82428, "s": 82399, "text": "Guest and non-guest accounts" }, { "code": null, "e": 82442, "s": 82428, "text": "Cash handling" }, { "code": null, "e": 82457, "s": 82442, "text": "Night auditing" }, { "code": null, "e": 82465, "s": 82457, "text": "Reports" }, { "code": null, "e": 82504, "s": 82465, "text": "Guest database for market segmentation" }, { "code": null, "e": 82518, "s": 82504, "text": "Guest history" }, { "code": null, "e": 82535, "s": 82518, "text": "Yield management" }, { "code": null, "e": 82572, "s": 82535, "text": "Travel agents information as clients" }, { "code": null, "e": 82590, "s": 82572, "text": "Reports for goals" }, { "code": null, "e": 82637, "s": 82590, "text": "Performance evaluation by comparative analysis" }, { "code": null, "e": 82652, "s": 82637, "text": "Lost and found" }, { "code": null, "e": 82673, "s": 82652, "text": "Accommodation status" }, { "code": null, "e": 82689, "s": 82673, "text": "Laundry charges" }, { "code": null, "e": 82699, "s": 82689, "text": "POS sales" }, { "code": null, "e": 82718, "s": 82699, "text": "Material inventory" }, { "code": null, "e": 82741, "s": 82718, "text": "Periodic sales reports" }, { "code": null, "e": 82758, "s": 82741, "text": "Standard recipes" }, { "code": null, "e": 82838, "s": 82758, "text": "Individual staff member’s records regarding shifts, attendance, and appraisals." }, { "code": null, "e": 82871, "s": 82838, "text": "Account payables and receivables" }, { "code": null, "e": 82879, "s": 82871, "text": "Payroll" }, { "code": null, "e": 82893, "s": 82879, "text": "Balance sheet" }, { "code": null, "e": 82913, "s": 82893, "text": "Profit/Loss reports" }, { "code": null, "e": 82995, "s": 82913, "text": "Outgoing and incoming call records with date, time, place, duration, and charges." }, { "code": null, "e": 83070, "s": 82995, "text": "The following concerns are considered while selecting an appropriate PMS −" }, { "code": null, "e": 83121, "s": 83070, "text": "Size of the property: The number of accommodations" }, { "code": null, "e": 83141, "s": 83121, "text": "Number of locations" }, { "code": null, "e": 83161, "s": 83141, "text": "Number of employees" }, { "code": null, "e": 83187, "s": 83161, "text": "Property service policies" }, { "code": null, "e": 83231, "s": 83187, "text": "Budget for technical resources and training" }, { "code": null, "e": 83253, "s": 83231, "text": "Nearest future growth" }, { "code": null, "e": 83340, "s": 83253, "text": "User-friendly design that fosters intuitive navigation through logical order of tasks." }, { "code": null, "e": 83404, "s": 83340, "text": "Training expertise and time period required to train the staff." }, { "code": null, "e": 83429, "s": 83404, "text": "Hotel’s online presence." }, { "code": null, "e": 83459, "s": 83429, "text": "Guest-oriented functionality." }, { "code": null, "e": 83472, "s": 83459, "text": "Scalability." }, { "code": null, "e": 83509, "s": 83472, "text": "\n 127 Lectures \n 16.5 hours \n" }, { "code": null, "e": 83528, "s": 83509, "text": " Joseph Delgadillo" }, { "code": null, "e": 83565, "s": 83528, "text": "\n 131 Lectures \n 12.5 hours \n" }, { "code": null, "e": 83575, "s": 83565, "text": " Sandra L" }, { "code": null, "e": 83609, "s": 83575, "text": "\n 55 Lectures \n 11 hours \n" }, { "code": null, "e": 83645, "s": 83609, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 83682, "s": 83645, "text": "\n 107 Lectures \n 12.5 hours \n" }, { "code": null, "e": 83699, "s": 83682, "text": " Code And Create" }, { "code": null, "e": 83736, "s": 83699, "text": "\n 103 Lectures \n 16.5 hours \n" }, { "code": null, "e": 83744, "s": 83736, "text": " Nick O" }, { "code": null, "e": 83751, "s": 83744, "text": " Print" }, { "code": null, "e": 83762, "s": 83751, "text": " Add Notes" } ]
5 Exciting Deep Learning Advancements to Keep Your Eye on in 2021 | by Andre Ye | Towards Data Science
2021 is here, and deep learning is as active as ever; research in the field is speeding up exponentially. There are obviously many more deep learning advancements that are fascinating and exciting. To me, though, the five presented demonstrate a central undercurrent in ongoing deep learning research: how necessary is the largeness of deep learning models? tl;dr: GrowNet applies gradient boosting to shallow neural networks. It has been rising in popularity, yielding superior results in classification, regression, and ranking. It may indicate research supporting larger ensembles and shallower networks on non-specialized data (non-image or sequence). Gradient boosting has proven to become very popular in recent years, rivalling that of a neural network. The idea is to have an ensemble of weak (simple) learners, where each corrects the mistake of the previous. For instance, an ideal 3-model gradient boosting ensemble may look like this, where the real label of the example is 1. Model 1 predicts 0.734. Current prediction is 0.734.Model 2 predicts 0.464. Current prediction is 0.734+0.464=1.198 .Model 3 predicts -0.199. Current prediction is 1.198-0.199=0.999. Model 1 predicts 0.734. Current prediction is 0.734. Model 2 predicts 0.464. Current prediction is 0.734+0.464=1.198 . Model 3 predicts -0.199. Current prediction is 1.198-0.199=0.999. Each model is trained on the residual of the previous. Although each model may be individually weak, as a whole the ensemble can develop incredible complexity. Gradient boosting frameworks like XGBoost use gradient boosting on decision trees, which are one of the simplest machine learning algorithms. There has been some discussion on neural networks not being weak enough for gradient boosting; because gradient boosting has so much capability for overfitting, it is crucial that each learner in the ensemble be weak. However, recent work has shown that extremely deep neural networks can be decomposed into a collection of many smaller subnetworks. Therefore, massive neural networks may just be sophisticated ensembles of small neural networks. This challenges the idea that neural networks are too strong to be weak learners in gradient boosting. The GrowNet ensemble consists of k models. Each model is fed the original features and the predictions of the previous model. The predictions of all the models are summed to produce a final output. Every model can be as simple as having only one hidden layer. GrowNet is easy to tune and requires less computational cost and time to train, yet it outperforms deep neural networks in regression, classification, and ranking on multiple datasets. Data scientists have picked up on these benefits and it is growing in popularity. Paper, Pytorch Implementation tl;dr: TabNet is a deep leaning model for tabular data, designed with the ability to represent hierarchical relationships and draws inspiration from decision tree models. It has yielded superior results on many real-world tabular datasets. Neural networks are famously bad at modelling tabular data, and the accepted explanation is because their structure — very prone to overfitting — instead succeeds in recognizing the complex relationships of specialized data, like images or text. Decision-tree models like XGBoost or Adaboost have instead been popular with real-world tabular data, because they split the feature space in simple perpendicular planes. This level of separation is usually fine for most real-world datasets; even though these models, regardless how complex, make assumptions about decision boundaries, overfitting is a worse problem. Yet for many real-world datasets, decision-tree models are not enough and neural networks are too much. TabNet was created by two Google researchers to address this problem. The model relies on a fundamental neural network design, which makes decisions like a more complex decision tree. Furthermore, TabNet is trained in two stages. In the unsupervised pre-training stage, the model is trained to predict masked values in the data. Decision-making layers are then appended to the pretrained encoder and supervised fine-tuning takes place. This is one of first instance of incredibly successful unsupervised pre-training on tabular data. Critically, the model uses attention, so it can choose which features it will make a decision from. This allows it to develop a strong representation of hierarchical structures often present in real-world data. These mechanisms mean input data for TabNet need no processing whatsoever. TabNet is very quickly rising among data scientists; almost all of top-scoring competitors in the Mechanisms of Action Kaggle competition, for instance, incorporated TabNet into their solutions. Because of its popularity, it has been implemented in a very simple and usable API. This represents a broadening of deep learning past extremely specialized data types, and reveals just how universal neural networks can be. [link] Paper, Simple Pytorch API Implementation, Simple TensorFlow API Implementation tl;dr: Model scaling to improve deep CNNs can be unorganized. Compound scaling is a simple and effective method that uniformly scales the width, depth, and resolution of the network. EfficientNet is a simple network with compound scaling applied to it, and yields state of the art results. The model is incredibly popular in the image recognition work. Deep convolutional neural networks have been growing larger in an attempt to make them more powerful. Exactly how they become bigger, though, is actually quite arbitrary. Sometimes, the resolution of the image is increased (more pixels). Other times, it may be the depth (# of layers) or the width (# of neurons in each layer) that are increased. Compound scaling is a simple idea: instead of scaling them arbitrarily, scale the resolution, depth, and width of the network equally. If one wants to use 23 times more computational resources, for example; increase the network depth by α3 times increase the network width by β3 times increase the image size by γ3 times The values of α, β, and γ can be found through a simple grid search. Compound scaling can be applied to any network, and compound-scaled versions of models like ResNet have consistently performed better than arbitrary scaled ones. The authors of the paper developed a baseline model, EfficientNetB0, which consists of very standard convolutions. Then, using compound scaling, seven scaled models — EfficientNetB1 to EfficientNetB7 — were created. The results are amazing — EfficientNets were able to perform better than models that required 4 to 7 times more parameters and 6 to 19 times more computational resources. It seems that compound scaling is one of the most efficient ways to utilize neural network space. EfficientNet has been one of the most important recent contributions. It indicates a turn in research towards more powerful but also efficient and practical neural networks. Paper, Simple Pytorch API Implementation, Simple TensorFlow Implementation tl;dr: Neural networks are essentially giant lotteries; through random initialization, certain subnetworks are mathematically lucky and are recognized for their potential by the optimizer. These subnetworks (‘winning tickets’) emerge as doing most of the heavy lifting, while the rest of the network doesn’t do much. This hypothesis is groundbreaking in understanding how neural networks work. Why don’t neural networks overfit? How do they generalize with so many parameters? Why do big neural networks work better than smaller ones when it is common statistics principle that more parameters = overfitting? “Bah! Go away and shut up!” grumbles the deep learning community. “We don’t care about how neural networks work as long as they work.” Too long have these big questions been under-investigated. One common answer is regularization. However, this doesn’t seem to be the case — in a study conducted by Zhang et al., an Inception architecture without various regularization methods didn’t perform much worse than one with. Thus, one cannot argue that regularization is the basis for generalization. Neural network pruning offers a glimpse into one convincing answer. With neural network pruning, over 90 percent — in some cases 95 or even 99 percent — of neural network weights and neurons can be eliminated with little to no loss on performance. How can this be? Imagine you want to order a pen on Amazon. When the delivery package arrives, you find it is in a large cardboard box with lots of stuffing inside it. You finally find the pen after several minutes of searching. After you find the pen, the stuffing doesn’t matter. But before you find it, the stuffing is part of the delivery. The cardboard box with the stuffing is the neural network, and the pen is the subnetwork doing all the real work. After you locate that subnetwork, you can ditch the rest of the neural network. However, there needs to be a network in the first place to find the subnetwork. Lottery Ticket Hypothesis: In every sufficiently deep neural network, there is a smaller subnetwork that can perform just as well as the whole neural network. Weights in the neural network begin randomly initialized. At this point, there are plenty of random subnetworks in the network, but some have more mathematical potential. That is, the optimizer thinks it is mathematically better to update this set of weights to lower the loss. Eventually, the optimizer has developed a subnetwork to do all the work; the other parts of the network do not serve much of a purpose. Each subnetwork is a ‘lottery ticket’, with a random initialization. Favorable initializations are ‘winning tickets’ identified by the optimizer. The more random tickets you have, the higher probability one of them will be a winning ticket. This is why larger networks generally perform better. This hypothesis is particularly important to proposing an explanation for the Deep Double Descent, in which after a certain threshold, more parameters yields a better generalization rather than less. The Lottery Ticket Hypothesis is one giant step forward towards understanding truly how deep neural networks work. Although it’s still a hypothesis, there is convincing evidence for it, and such a discovery would transform how we approach innovation in deep learning. Paper tl;dr: Researchers developed a method to prune a completely randomly initialized network to achieve top performance with trained models. In close relationship with the Lottery Ticket Hypothesis, this study explores just how much information can lie in a neural network. It’s common for data scientists to see “60 million parameters” and underestimate how much power 60 million parameters can really store. In support of the Lottery Ticket Hypothesis, the authors of the paper developed the edge-popup algorithm, which assesses how ‘helpful’ an edge, or a connection, would be towards prediction. Only the k% more ‘helpful’ edges are retained; the remaining ones are pruned (removed). Using the edge-popup algorithm on a sufficiently large random neural network yields results very close to, and sometimes better than, performance of the trained neural network with all of its weights intact. That’s amazing — within a completely untrained, randomly initialized neural network lies already a top-performing subnetwork. This is like being told that your name can be found in a pretty short sequence of random letters. uqhoquiwhrpugtdfdsnaoidpufehiobnfjdopafwuhibdsofpabievniawo;jkjndjknajsodijaiufhuiduisafidjohndoeojahsiudhuidbviubdiaiupdphquiwhpeuhqiuhdpueohdpqiuwhdpiashiudhjashdiuhasiuhdibcisviywqrpiuhopfdbscjasnkuipi This study is more of a question than an answer. It points us in an area of new research: getting to the bottom of exactly how neural networks work. If these findings are universal, surely there must be a better training method that can take advantage of this fundamental axiom of deep learning waiting to be discovered. Paper GrowNet. This application of ensemble methods to deep learning is one demonstration of harnessing simple subnetwork structures into a complex, sophisticated, and successful model. TabNet. Neural network structures are exceptionally versatile, and TabNet marks the true expansion of neural networks to all sorts of data types. It is a perfect balance between underfitting and overfitting. EfficientNet. Part of a growing trend of packing more predictive power into less space, EfficientNet is incredibly simplistic yet effective. It demonstrates that there is indeed a structure towards scaling models. This is something incredibly important to pay attention to going forward as models continually become larger and larger. The Lottery Ticket Hypothesis. A fascinating perspective towards how neural networks generalize, the Lottery Ticket Hypothesis is a golden key that will help us unlock greater deep learning achievements. Identifying the power of large networks coming not from the largeness itself but an increased number of ‘lottery tickets’ is groundbreaking. The Top-Performing Model with Zero Training. A vivid demonstration of just how much we underestimate the predictive power within a randomly initialized neural network. There is no doubt 2021 will bring many more fascinating advancements in deep learning.
[ { "code": null, "e": 530, "s": 172, "text": "2021 is here, and deep learning is as active as ever; research in the field is speeding up exponentially. There are obviously many more deep learning advancements that are fascinating and exciting. To me, though, the five presented demonstrate a central undercurrent in ongoing deep learning research: how necessary is the largeness of deep learning models?" }, { "code": null, "e": 828, "s": 530, "text": "tl;dr: GrowNet applies gradient boosting to shallow neural networks. It has been rising in popularity, yielding superior results in classification, regression, and ranking. It may indicate research supporting larger ensembles and shallower networks on non-specialized data (non-image or sequence)." }, { "code": null, "e": 1161, "s": 828, "text": "Gradient boosting has proven to become very popular in recent years, rivalling that of a neural network. The idea is to have an ensemble of weak (simple) learners, where each corrects the mistake of the previous. For instance, an ideal 3-model gradient boosting ensemble may look like this, where the real label of the example is 1." }, { "code": null, "e": 1344, "s": 1161, "text": "Model 1 predicts 0.734. Current prediction is 0.734.Model 2 predicts 0.464. Current prediction is 0.734+0.464=1.198 .Model 3 predicts -0.199. Current prediction is 1.198-0.199=0.999." }, { "code": null, "e": 1397, "s": 1344, "text": "Model 1 predicts 0.734. Current prediction is 0.734." }, { "code": null, "e": 1463, "s": 1397, "text": "Model 2 predicts 0.464. Current prediction is 0.734+0.464=1.198 ." }, { "code": null, "e": 1529, "s": 1463, "text": "Model 3 predicts -0.199. Current prediction is 1.198-0.199=0.999." }, { "code": null, "e": 1831, "s": 1529, "text": "Each model is trained on the residual of the previous. Although each model may be individually weak, as a whole the ensemble can develop incredible complexity. Gradient boosting frameworks like XGBoost use gradient boosting on decision trees, which are one of the simplest machine learning algorithms." }, { "code": null, "e": 2049, "s": 1831, "text": "There has been some discussion on neural networks not being weak enough for gradient boosting; because gradient boosting has so much capability for overfitting, it is crucial that each learner in the ensemble be weak." }, { "code": null, "e": 2381, "s": 2049, "text": "However, recent work has shown that extremely deep neural networks can be decomposed into a collection of many smaller subnetworks. Therefore, massive neural networks may just be sophisticated ensembles of small neural networks. This challenges the idea that neural networks are too strong to be weak learners in gradient boosting." }, { "code": null, "e": 2641, "s": 2381, "text": "The GrowNet ensemble consists of k models. Each model is fed the original features and the predictions of the previous model. The predictions of all the models are summed to produce a final output. Every model can be as simple as having only one hidden layer." }, { "code": null, "e": 2908, "s": 2641, "text": "GrowNet is easy to tune and requires less computational cost and time to train, yet it outperforms deep neural networks in regression, classification, and ranking on multiple datasets. Data scientists have picked up on these benefits and it is growing in popularity." }, { "code": null, "e": 2938, "s": 2908, "text": "Paper, Pytorch Implementation" }, { "code": null, "e": 3178, "s": 2938, "text": "tl;dr: TabNet is a deep leaning model for tabular data, designed with the ability to represent hierarchical relationships and draws inspiration from decision tree models. It has yielded superior results on many real-world tabular datasets." }, { "code": null, "e": 3424, "s": 3178, "text": "Neural networks are famously bad at modelling tabular data, and the accepted explanation is because their structure — very prone to overfitting — instead succeeds in recognizing the complex relationships of specialized data, like images or text." }, { "code": null, "e": 3792, "s": 3424, "text": "Decision-tree models like XGBoost or Adaboost have instead been popular with real-world tabular data, because they split the feature space in simple perpendicular planes. This level of separation is usually fine for most real-world datasets; even though these models, regardless how complex, make assumptions about decision boundaries, overfitting is a worse problem." }, { "code": null, "e": 4080, "s": 3792, "text": "Yet for many real-world datasets, decision-tree models are not enough and neural networks are too much. TabNet was created by two Google researchers to address this problem. The model relies on a fundamental neural network design, which makes decisions like a more complex decision tree." }, { "code": null, "e": 4430, "s": 4080, "text": "Furthermore, TabNet is trained in two stages. In the unsupervised pre-training stage, the model is trained to predict masked values in the data. Decision-making layers are then appended to the pretrained encoder and supervised fine-tuning takes place. This is one of first instance of incredibly successful unsupervised pre-training on tabular data." }, { "code": null, "e": 4641, "s": 4430, "text": "Critically, the model uses attention, so it can choose which features it will make a decision from. This allows it to develop a strong representation of hierarchical structures often present in real-world data." }, { "code": null, "e": 4995, "s": 4641, "text": "These mechanisms mean input data for TabNet need no processing whatsoever. TabNet is very quickly rising among data scientists; almost all of top-scoring competitors in the Mechanisms of Action Kaggle competition, for instance, incorporated TabNet into their solutions. Because of its popularity, it has been implemented in a very simple and usable API." }, { "code": null, "e": 5142, "s": 4995, "text": "This represents a broadening of deep learning past extremely specialized data types, and reveals just how universal neural networks can be. [link]" }, { "code": null, "e": 5221, "s": 5142, "text": "Paper, Simple Pytorch API Implementation, Simple TensorFlow API Implementation" }, { "code": null, "e": 5574, "s": 5221, "text": "tl;dr: Model scaling to improve deep CNNs can be unorganized. Compound scaling is a simple and effective method that uniformly scales the width, depth, and resolution of the network. EfficientNet is a simple network with compound scaling applied to it, and yields state of the art results. The model is incredibly popular in the image recognition work." }, { "code": null, "e": 5921, "s": 5574, "text": "Deep convolutional neural networks have been growing larger in an attempt to make them more powerful. Exactly how they become bigger, though, is actually quite arbitrary. Sometimes, the resolution of the image is increased (more pixels). Other times, it may be the depth (# of layers) or the width (# of neurons in each layer) that are increased." }, { "code": null, "e": 6056, "s": 5921, "text": "Compound scaling is a simple idea: instead of scaling them arbitrarily, scale the resolution, depth, and width of the network equally." }, { "code": null, "e": 6128, "s": 6056, "text": "If one wants to use 23 times more computational resources, for example;" }, { "code": null, "e": 6167, "s": 6128, "text": "increase the network depth by α3 times" }, { "code": null, "e": 6206, "s": 6167, "text": "increase the network width by β3 times" }, { "code": null, "e": 6242, "s": 6206, "text": "increase the image size by γ3 times" }, { "code": null, "e": 6473, "s": 6242, "text": "The values of α, β, and γ can be found through a simple grid search. Compound scaling can be applied to any network, and compound-scaled versions of models like ResNet have consistently performed better than arbitrary scaled ones." }, { "code": null, "e": 6689, "s": 6473, "text": "The authors of the paper developed a baseline model, EfficientNetB0, which consists of very standard convolutions. Then, using compound scaling, seven scaled models — EfficientNetB1 to EfficientNetB7 — were created." }, { "code": null, "e": 6958, "s": 6689, "text": "The results are amazing — EfficientNets were able to perform better than models that required 4 to 7 times more parameters and 6 to 19 times more computational resources. It seems that compound scaling is one of the most efficient ways to utilize neural network space." }, { "code": null, "e": 7132, "s": 6958, "text": "EfficientNet has been one of the most important recent contributions. It indicates a turn in research towards more powerful but also efficient and practical neural networks." }, { "code": null, "e": 7207, "s": 7132, "text": "Paper, Simple Pytorch API Implementation, Simple TensorFlow Implementation" }, { "code": null, "e": 7601, "s": 7207, "text": "tl;dr: Neural networks are essentially giant lotteries; through random initialization, certain subnetworks are mathematically lucky and are recognized for their potential by the optimizer. These subnetworks (‘winning tickets’) emerge as doing most of the heavy lifting, while the rest of the network doesn’t do much. This hypothesis is groundbreaking in understanding how neural networks work." }, { "code": null, "e": 7816, "s": 7601, "text": "Why don’t neural networks overfit? How do they generalize with so many parameters? Why do big neural networks work better than smaller ones when it is common statistics principle that more parameters = overfitting?" }, { "code": null, "e": 8010, "s": 7816, "text": "“Bah! Go away and shut up!” grumbles the deep learning community. “We don’t care about how neural networks work as long as they work.” Too long have these big questions been under-investigated." }, { "code": null, "e": 8311, "s": 8010, "text": "One common answer is regularization. However, this doesn’t seem to be the case — in a study conducted by Zhang et al., an Inception architecture without various regularization methods didn’t perform much worse than one with. Thus, one cannot argue that regularization is the basis for generalization." }, { "code": null, "e": 8379, "s": 8311, "text": "Neural network pruning offers a glimpse into one convincing answer." }, { "code": null, "e": 8576, "s": 8379, "text": "With neural network pruning, over 90 percent — in some cases 95 or even 99 percent — of neural network weights and neurons can be eliminated with little to no loss on performance. How can this be?" }, { "code": null, "e": 8788, "s": 8576, "text": "Imagine you want to order a pen on Amazon. When the delivery package arrives, you find it is in a large cardboard box with lots of stuffing inside it. You finally find the pen after several minutes of searching." }, { "code": null, "e": 9177, "s": 8788, "text": "After you find the pen, the stuffing doesn’t matter. But before you find it, the stuffing is part of the delivery. The cardboard box with the stuffing is the neural network, and the pen is the subnetwork doing all the real work. After you locate that subnetwork, you can ditch the rest of the neural network. However, there needs to be a network in the first place to find the subnetwork." }, { "code": null, "e": 9336, "s": 9177, "text": "Lottery Ticket Hypothesis: In every sufficiently deep neural network, there is a smaller subnetwork that can perform just as well as the whole neural network." }, { "code": null, "e": 9750, "s": 9336, "text": "Weights in the neural network begin randomly initialized. At this point, there are plenty of random subnetworks in the network, but some have more mathematical potential. That is, the optimizer thinks it is mathematically better to update this set of weights to lower the loss. Eventually, the optimizer has developed a subnetwork to do all the work; the other parts of the network do not serve much of a purpose." }, { "code": null, "e": 10045, "s": 9750, "text": "Each subnetwork is a ‘lottery ticket’, with a random initialization. Favorable initializations are ‘winning tickets’ identified by the optimizer. The more random tickets you have, the higher probability one of them will be a winning ticket. This is why larger networks generally perform better." }, { "code": null, "e": 10245, "s": 10045, "text": "This hypothesis is particularly important to proposing an explanation for the Deep Double Descent, in which after a certain threshold, more parameters yields a better generalization rather than less." }, { "code": null, "e": 10513, "s": 10245, "text": "The Lottery Ticket Hypothesis is one giant step forward towards understanding truly how deep neural networks work. Although it’s still a hypothesis, there is convincing evidence for it, and such a discovery would transform how we approach innovation in deep learning." }, { "code": null, "e": 10519, "s": 10513, "text": "Paper" }, { "code": null, "e": 10656, "s": 10519, "text": "tl;dr: Researchers developed a method to prune a completely randomly initialized network to achieve top performance with trained models." }, { "code": null, "e": 10925, "s": 10656, "text": "In close relationship with the Lottery Ticket Hypothesis, this study explores just how much information can lie in a neural network. It’s common for data scientists to see “60 million parameters” and underestimate how much power 60 million parameters can really store." }, { "code": null, "e": 11203, "s": 10925, "text": "In support of the Lottery Ticket Hypothesis, the authors of the paper developed the edge-popup algorithm, which assesses how ‘helpful’ an edge, or a connection, would be towards prediction. Only the k% more ‘helpful’ edges are retained; the remaining ones are pruned (removed)." }, { "code": null, "e": 11411, "s": 11203, "text": "Using the edge-popup algorithm on a sufficiently large random neural network yields results very close to, and sometimes better than, performance of the trained neural network with all of its weights intact." }, { "code": null, "e": 11635, "s": 11411, "text": "That’s amazing — within a completely untrained, randomly initialized neural network lies already a top-performing subnetwork. This is like being told that your name can be found in a pretty short sequence of random letters." }, { "code": null, "e": 11840, "s": 11635, "text": "uqhoquiwhrpugtdfdsnaoidpufehiobnfjdopafwuhibdsofpabievniawo;jkjndjknajsodijaiufhuiduisafidjohndoeojahsiudhuidbviubdiaiupdphquiwhpeuhqiuhdpueohdpqiuwhdpiashiudhjashdiuhasiuhdibcisviywqrpiuhopfdbscjasnkuipi" }, { "code": null, "e": 12161, "s": 11840, "text": "This study is more of a question than an answer. It points us in an area of new research: getting to the bottom of exactly how neural networks work. If these findings are universal, surely there must be a better training method that can take advantage of this fundamental axiom of deep learning waiting to be discovered." }, { "code": null, "e": 12167, "s": 12161, "text": "Paper" }, { "code": null, "e": 12347, "s": 12167, "text": "GrowNet. This application of ensemble methods to deep learning is one demonstration of harnessing simple subnetwork structures into a complex, sophisticated, and successful model." }, { "code": null, "e": 12555, "s": 12347, "text": "TabNet. Neural network structures are exceptionally versatile, and TabNet marks the true expansion of neural networks to all sorts of data types. It is a perfect balance between underfitting and overfitting." }, { "code": null, "e": 12890, "s": 12555, "text": "EfficientNet. Part of a growing trend of packing more predictive power into less space, EfficientNet is incredibly simplistic yet effective. It demonstrates that there is indeed a structure towards scaling models. This is something incredibly important to pay attention to going forward as models continually become larger and larger." }, { "code": null, "e": 13235, "s": 12890, "text": "The Lottery Ticket Hypothesis. A fascinating perspective towards how neural networks generalize, the Lottery Ticket Hypothesis is a golden key that will help us unlock greater deep learning achievements. Identifying the power of large networks coming not from the largeness itself but an increased number of ‘lottery tickets’ is groundbreaking." }, { "code": null, "e": 13403, "s": 13235, "text": "The Top-Performing Model with Zero Training. A vivid demonstration of just how much we underestimate the predictive power within a randomly initialized neural network." } ]
Replace dot with comma on MySQL SELECT?
To replace dot with comma on SELECT, you can use REPLACE(). Following is the syntax − select replace(yourColumnName, '.' , ',' ) from yourTableName; Let us first create a table − mysql> create table DemoTable ( Value float ); Query OK, 0 rows affected (0.63 sec) Insert records in the table using insert command − mysql> insert into DemoTable values(4.56); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(456.23); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(1078.3); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values(2000.50); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable values(78.99); Query OK, 1 row affected (0.16 sec) Display records from the table using select command − mysql> select *from DemoTable; This will produce the following output − +--------+ | Value | +--------+ | 4.56 | | 456.23 | | 1078.3 | | 2000.5 | | 78.99 | +--------+ 5 rows in set (0.00 sec) Following is the query to replace dot with comma on SELECT − mysql> select replace(Value,'.',',') from DemoTable; This will produce the following output − +------------------------+ | replace(Value,'.',',') | +------------------------+ | 4,56 | | 456,23 | | 1078,3 | | 2000,5 | | 78,99 | +------------------------+ 5 rows in set (0.07 sec)
[ { "code": null, "e": 1122, "s": 1062, "text": "To replace dot with comma on SELECT, you can use REPLACE()." }, { "code": null, "e": 1149, "s": 1122, "text": " Following is the syntax −" }, { "code": null, "e": 1212, "s": 1149, "text": "select replace(yourColumnName, '.' , ',' ) from yourTableName;" }, { "code": null, "e": 1242, "s": 1212, "text": "Let us first create a table −" }, { "code": null, "e": 1329, "s": 1242, "text": "mysql> create table DemoTable\n(\n Value float\n);\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1380, "s": 1329, "text": "Insert records in the table using insert command −" }, { "code": null, "e": 1783, "s": 1380, "text": "mysql> insert into DemoTable values(4.56);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(456.23);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values(1078.3);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable values(2000.50);\nQuery OK, 1 row affected (0.26 sec)\nmysql> insert into DemoTable values(78.99);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1837, "s": 1783, "text": "Display records from the table using select command −" }, { "code": null, "e": 1868, "s": 1837, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1909, "s": 1868, "text": "This will produce the following output −" }, { "code": null, "e": 2033, "s": 1909, "text": "+--------+\n| Value |\n+--------+\n| 4.56 |\n| 456.23 |\n| 1078.3 |\n| 2000.5 |\n| 78.99 |\n+--------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2094, "s": 2033, "text": "Following is the query to replace dot with comma on SELECT −" }, { "code": null, "e": 2147, "s": 2094, "text": "mysql> select replace(Value,'.',',') from DemoTable;" }, { "code": null, "e": 2188, "s": 2147, "text": "This will produce the following output −" }, { "code": null, "e": 2456, "s": 2188, "text": "+------------------------+\n| replace(Value,'.',',') |\n+------------------------+\n| 4,56 |\n| 456,23 |\n| 1078,3 |\n| 2000,5 |\n| 78,99 |\n+------------------------+\n5 rows in set (0.07 sec)" } ]
Java Program to set the height of only a single row in a JTable with multiple rows
To set the row height, use the setRowHeight and set a parameter that would be the number of pixels you need to set the row height. However, if you want to set the row height of a single row then you need to use the same method, but set an additional parameter as shown below − table.setRowHeight(3, 30); The above sets row height to 30 pixels for row index 4. The following is an example to set the height of a row in a table − package my; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SwingDemo { public static void main(String[] argv) throws Exception { DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel); tableModel.addColumn("Language/ Technology"); tableModel.addColumn("Text Tutorial"); tableModel.addColumn("Video Tutorial"); tableModel.addColumn("Interview QA"); tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "Yes"}); tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "Yes"}); tableModel.addRow(new Object[] { "Java", "Yes", "No", "Yes"}); tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "Yes"}); tableModel.addRow(new Object[] { "MVC", "Yes", "No", "Yes"}); tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "Yes"}); tableModel.addRow(new Object[] { "F#", "Yes", "No", "Yes"}); tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "Yes"}); tableModel.addRow(new Object[] { "AWS", "No", "No", "Yes"}); table.setRowHeight(3, 30); JFrame f = new JFrame(); f.setSize(600, 400); f.add(new JScrollPane(table)); f.setVisible(true); } } The output is as follows. Here, we have set the row height for row 4 −
[ { "code": null, "e": 1193, "s": 1062, "text": "To set the row height, use the setRowHeight and set a parameter that would be the number of pixels you need to set the row height." }, { "code": null, "e": 1339, "s": 1193, "text": "However, if you want to set the row height of a single row then you need to use the same method, but set an additional parameter as shown below −" }, { "code": null, "e": 1366, "s": 1339, "text": "table.setRowHeight(3, 30);" }, { "code": null, "e": 1422, "s": 1366, "text": "The above sets row height to 30 pixels for row index 4." }, { "code": null, "e": 1490, "s": 1422, "text": "The following is an example to set the height of a row in a table −" }, { "code": null, "e": 2807, "s": 1490, "text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n DefaultTableModel tableModel = new DefaultTableModel();\n JTable table = new JTable(tableModel);\n tableModel.addColumn(\"Language/ Technology\");\n tableModel.addColumn(\"Text Tutorial\");\n tableModel.addColumn(\"Video Tutorial\");\n tableModel.addColumn(\"Interview QA\");\n tableModel.addRow(new Object[] { \"Blockchain\", \"Yes\", \"No\", \"Yes\"});\n tableModel.addRow(new Object[] { \"C#\", \"Yes\", \"Yes\", \"Yes\"});\n tableModel.addRow(new Object[] { \"Java\", \"Yes\", \"No\", \"Yes\"});\n tableModel.addRow(new Object[] { \"NodeJS\", \"No\", \"Yes\", \"Yes\"});\n tableModel.addRow(new Object[] { \"MVC\", \"Yes\", \"No\", \"Yes\"});\n tableModel.addRow(new Object[] { \"ASP.NET\", \"Yes\", \"Yes\", \"Yes\"});\n tableModel.addRow(new Object[] { \"F#\", \"Yes\", \"No\", \"Yes\"});\n tableModel.addRow(new Object[] { \"SharePoint\", \"Yes\", \"Yes\", \"Yes\"});\n tableModel.addRow(new Object[] { \"AWS\", \"No\", \"No\", \"Yes\"});\n table.setRowHeight(3, 30);\n JFrame f = new JFrame();\n f.setSize(600, 400);\n f.add(new JScrollPane(table));\n f.setVisible(true);\n }\n}" }, { "code": null, "e": 2878, "s": 2807, "text": "The output is as follows. Here, we have set the row height for row 4 −" } ]
Effect Size. Moving beyond the p-value | by Aren Carpenter | Towards Data Science
In the sciences, we deal with p-values and statistical tests constantly. We hope to see a p-value < 0.05 to declare that we’ve been successful in our efforts, but this fervor for incredibly low p-values means that we don’t ask another very important question. “Does it even matter?” Let’s take a case where we are looking at two sample means. Simply, the p-value is the probability that sample means are the “same” or come from the same underlying distribution. This is the null hypothesis (Ho: mean1 = mean2), whereas the alternative hypothesis (Ha: mean1 ≠ mean2) represents the two sample means not being equal. Dive deeper into hypothesis testing here. This post assumes some base knowledge. After conducting a two-sample t-test for difference of means we can calculate a p-value to either reject or fail to reject our null hypothesis. If we get a p-value of less than 0.05, then we can reject the null and conclude that the means are different. But that’s all we can say! Let’s get back to our initial question, “Does it even matter?” Even if we know that the means are different, we don’t know if that difference is significant. For a quick semantic point, I don’t mean that the difference is not statistically significant (that’s what our p-value gives us), but significant in the colloquial sense. Does it matter that one mean is different from the other, and by how much? It is possible to generate very significant p-values for effect sizes with little practical importance and vice versa. This is incredibly important in data science due to the size of our datasets. With enough observations, even tiny differences in parameters become statistically significant, even if these differences are not important. And for those not intimately familiar with the scale of the data, there is no common framework for interpreting these differences. For a deeper examination of Statistical Power and Power Analysis, Machine Learning Mastery has an excellent guide. Looking at the raw differences between means is one simple, quick method of assessing the effect size, but often requires some previous knowledge or sense of the data if it’s not an intuitive measure like height or weight. For example, with a population of male and female weights, perhaps men weigh 15 kg more than women on average. That is much more intuitive than (drawing from my previous research) a 2x increase in Investigations per Entry between control and experimental groups of Diamondback terrapins. Building on just raw values, you can also calculate an overlap threshold where the respective population distributions cross each other. Using the AUC (Area Under the Curve), you can then calculate the amount of overlap in the distributions and count the observations who are on the “wrong side”. This measure is also called the Misclassification Rate. Another unstandardized measure is the probability of Superiority. Basically, taken random samples from each group, what is the probability that one is larger than the other. It’s an easy method to calculate, but as a random measure it won’t be as precise as other methods. As unstandardized measures of effect size, both overlap and superiority have the benefits of being comparable between studies because they are raw probabilities and they provide raw values to get an intuitive sense of the differences between the groups. One way to rationalize the differences between the means is to standardize the effect size by dividing by some standardizer (usually standard deviation). The most common method is Cohen’s d. Simply, it’s used to represent the magnitude of differences between two groups on a given variable. We standardize the difference of means by dividing by the pooled standard deviation of all groups. You can also use the standard deviation from either of the groups alone if there is a normative comparison to be made (say you had a control group and an experimental group). d = effect size (difference of means) / pooled standard deviation In code, Cohen’s d for two groups can be calculated as: def cohen_d(group1, group2): """ Calculate Cohen's d for two groups. Group1/Group2: Pandas Series or Numpy array Return d: float64 """ diff = group1.mean() - group2.mean() n1, n2 = len(group1), len(group2) var1, var2 = group1.var(), group2.var() pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2) d = diff / np.sqrt(pooled_var) # sqrt of var is stdev return d # d is ultimately a ratio Once we have some value for d, how do we interpret it? Remember that d is a ratio and is thus unit-less. One benefit of this is that we can directly compare d values from studies with different units/parameters, for example new trial drugs with different mechanisms of action, to see their relative effect size. As a rule of thumb: Small Effect = 0.2 Medium Effect = 0.5 Large Effect = 0.8 Here’s a great tool for getting an intuitive sense of Cohen’s d. Effect size is very often overlooked when calculating various statistical tests on data, but it’s very important to know if the differences between our groups actually matter! In data science, our datasets can be very large which makes it easier to find statistically significant differences between groups, even if those differences aren’t practically significant. I’d recommend starting with an unstandardized method to get a sense of the raw difference between your groups, before calculating Cohen’s d to see how much that difference matters compared to other experiments! I’m always looking to connect and explore other projects! LinkedIn | Medium | GitHub
[ { "code": null, "e": 455, "s": 172, "text": "In the sciences, we deal with p-values and statistical tests constantly. We hope to see a p-value < 0.05 to declare that we’ve been successful in our efforts, but this fervor for incredibly low p-values means that we don’t ask another very important question. “Does it even matter?”" }, { "code": null, "e": 788, "s": 455, "text": "Let’s take a case where we are looking at two sample means. Simply, the p-value is the probability that sample means are the “same” or come from the same underlying distribution. This is the null hypothesis (Ho: mean1 = mean2), whereas the alternative hypothesis (Ha: mean1 ≠ mean2) represents the two sample means not being equal." }, { "code": null, "e": 869, "s": 788, "text": "Dive deeper into hypothesis testing here. This post assumes some base knowledge." }, { "code": null, "e": 1150, "s": 869, "text": "After conducting a two-sample t-test for difference of means we can calculate a p-value to either reject or fail to reject our null hypothesis. If we get a p-value of less than 0.05, then we can reject the null and conclude that the means are different. But that’s all we can say!" }, { "code": null, "e": 1554, "s": 1150, "text": "Let’s get back to our initial question, “Does it even matter?” Even if we know that the means are different, we don’t know if that difference is significant. For a quick semantic point, I don’t mean that the difference is not statistically significant (that’s what our p-value gives us), but significant in the colloquial sense. Does it matter that one mean is different from the other, and by how much?" }, { "code": null, "e": 1673, "s": 1554, "text": "It is possible to generate very significant p-values for effect sizes with little practical importance and vice versa." }, { "code": null, "e": 1751, "s": 1673, "text": "This is incredibly important in data science due to the size of our datasets." }, { "code": null, "e": 2023, "s": 1751, "text": "With enough observations, even tiny differences in parameters become statistically significant, even if these differences are not important. And for those not intimately familiar with the scale of the data, there is no common framework for interpreting these differences." }, { "code": null, "e": 2138, "s": 2023, "text": "For a deeper examination of Statistical Power and Power Analysis, Machine Learning Mastery has an excellent guide." }, { "code": null, "e": 2649, "s": 2138, "text": "Looking at the raw differences between means is one simple, quick method of assessing the effect size, but often requires some previous knowledge or sense of the data if it’s not an intuitive measure like height or weight. For example, with a population of male and female weights, perhaps men weigh 15 kg more than women on average. That is much more intuitive than (drawing from my previous research) a 2x increase in Investigations per Entry between control and experimental groups of Diamondback terrapins." }, { "code": null, "e": 2786, "s": 2649, "text": "Building on just raw values, you can also calculate an overlap threshold where the respective population distributions cross each other." }, { "code": null, "e": 3002, "s": 2786, "text": "Using the AUC (Area Under the Curve), you can then calculate the amount of overlap in the distributions and count the observations who are on the “wrong side”. This measure is also called the Misclassification Rate." }, { "code": null, "e": 3275, "s": 3002, "text": "Another unstandardized measure is the probability of Superiority. Basically, taken random samples from each group, what is the probability that one is larger than the other. It’s an easy method to calculate, but as a random measure it won’t be as precise as other methods." }, { "code": null, "e": 3529, "s": 3275, "text": "As unstandardized measures of effect size, both overlap and superiority have the benefits of being comparable between studies because they are raw probabilities and they provide raw values to get an intuitive sense of the differences between the groups." }, { "code": null, "e": 3720, "s": 3529, "text": "One way to rationalize the differences between the means is to standardize the effect size by dividing by some standardizer (usually standard deviation). The most common method is Cohen’s d." }, { "code": null, "e": 4094, "s": 3720, "text": "Simply, it’s used to represent the magnitude of differences between two groups on a given variable. We standardize the difference of means by dividing by the pooled standard deviation of all groups. You can also use the standard deviation from either of the groups alone if there is a normative comparison to be made (say you had a control group and an experimental group)." }, { "code": null, "e": 4160, "s": 4094, "text": "d = effect size (difference of means) / pooled standard deviation" }, { "code": null, "e": 4216, "s": 4160, "text": "In code, Cohen’s d for two groups can be calculated as:" }, { "code": null, "e": 4657, "s": 4216, "text": "def cohen_d(group1, group2): \"\"\" Calculate Cohen's d for two groups. Group1/Group2: Pandas Series or Numpy array Return d: float64 \"\"\" diff = group1.mean() - group2.mean() n1, n2 = len(group1), len(group2) var1, var2 = group1.var(), group2.var() pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2) d = diff / np.sqrt(pooled_var) # sqrt of var is stdev return d # d is ultimately a ratio" }, { "code": null, "e": 4969, "s": 4657, "text": "Once we have some value for d, how do we interpret it? Remember that d is a ratio and is thus unit-less. One benefit of this is that we can directly compare d values from studies with different units/parameters, for example new trial drugs with different mechanisms of action, to see their relative effect size." }, { "code": null, "e": 4989, "s": 4969, "text": "As a rule of thumb:" }, { "code": null, "e": 5008, "s": 4989, "text": "Small Effect = 0.2" }, { "code": null, "e": 5028, "s": 5008, "text": "Medium Effect = 0.5" }, { "code": null, "e": 5047, "s": 5028, "text": "Large Effect = 0.8" }, { "code": null, "e": 5112, "s": 5047, "text": "Here’s a great tool for getting an intuitive sense of Cohen’s d." }, { "code": null, "e": 5689, "s": 5112, "text": "Effect size is very often overlooked when calculating various statistical tests on data, but it’s very important to know if the differences between our groups actually matter! In data science, our datasets can be very large which makes it easier to find statistically significant differences between groups, even if those differences aren’t practically significant. I’d recommend starting with an unstandardized method to get a sense of the raw difference between your groups, before calculating Cohen’s d to see how much that difference matters compared to other experiments!" }, { "code": null, "e": 5747, "s": 5689, "text": "I’m always looking to connect and explore other projects!" } ]
Sequential Test Cases for Dynamic Pages
In this chapter, we will describe the various combinations of -n and -c with the important flags to gradually increase the load on your webserver. You should mainly focus on how the following metrics change as you increase the load − Requests per second Connection Times (ms) Percentage of the requests served within a certain time (ms) You should also notice for the threshold value when server starts getting stuck and you start getting failed requests. Let us do 100 sequential page-loads by a single user − $ ab -l -r -n 100 -c 1 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ This is ApacheBench, Version 2.3 <$Revision: 1604373 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: Rocket Server Hostname: 127.0.0.1 Server Port: 8000 Document Path: / Document Length: Variable Concurrency Level: 1 Time taken for tests: 0.045 seconds Complete requests: 100 Failed requests: 0 Non-2xx responses: 100 Keep-Alive requests: 0 Total transferred: 27700 bytes HTML transferred: 6600 bytes Requests per second: 2206.24 [#/sec] (mean) Time per request: 0.453 [ms] (mean) Time per request: 0.453 [ms] (mean, across all concurrent requests) Transfer rate: 596.80 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.0 0 0 Processing: 0 0 0.0 0 0 Waiting: 0 0 0.0 0 0 Total: 0 0 0.0 0 1 Percentage of the requests served within a certain time (ms) 50% 0 66% 0 75% 0 80% 0 90% 1 95% 1 98% 1 99% 1 100% 1 (longest request) This case corresponds to a peak load on a website that gets around 50,000+ hits a month. $ ab -l -r -n 10 -c 5 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ In the following subsequent outputs, we will be omitting the common header for clarity purpose. ... Requests per second: 2009.24 [#/sec] (mean) Time per request: 2.488 [ms] (mean) Time per request: 0.498 [ms] (mean, across all concurrent requests) Transfer rate: 543.52 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 1 0.5 1 2 Processing: 0 1 0.5 1 2 Waiting: 0 1 0.5 1 1 Total: 2 2 0.4 3 3 ERROR: The median and mean for the total time are more than twice the standard deviation apart. These results are NOT reliable. Percentage of the requests served within a certain time (ms) 50% 3 66% 3 75% 3 80% 3 90% 3 95% 3 98% 3 99% 3 100% 3 (longest request) This test corresponds to 100 page loads by 10 different concurrent users, each user is doing 10 sequential pages loads. $ ab -r -n 10 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ ... Requests per second: 2225.68 [#/sec] (mean) Time per request: 4.493 [ms] (mean) Time per request: 0.449 [ms] (mean, across all concurrent requests) Transfer rate: 602.07 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 1 2 0.7 2 3 Processing: 0 2 1.0 2 3 Waiting: 0 1 1.0 2 3 Total: 4 4 0.3 4 4 WARNING: The median and mean for the waiting time are not within a normal deviation These results are probably not that reliable. Percentage of the requests served within a certain time (ms) 50% 4 66% 4 75% 4 80% 4 90% 4 95% 4 98% 4 99% 4 100% 4 (longest request) This test corresponds to 400 page loads by 20 different concurrent users, each user is doing 20 sequential pages loads. $ ab -r -n 20 -c 20 -k -H “Accept-Encoding: gzip, deflate” http://127.0.0.1:8000/ ... Requests per second: 1619.96 [#/sec] (mean) Time per request: 12.346 [ms] (mean) Time per request: 0.617 [ms] (mean, across all concurrent requests) Transfer rate: 438.21 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 2 6 2.3 6 10 Processing: 1 5 2.9 5 10 Waiting: 0 5 2.9 5 9 Total: 10 11 0.6 11 12 Percentage of the requests served within a certain time (ms) 50% 11 66% 11 75% 12 80% 12 90% 12 95% 12 98% 12 99% 12 100% 12 (longest request) This test corresponds to 900 page loads by 30 different concurrent users, each user is doing 30 sequential pages loads. $ ab -r -n 30 -c 30 -k -H "Accept-Encoding: gzip, deflate" http://127.0.0.1:8000/ ... Requests per second: 2283.45 [#/sec] (mean) Time per request: 13.138 [ms] (mean) Time per request: 0.438 [ms] (mean, across all concurrent requests) Transfer rate: 617.69 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 2 6 2.7 6 11 Processing: 1 6 3.1 6 11 Waiting: 0 5 3.2 5 10 Total: 11 12 0.5 12 13 Percentage of the requests served within a certain time (ms) 50% 12 66% 12 75% 12 80% 12 90% 13 95% 13 98% 13 99% 13 100% 13 (longest request) We have now learned how to increase the load gradually on the website and test its performance. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 1981, "s": 1834, "text": "In this chapter, we will describe the various combinations of -n and -c with the important flags to gradually increase the load on your webserver." }, { "code": null, "e": 2068, "s": 1981, "text": "You should mainly focus on how the following metrics change as you increase the load −" }, { "code": null, "e": 2088, "s": 2068, "text": "Requests per second" }, { "code": null, "e": 2110, "s": 2088, "text": "Connection Times (ms)" }, { "code": null, "e": 2171, "s": 2110, "text": "Percentage of the requests served within a certain time (ms)" }, { "code": null, "e": 2290, "s": 2171, "text": "You should also notice for the threshold value when server starts getting stuck and you start getting failed requests." }, { "code": null, "e": 2345, "s": 2290, "text": "Let us do 100 sequential page-loads by a single user −" }, { "code": null, "e": 2432, "s": 2345, "text": "$ ab -l -r -n 100 -c 1 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 3731, "s": 2432, "text": "This is ApacheBench, Version 2.3 <$Revision: 1604373 $>\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\nLicensed to The Apache Software Foundation, http://www.apache.org/\n\nBenchmarking 127.0.0.1 (be patient).....done\n\n\nServer Software: Rocket\nServer Hostname: 127.0.0.1\nServer Port: 8000\n\nDocument Path: /\nDocument Length: Variable\n\nConcurrency Level: 1\nTime taken for tests: 0.045 seconds\nComplete requests: 100\nFailed requests: 0\nNon-2xx responses: 100\nKeep-Alive requests: 0\nTotal transferred: 27700 bytes\nHTML transferred: 6600 bytes\nRequests per second: 2206.24 [#/sec] (mean)\nTime per request: 0.453 [ms] (mean)\nTime per request: 0.453 [ms] (mean, across all concurrent requests)\nTransfer rate: 596.80 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 0.0 0 0\nProcessing: 0 0 0.0 0 0\nWaiting: 0 0 0.0 0 0\nTotal: 0 0 0.0 0 1\n\nPercentage of the requests served within a certain time (ms)\n 50% 0\n 66% 0\n 75% 0\n 80% 0\n 90% 1\n 95% 1\n 98% 1\n 99% 1\n 100% 1 (longest request)\n" }, { "code": null, "e": 3820, "s": 3731, "text": "This case corresponds to a peak load on a website that gets around 50,000+ hits a month." }, { "code": null, "e": 3906, "s": 3820, "text": "$ ab -l -r -n 10 -c 5 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 4002, "s": 3906, "text": "In the following subsequent outputs, we will be omitting the common header for clarity purpose." }, { "code": null, "e": 4798, "s": 4002, "text": "...\nRequests per second: 2009.24 [#/sec] (mean)\nTime per request: 2.488 [ms] (mean)\nTime per request: 0.498 [ms] (mean, across all concurrent requests)\nTransfer rate: 543.52 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 1 0.5 1 2\nProcessing: 0 1 0.5 1 2\nWaiting: 0 1 0.5 1 1\nTotal: 2 2 0.4 3 3\nERROR: The median and mean for the total time are more than twice the standard\n deviation apart. These results are NOT reliable.\n\nPercentage of the requests served within a certain time (ms)\n 50% 3\n 66% 3\n 75% 3\n 80% 3\n 90% 3\n 95% 3\n 98% 3\n 99% 3\n 100% 3 (longest request)\n" }, { "code": null, "e": 4918, "s": 4798, "text": "This test corresponds to 100 page loads by 10 different concurrent users, each user is doing 10 sequential pages loads." }, { "code": null, "e": 5003, "s": 4918, "text": "$ ab -r -n 10 -c 10 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 5802, "s": 5003, "text": "...\nRequests per second: 2225.68 [#/sec] (mean)\nTime per request: 4.493 [ms] (mean)\nTime per request: 0.449 [ms] (mean, across all concurrent requests)\nTransfer rate: 602.07 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 1 2 0.7 2 3\nProcessing: 0 2 1.0 2 3\nWaiting: 0 1 1.0 2 3\nTotal: 4 4 0.3 4 4\nWARNING: The median and mean for the waiting time are not within a normal deviation\n These results are probably not that reliable.\n\nPercentage of the requests served within a certain time (ms)\n 50% 4\n 66% 4\n 75% 4\n 80% 4\n 90% 4\n 95% 4\n 98% 4\n 99% 4\n 100% 4 (longest request)\n" }, { "code": null, "e": 5922, "s": 5802, "text": "This test corresponds to 400 page loads by 20 different concurrent users, each user is doing 20 sequential pages loads." }, { "code": null, "e": 6005, "s": 5922, "text": "$ ab -r -n 20 -c 20 -k -H “Accept-Encoding: gzip, deflate” http://127.0.0.1:8000/\n" }, { "code": null, "e": 6668, "s": 6005, "text": "...\nRequests per second: 1619.96 [#/sec] (mean)\nTime per request: 12.346 [ms] (mean)\nTime per request: 0.617 [ms] (mean, across all concurrent requests)\nTransfer rate: 438.21 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 2 6 2.3 6 10\nProcessing: 1 5 2.9 5 10\nWaiting: 0 5 2.9 5 9\nTotal: 10 11 0.6 11 12\n\nPercentage of the requests served within a certain time (ms)\n 50% 11\n 66% 11\n 75% 12\n 80% 12\n 90% 12\n 95% 12\n 98% 12\n 99% 12\n 100% 12 (longest request)\n " }, { "code": null, "e": 6788, "s": 6668, "text": "This test corresponds to 900 page loads by 30 different concurrent users, each user is doing 30 sequential pages loads." }, { "code": null, "e": 6873, "s": 6788, "text": "$ ab -r -n 30 -c 30 -k -H \"Accept-Encoding: gzip, deflate\" http://127.0.0.1:8000/\n" }, { "code": null, "e": 7535, "s": 6873, "text": "...\nRequests per second: 2283.45 [#/sec] (mean)\nTime per request: 13.138 [ms] (mean)\nTime per request: 0.438 [ms] (mean, across all concurrent requests)\nTransfer rate: 617.69 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 2 6 2.7 6 11\nProcessing: 1 6 3.1 6 11\nWaiting: 0 5 3.2 5 10\nTotal: 11 12 0.5 12 13\n\nPercentage of the requests served within a certain time (ms)\n 50% 12\n 66% 12\n 75% 12\n 80% 12\n 90% 13\n 95% 13\n 98% 13\n 99% 13\n 100% 13 (longest request)\n" }, { "code": null, "e": 7631, "s": 7535, "text": "We have now learned how to increase the load gradually on the website and test its performance." }, { "code": null, "e": 7666, "s": 7631, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7685, "s": 7666, "text": " Arnab Chakraborty" }, { "code": null, "e": 7720, "s": 7685, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7741, "s": 7720, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 7774, "s": 7741, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7787, "s": 7774, "text": " Nilay Mehta" }, { "code": null, "e": 7822, "s": 7787, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7840, "s": 7822, "text": " Bigdata Engineer" }, { "code": null, "e": 7873, "s": 7840, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 7891, "s": 7873, "text": " Bigdata Engineer" }, { "code": null, "e": 7924, "s": 7891, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 7942, "s": 7924, "text": " Bigdata Engineer" }, { "code": null, "e": 7949, "s": 7942, "text": " Print" }, { "code": null, "e": 7960, "s": 7949, "text": " Add Notes" } ]
Load and unload a table in SAP HANA using SQL query
In SAP HANA, it is possible to manually load and unload individual tables and table columns. You can perform loading of table to precisely measure the total or “worst case” amount of memory used by a particular table. A table is unload from database to actively free up memory. You can use following SQL queries to perform load/unload of table − LOAD <table_name> UNLOAD <table_name>
[ { "code": null, "e": 1155, "s": 1062, "text": "In SAP HANA, it is possible to manually load and unload individual tables and table columns." }, { "code": null, "e": 1280, "s": 1155, "text": "You can perform loading of table to precisely measure the total or “worst case” amount of memory used by a particular table." }, { "code": null, "e": 1340, "s": 1280, "text": "A table is unload from database to actively free up memory." }, { "code": null, "e": 1408, "s": 1340, "text": "You can use following SQL queries to perform load/unload of table −" }, { "code": null, "e": 1446, "s": 1408, "text": "LOAD <table_name>\nUNLOAD <table_name>" } ]
Writing Linguistic Rules for Natural Language Processing | by Jenny Lee | Towards Data Science
Ruminations of a LinguistA solution: Rule-Based Syntactic Feature ExtractionAn example: Question Type Extraction Using spaCy Ruminations of a Linguist A solution: Rule-Based Syntactic Feature Extraction An example: Question Type Extraction Using spaCy When I first started exploring data science towards the end of my Ph.D. program in linguistics, I was pleased to discover the role of linguistics — specifically, linguistic features — in the development of NLP models. At the same time, I was a bit perplexed by why there was relatively little talk of exploiting syntactic features (e.g., level of clausal embedding, presence of coordination, type of speech act, etc.) compared to other types of features, such as how many times a certain word occurs in the text (lexical features), word similarity measures (semantic features), and even where in the document a word or phrase occurs (positional features). For example, in a sentiment analysis task, we may use a list of content words (adjectives, nouns, verbs, and adverbs) as features to predict the semantic orientation of user feedback (i.e., positive or negative). In another feedback classification task, we may curate domain-specific lists of words or phrases to train a model that can direct user comments to an appropriate division of support, e.g., billing, technical, or customer service. Both these tasks require pre-built lexicons for feature extraction, and there are many such lexicons out there for public use, such as SocialSent and these ones curated by a Medium writer. (Also check out this research article which discusses different methods of building sentiment lexicons). While lexical features have played an important role in the development of many NLP applications, there has been relatively little work involving the use of syntactic features (one big exception being perhaps in the domain of grammar error detection). This was baffling (and a little bit irksome) to me as someone coming from a tradition of linguistics that gives syntax something of “supremacy” over semantics and phonology in the general architecture of grammar. This, of course, isn’t to say that linguists perceive syntax to be in some ways more important than the other branches of linguistics — but simply that it occupies a position of primacy in many models of grammar that posit that syntactic form is derived before a semantic or phonetic interpretation is achieved. Accustomed to this “centrality” of the syntactic module in linguistic theory, I struggled to make sense of the lukewarm attitude toward syntactic structure in NLP, which sharply contrasted with the great confidence that NLP developers put in lexical content as features. Language, as imagined by NLP, made me think of a fragmented Mr. Potato Head at times — two-dimensional body parts strewn on a page of a coloring book, words without relations to each other. Some of the unease I felt surrounding this apparent oversimplification of language (as a bag of words in my earliest understanding of it) did eventually dissipate when I caught on to the “magic” of machine learning/deep learning: Even without explicit coding, “it learns the syntax, too.” (And ironically, that is also how a child acquires language — without explicit instruction.) As a linguist (specifically a morphosyntactician), though, I am still honestly a bit hung up on the reality that syntactic features have not garnered as much attention as lexical features in NLP/ML, and I am inclined to attribute this asymmetry to the following reasons: As students of NLP, we are repeatedly introduced to an NLP pipeline that includes preprocessing techniques like stop words removal, lemmatization/stemming, and bag-of-words representation. These techniques are valuable in many cases but are inherently subtractive: They remove chunks of syntactic (and/or morphological) information that are present in the original text. Stop words removal eliminates function words which encode information about the relations between constituents/phrases, e.g., into, from, to, the, and, etc. Lemmatization and stemming removes important inflectional features such as tense and agreement as well as derivational affixes that may be crucial to determining the precise meaning of a word (e.g., -er in teacher, -ment in -embezzlement). And of course, bag-of-words representations disregard word order, a significant loss for a language like English which does not use morphological case to indicate word order. When these steps become normal and recurring parts of our everyday NLP pipeline, it has the potential to obscure or minimize the role that syntactic structure actually does play in natural language processing, consequently hindering or discouraging any efforts to systematically measure its impact on NLP models. I also speculate that the relative obscurity of syntactic features is in large part due to the practical challenges of writing sophisticated enough rules. NLP experts come into the field with varying degrees of knowledge in syntax, and without a firm grasp of the fundamentals and universals of syntactic structure that underlie every language as well as, to some extent, constraints on cross-linguistic variation, it may be difficult to know what syntactic features are relevant for a particular language, let alone go about writing heuristics to extract them. Unlike lexical features which in many cases amount to simple word counts, crafting well-thought-out linguistic rules at the sentence (syntactic) level is a much more challenging task that requires considerable domain knowledge. I also came to see that some of our most popular and commercialized NLP products do not require very complex syntactic representations of input text or speech — making syntactic features less than indispensable in the development of the models that power them. I think the reasons are (1) human speech in machine-human interaction tends to be oversimplified to begin with (“Hey Google, SF weather” vs. “Hey John, would you mind telling me what the weather is in San Francisco today?”) and (2) simple parses are more amenable to less computationally expensive systems than complex parses, so we’re compelled to work with those constraints. To be clear, the three things I outlined above are challenges/hindrances to using syntactic features, not justifications for excluding them, in feature engineering. While I’m not sure how much syntactic features can contribute to the performance of a model compared to other features, I do believe that as we seek to build machines that can interact with humans in much more subtle, natural, and sophisticated ways, syntactic input and representation will play an increasingly prominent role in the future of NLP. I think we would benefit greatly by doing these three things in response: Experiment more with syntactic features in our everyday ML endeavors and invest in streamlining that process so it becomes a repeated part of the pipeline.Create more open-source code for linguistic feature extraction.Hire more linguists — and help them grow in technical skills if necessary. Invest in them for the unique return they will bring. Experiment more with syntactic features in our everyday ML endeavors and invest in streamlining that process so it becomes a repeated part of the pipeline. Create more open-source code for linguistic feature extraction. Hire more linguists — and help them grow in technical skills if necessary. Invest in them for the unique return they will bring. In all three of these tasks, I think we would get the most mileage by exploiting, specifically, a rule-driven system. Syntax is an area that requires precise knowledge about a specific language and therefore lends itself well to rule-based representation (in NLP, that is), perhaps more so than any other area of grammar. The proposal to take a rule-based approach competes with taking an entirely ML approach to build feature sets. In the latter, you train a model that predicts the value of a specific feature to feed into a model that predicts the output of some target variable. This process is likely to be very time-consuming and expensive, however, because you’re training a model to train a model. And that is why I would recommend using rules as part of a hybrid system in almost all cases. Hybrid approaches combine an ML algorithm-driven base model with a rule-based system that serves as a kind of post-processing filter, and they are old news. There have been many successful applications of them, like this one and at my own job. Another advantage of rules and rule-based systems is that they can be used flexibly in a variety of ways and therefore bring value and rigor to almost every stage of the ML pipeline. In addition to using them to extract features during the feature engineering stage, they can also be used to: Pre-label large datasets to create noisy training data during data preparation (a labeling function)Exclude certain annotations during data preprocessing (a pre-filter)Filter out false positives from a classifier’s output before/during model evaluation (a post-filter) Pre-label large datasets to create noisy training data during data preparation (a labeling function) Exclude certain annotations during data preprocessing (a pre-filter) Filter out false positives from a classifier’s output before/during model evaluation (a post-filter) Therefore, it is hardly appropriate to pit rules or rule-based systems against ML algorithms as some might be inclined to do. Rather, we must acknowledge that they complement each other in some very compelling ways, adding a serious edge to the overall architecture. In this final section, I will provide a practical guide to writing some syntactic rules for feature extraction. I will use spaCy to do this, focusing on extracting question type. I chose question type because this category can illustrate particularly well the incredible value of linguistic knowledge in building a partially rule-driven NLP model. Moreover, there are probably many use cases for question type extraction (and by extension, sentence type), so hopefully, someone will benefit from the code below. Some applications I can think of are: a fine-grained classification of questions (is the sentence a wh-question, a yes or no question, or a tag question?), speech act detection (is the comment a question, request, or demand?), some comparative speech analyses (which individual or group uses more politeness strategies in their speech?), etc. With this concluding section, I ultimately hope to have driven home both the relevance of linguistic knowledge for NLP developers and the relevance of rules or rule-based systems in NLP/ML tasks. In writing linguistic rules, I generally follow these six steps: Identify categories of interest (e.g., “wh-question”, “polar question”, “not a question”).Come up with one or two big linguistic generalizations about each category.Come up with some counterexamples to the generalizations and revise/expand them as necessary.Write rules capturing the new generalizations.Test the rules on a bunch of examples.Fine-tune the rules by addressing any false positives and testing new examples. Identify categories of interest (e.g., “wh-question”, “polar question”, “not a question”). Come up with one or two big linguistic generalizations about each category. Come up with some counterexamples to the generalizations and revise/expand them as necessary. Write rules capturing the new generalizations. Test the rules on a bunch of examples. Fine-tune the rules by addressing any false positives and testing new examples. Often these steps will not be perfectly sequential. For example, identifying the categories you want to target (step 1) basically amounts to stating some generalizations about them (step 2), so you may do these steps at the same time. Before I illustrate how this flow can guide our rule writing, let’s dig into spaCy a bit. spaCy is a high-performance Python library that boasts of numerous features and capabilities to help you build your favorite NLP application, including tokenization, named entity recognition, part-of-speech tagging, dependency parsing, pre-trained word vectors and similarity, and built-in visualizers. Check out its full suite of features here, but here we’ll only be concerned with two of its processing components tbat will enable us to represent the syntactic structure of any sentence, namely, tagger and parser. The basic flow of using spaCy goes like this: First, load a model of your choice (e.g., "en_core_web_sm"). You can then examine the pipeline components by calling pipeline or pipeline_name on nlp. Next, call nlp by passing in a string and converting it to a spaCy Doc, a sequence of tokens (line 2 below). The syntactic structure of Doc can be constructed by accessing the following attributes of its component tokens: pos_: The coarse-grained part-of-speech tag. tag_: The fine-grained part-of-speech tag. dep_: The syntactic dependency tag, i.e. the relation between tokens. head: The syntactic governor, or the immediately dominating token I find it helpful to print out the values of these attributes along with token names and indices in tuples, like this: If you’d like to visualize the parse, type your sentence into spaCy’s built-in visualizer displaCy: The arrows indicate the head-dependent relations between tokens and each token is labeled with a coarse-level POS tag (fine-level (tag_) is not shown here). These two steps often go hand in hand. In coming up with rules for question type extraction, we must recognize that there are two types of questions in any language: wh-questions and polar questions. Read these generalizations carefully: Generalizations about question types:(1) Wh-questions (aka content questions): start with an interrogative word (a “wh-phrase”) like who, what, where, and how, and call for specific information.(2) Polar questions (aka yes or no questions): can be answered in the affirmative or the negative (with a yes or a no response), and begin with an auxiliary (did, do) or modal (will, can) verb. You may find it helpful to visualize these question types using displaCy. The last screenshot contains a parse for a wh-question and here’s one for a polar question: In addition to a visual parse, I like being able to see the pos-tag-dep triplet for each token, like this: Using your knowledge of Penn Treebank annotation conventions (because that’s what spaCy uses), you can try writing v1 functions that would capture the generalizations above. I usually prefer to write separate functions for the different categories rather than writing a single function that contains complicated if/then logic. Here’s a quick first version attempting to capture the generalizations in (1)-(2). Coming up with counterexamples to your initial generalizations is essential because they will challenge your basic assumptions about the linguistic phenomenon under consideration (here, question formation) and force you to identify a common thread between the different examples to express their behavior and characteristics in a unified, generalized way. Ultimately, that will help help you write simpler but more robust and comprehensive rules. The two generalizations given above are reproduced here to save you scrolling: (1) Wh-questions (aka content questions): start with an interrogative word (a “wh-phrase”) like who, what, where, and how, and call for specific information.(2) Polar questions (aka yes or no questions): can be answered in the affirmative or the negative (with a yes or a no response), and begin with an auxiliary (did, do) or modal (will, can) verb. Here’s the first pair of counterexamples to the generalization in (1): (3) What you say is unbelievable.(4) Who you're going to kill is not my problem. We see that (1) is not borne out by these sentences because despite beginning with a wh-word, they are not wh-questions! They are what linguists call wh-clefts, or pseudoclefts. Pseudoclefts are often described as giving emphasis, or “focus”, to part of the sentence and have the form in (5): (5) free relative + "be" + focused constituent A free relative is a wh-relative clause that (apparently) lacks a head noun (so “what you say” instead of “the thing you say”). This part of the pseudocleft introduces a topic (what the sentence is about) and is linked to a focused constituent which introduces new information (“unbelievable”) by the verb “be”. Here are some additional counterexamples to (1): (5) In which article did they talk about spaCy?(6) To whom did you read the article? These sentences fail to bear out (1) for a different reason: While they don’t start with a wh-phrase as the generalization says, they still are wh-questions in that they can be answered with specific information (e.g., an answer to (6) can be “I read the article to my sister.”). These sentences are so-called pied-piped constructions and are characterized by a wh-word appearing along with a preposition, as though it has “dragged” the other to the front of the sentence. (6) in particular can be contrasted with another sentence that “strands” a preposition: “Who did you read the article to?”. Finally, here are two counterexamples to the generalization about polar questions, stated in (2): (7) Is it going to rain tonight?(8) Were you sad about her leaving? These sentences show that in addition to auxiliary and modal verbs, the copula (“be”) as a main verb (vs. an auxiliary) should be included in the category of verbs that can appear at the beginning of polar questions. Stated more simply, a verb and a subject undergo inversion in polar questions when the verb is an auxiliary, a modal, or a form of “be” that serves as the main verb. This brings us to the following revised generalizations: (1') Wh-questions (aka content questions): contain an interrogative word (a “wh-phrase”) like who, what, where, and how, and call for more specific information.(2') Polar questions (aka yes or no questions): can be answered in the affirmative or the negative (with a yes or a no response), and display subject-verb inversion where the verb must be either an auxiliary (did, do), a modal (will, can), or a form of the main verb be. I think this step demonstrates quite palpably that linguistic knowledge is indispensable to writing sophisticated feature-extracting rules. Knowing that English employs various strategies to signal interrogative sentences such as subject-verb inversion and wh-movement, as well as recognizing (and having names for) interesting linguistic phenomena, like pied-piping and clefting, can help you formulate generalizations that can in turn help you write comprehensive rules that are not overly specific. We can now modify the earlier versions of the functions, is_wh_question_v1 and is_polar_question_v1, to conform to the new generalizations (1') and (2'). This part will require some time and practice before we can feel very confident and comfortable, so be patient! Below I’ll highlight a few core things that characterize each of the v2 functions: In is_wh_question_v2: Referring to spaCy tags (e.g., "WDT", "WP", etc.) makes your rules more general than referring to the individual wh-words (line 3). Pied-piping can be captured by a prep dependency relation between the wh-word and its head (the syntactic parent, or “governor” of the token) (line 8). Pseudoclefts are excluded by returning False if the wh-word stands in a csubj or advcl relation to its head (lines 11–13). In is_polar_question_v2, we need to account for two situations: The question occurs in a non-copular construction in which “is” (or another form of “be”, like “were”) functions as an auxiliary, e.g., “Is she using spaCy?” (the main verb here is “using”.)The question occurs in a copular construction in which “is” functions as the main verb, “Is the mouse dead?” The question occurs in a non-copular construction in which “is” (or another form of “be”, like “were”) functions as an auxiliary, e.g., “Is she using spaCy?” (the main verb here is “using”.) The question occurs in a copular construction in which “is” functions as the main verb, “Is the mouse dead?” Type 1 is captured in lines 14–16, and the inversion of the subject is with respect to the auxiliary. (The same lines of code can also account for subject-modal inversion, like “Can you read the article?”). Type II is captured in lines 20–22, and the inversion of the subject is with respect to the root, i.e., the sole token whose dependency tag is "ROOT" in the doc. The mutual exclusivity of polar questions and wh-questions is captured in lines 9–10. Finally, to put all of the above together, we can write a test function that takes a list of example sentences and prints the question type for each sentence. When I run get_question_type(sentences), I get the following output: In [352]: get_question_type(sentences)Is that for real? -- polarCan you stop? -- polarDo you love John? -- polarAre you sad? -- polarWas she singing? -- polarWon't you come over for dinner? -- polarWould you help me? -- polarWho do you love? -- whWhose child is that. -- whHow do you know him? -- whTo whom did she read the book? -- whI'm hungry. -- not a questionSpacy is so fun! -- not a questionTell me what you mean. -- not a questionWould love to help you. -- not a questionDon't be sad. -- not a questionWhatever you want. -- wh # false positive What you say is impossible. -- not a questionWhere you go, I will go. -- not a question Everything is correct except for the third to last sentence, “Whatever you want.”. With the v2 functions, we have achieved an accuracy of 18/19 = 94.7%. Not bad! Note that these rules are truly sensitive to the underlying syntactic structure of each sentence and not to some superficial properties like the presence of a question mark (as illustrated by the correct classification of the example “Whose child is that.”). And for good measure: from sklearn.metrics import classification_reportcr = classification_report(true_values, rules_predictions)print(cr) precision recall f1-score supportnot a question 1.00 0.88 0.93 8 polar 1.00 1.00 1.00 7 wh 0.80 1.00 0.89 4 As a final step, you will want to fine-tune your rules by addressing any false positives to increase precision (e.g., “Whatever you want.” was incorrectly classified as a wh-question) and testing with more examples (and more complex examples) to increase recall. When you are satisfied, apply the rules to new data and use the results at any stage of your workflow that you deem appropriate. For example, you may choose to incorporate them as features during feature engineering or use them as early as the data pipeline to generate noisy data for annotation. Linguistic rule writing for NLP/machine learning is a rich, iterative process that requires a deep understanding of language and the ability to codify that knowledge in the form of general heuristics in a programming language. While rules are probably not adequate to stand alone in most applications of NLP and good rule writing almost always requires expert knowledge, they have many advantages and are a great complement to ML algorithms. If I have convinced you at all of their value, please give spaCy a try and feel free to suggest a v3 function below or add a request for rules for other features. :)
[ { "code": null, "e": 297, "s": 172, "text": "Ruminations of a LinguistA solution: Rule-Based Syntactic Feature ExtractionAn example: Question Type Extraction Using spaCy" }, { "code": null, "e": 323, "s": 297, "text": "Ruminations of a Linguist" }, { "code": null, "e": 375, "s": 323, "text": "A solution: Rule-Based Syntactic Feature Extraction" }, { "code": null, "e": 424, "s": 375, "text": "An example: Question Type Extraction Using spaCy" }, { "code": null, "e": 1080, "s": 424, "text": "When I first started exploring data science towards the end of my Ph.D. program in linguistics, I was pleased to discover the role of linguistics — specifically, linguistic features — in the development of NLP models. At the same time, I was a bit perplexed by why there was relatively little talk of exploiting syntactic features (e.g., level of clausal embedding, presence of coordination, type of speech act, etc.) compared to other types of features, such as how many times a certain word occurs in the text (lexical features), word similarity measures (semantic features), and even where in the document a word or phrase occurs (positional features)." }, { "code": null, "e": 1523, "s": 1080, "text": "For example, in a sentiment analysis task, we may use a list of content words (adjectives, nouns, verbs, and adverbs) as features to predict the semantic orientation of user feedback (i.e., positive or negative). In another feedback classification task, we may curate domain-specific lists of words or phrases to train a model that can direct user comments to an appropriate division of support, e.g., billing, technical, or customer service." }, { "code": null, "e": 2069, "s": 1523, "text": "Both these tasks require pre-built lexicons for feature extraction, and there are many such lexicons out there for public use, such as SocialSent and these ones curated by a Medium writer. (Also check out this research article which discusses different methods of building sentiment lexicons). While lexical features have played an important role in the development of many NLP applications, there has been relatively little work involving the use of syntactic features (one big exception being perhaps in the domain of grammar error detection)." }, { "code": null, "e": 2865, "s": 2069, "text": "This was baffling (and a little bit irksome) to me as someone coming from a tradition of linguistics that gives syntax something of “supremacy” over semantics and phonology in the general architecture of grammar. This, of course, isn’t to say that linguists perceive syntax to be in some ways more important than the other branches of linguistics — but simply that it occupies a position of primacy in many models of grammar that posit that syntactic form is derived before a semantic or phonetic interpretation is achieved. Accustomed to this “centrality” of the syntactic module in linguistic theory, I struggled to make sense of the lukewarm attitude toward syntactic structure in NLP, which sharply contrasted with the great confidence that NLP developers put in lexical content as features." }, { "code": null, "e": 3055, "s": 2865, "text": "Language, as imagined by NLP, made me think of a fragmented Mr. Potato Head at times — two-dimensional body parts strewn on a page of a coloring book, words without relations to each other." }, { "code": null, "e": 3437, "s": 3055, "text": "Some of the unease I felt surrounding this apparent oversimplification of language (as a bag of words in my earliest understanding of it) did eventually dissipate when I caught on to the “magic” of machine learning/deep learning: Even without explicit coding, “it learns the syntax, too.” (And ironically, that is also how a child acquires language — without explicit instruction.)" }, { "code": null, "e": 3708, "s": 3437, "text": "As a linguist (specifically a morphosyntactician), though, I am still honestly a bit hung up on the reality that syntactic features have not garnered as much attention as lexical features in NLP/ML, and I am inclined to attribute this asymmetry to the following reasons:" }, { "code": null, "e": 4964, "s": 3708, "text": "As students of NLP, we are repeatedly introduced to an NLP pipeline that includes preprocessing techniques like stop words removal, lemmatization/stemming, and bag-of-words representation. These techniques are valuable in many cases but are inherently subtractive: They remove chunks of syntactic (and/or morphological) information that are present in the original text. Stop words removal eliminates function words which encode information about the relations between constituents/phrases, e.g., into, from, to, the, and, etc. Lemmatization and stemming removes important inflectional features such as tense and agreement as well as derivational affixes that may be crucial to determining the precise meaning of a word (e.g., -er in teacher, -ment in -embezzlement). And of course, bag-of-words representations disregard word order, a significant loss for a language like English which does not use morphological case to indicate word order. When these steps become normal and recurring parts of our everyday NLP pipeline, it has the potential to obscure or minimize the role that syntactic structure actually does play in natural language processing, consequently hindering or discouraging any efforts to systematically measure its impact on NLP models." }, { "code": null, "e": 5754, "s": 4964, "text": "I also speculate that the relative obscurity of syntactic features is in large part due to the practical challenges of writing sophisticated enough rules. NLP experts come into the field with varying degrees of knowledge in syntax, and without a firm grasp of the fundamentals and universals of syntactic structure that underlie every language as well as, to some extent, constraints on cross-linguistic variation, it may be difficult to know what syntactic features are relevant for a particular language, let alone go about writing heuristics to extract them. Unlike lexical features which in many cases amount to simple word counts, crafting well-thought-out linguistic rules at the sentence (syntactic) level is a much more challenging task that requires considerable domain knowledge." }, { "code": null, "e": 6393, "s": 5754, "text": "I also came to see that some of our most popular and commercialized NLP products do not require very complex syntactic representations of input text or speech — making syntactic features less than indispensable in the development of the models that power them. I think the reasons are (1) human speech in machine-human interaction tends to be oversimplified to begin with (“Hey Google, SF weather” vs. “Hey John, would you mind telling me what the weather is in San Francisco today?”) and (2) simple parses are more amenable to less computationally expensive systems than complex parses, so we’re compelled to work with those constraints." }, { "code": null, "e": 6981, "s": 6393, "text": "To be clear, the three things I outlined above are challenges/hindrances to using syntactic features, not justifications for excluding them, in feature engineering. While I’m not sure how much syntactic features can contribute to the performance of a model compared to other features, I do believe that as we seek to build machines that can interact with humans in much more subtle, natural, and sophisticated ways, syntactic input and representation will play an increasingly prominent role in the future of NLP. I think we would benefit greatly by doing these three things in response:" }, { "code": null, "e": 7328, "s": 6981, "text": "Experiment more with syntactic features in our everyday ML endeavors and invest in streamlining that process so it becomes a repeated part of the pipeline.Create more open-source code for linguistic feature extraction.Hire more linguists — and help them grow in technical skills if necessary. Invest in them for the unique return they will bring." }, { "code": null, "e": 7484, "s": 7328, "text": "Experiment more with syntactic features in our everyday ML endeavors and invest in streamlining that process so it becomes a repeated part of the pipeline." }, { "code": null, "e": 7548, "s": 7484, "text": "Create more open-source code for linguistic feature extraction." }, { "code": null, "e": 7677, "s": 7548, "text": "Hire more linguists — and help them grow in technical skills if necessary. Invest in them for the unique return they will bring." }, { "code": null, "e": 8721, "s": 7677, "text": "In all three of these tasks, I think we would get the most mileage by exploiting, specifically, a rule-driven system. Syntax is an area that requires precise knowledge about a specific language and therefore lends itself well to rule-based representation (in NLP, that is), perhaps more so than any other area of grammar. The proposal to take a rule-based approach competes with taking an entirely ML approach to build feature sets. In the latter, you train a model that predicts the value of a specific feature to feed into a model that predicts the output of some target variable. This process is likely to be very time-consuming and expensive, however, because you’re training a model to train a model. And that is why I would recommend using rules as part of a hybrid system in almost all cases. Hybrid approaches combine an ML algorithm-driven base model with a rule-based system that serves as a kind of post-processing filter, and they are old news. There have been many successful applications of them, like this one and at my own job." }, { "code": null, "e": 9014, "s": 8721, "text": "Another advantage of rules and rule-based systems is that they can be used flexibly in a variety of ways and therefore bring value and rigor to almost every stage of the ML pipeline. In addition to using them to extract features during the feature engineering stage, they can also be used to:" }, { "code": null, "e": 9283, "s": 9014, "text": "Pre-label large datasets to create noisy training data during data preparation (a labeling function)Exclude certain annotations during data preprocessing (a pre-filter)Filter out false positives from a classifier’s output before/during model evaluation (a post-filter)" }, { "code": null, "e": 9384, "s": 9283, "text": "Pre-label large datasets to create noisy training data during data preparation (a labeling function)" }, { "code": null, "e": 9453, "s": 9384, "text": "Exclude certain annotations during data preprocessing (a pre-filter)" }, { "code": null, "e": 9554, "s": 9453, "text": "Filter out false positives from a classifier’s output before/during model evaluation (a post-filter)" }, { "code": null, "e": 9821, "s": 9554, "text": "Therefore, it is hardly appropriate to pit rules or rule-based systems against ML algorithms as some might be inclined to do. Rather, we must acknowledge that they complement each other in some very compelling ways, adding a serious edge to the overall architecture." }, { "code": null, "e": 10676, "s": 9821, "text": "In this final section, I will provide a practical guide to writing some syntactic rules for feature extraction. I will use spaCy to do this, focusing on extracting question type. I chose question type because this category can illustrate particularly well the incredible value of linguistic knowledge in building a partially rule-driven NLP model. Moreover, there are probably many use cases for question type extraction (and by extension, sentence type), so hopefully, someone will benefit from the code below. Some applications I can think of are: a fine-grained classification of questions (is the sentence a wh-question, a yes or no question, or a tag question?), speech act detection (is the comment a question, request, or demand?), some comparative speech analyses (which individual or group uses more politeness strategies in their speech?), etc." }, { "code": null, "e": 10872, "s": 10676, "text": "With this concluding section, I ultimately hope to have driven home both the relevance of linguistic knowledge for NLP developers and the relevance of rules or rule-based systems in NLP/ML tasks." }, { "code": null, "e": 10937, "s": 10872, "text": "In writing linguistic rules, I generally follow these six steps:" }, { "code": null, "e": 11359, "s": 10937, "text": "Identify categories of interest (e.g., “wh-question”, “polar question”, “not a question”).Come up with one or two big linguistic generalizations about each category.Come up with some counterexamples to the generalizations and revise/expand them as necessary.Write rules capturing the new generalizations.Test the rules on a bunch of examples.Fine-tune the rules by addressing any false positives and testing new examples." }, { "code": null, "e": 11450, "s": 11359, "text": "Identify categories of interest (e.g., “wh-question”, “polar question”, “not a question”)." }, { "code": null, "e": 11526, "s": 11450, "text": "Come up with one or two big linguistic generalizations about each category." }, { "code": null, "e": 11620, "s": 11526, "text": "Come up with some counterexamples to the generalizations and revise/expand them as necessary." }, { "code": null, "e": 11667, "s": 11620, "text": "Write rules capturing the new generalizations." }, { "code": null, "e": 11706, "s": 11667, "text": "Test the rules on a bunch of examples." }, { "code": null, "e": 11786, "s": 11706, "text": "Fine-tune the rules by addressing any false positives and testing new examples." }, { "code": null, "e": 12111, "s": 11786, "text": "Often these steps will not be perfectly sequential. For example, identifying the categories you want to target (step 1) basically amounts to stating some generalizations about them (step 2), so you may do these steps at the same time. Before I illustrate how this flow can guide our rule writing, let’s dig into spaCy a bit." }, { "code": null, "e": 12826, "s": 12111, "text": "spaCy is a high-performance Python library that boasts of numerous features and capabilities to help you build your favorite NLP application, including tokenization, named entity recognition, part-of-speech tagging, dependency parsing, pre-trained word vectors and similarity, and built-in visualizers. Check out its full suite of features here, but here we’ll only be concerned with two of its processing components tbat will enable us to represent the syntactic structure of any sentence, namely, tagger and parser. The basic flow of using spaCy goes like this: First, load a model of your choice (e.g., \"en_core_web_sm\"). You can then examine the pipeline components by calling pipeline or pipeline_name on nlp." }, { "code": null, "e": 13048, "s": 12826, "text": "Next, call nlp by passing in a string and converting it to a spaCy Doc, a sequence of tokens (line 2 below). The syntactic structure of Doc can be constructed by accessing the following attributes of its component tokens:" }, { "code": null, "e": 13093, "s": 13048, "text": "pos_: The coarse-grained part-of-speech tag." }, { "code": null, "e": 13136, "s": 13093, "text": "tag_: The fine-grained part-of-speech tag." }, { "code": null, "e": 13206, "s": 13136, "text": "dep_: The syntactic dependency tag, i.e. the relation between tokens." }, { "code": null, "e": 13272, "s": 13206, "text": "head: The syntactic governor, or the immediately dominating token" }, { "code": null, "e": 13391, "s": 13272, "text": "I find it helpful to print out the values of these attributes along with token names and indices in tuples, like this:" }, { "code": null, "e": 13491, "s": 13391, "text": "If you’d like to visualize the parse, type your sentence into spaCy’s built-in visualizer displaCy:" }, { "code": null, "e": 13648, "s": 13491, "text": "The arrows indicate the head-dependent relations between tokens and each token is labeled with a coarse-level POS tag (fine-level (tag_) is not shown here)." }, { "code": null, "e": 13886, "s": 13648, "text": "These two steps often go hand in hand. In coming up with rules for question type extraction, we must recognize that there are two types of questions in any language: wh-questions and polar questions. Read these generalizations carefully:" }, { "code": null, "e": 14274, "s": 13886, "text": "Generalizations about question types:(1) Wh-questions (aka content questions): start with an interrogative word (a “wh-phrase”) like who, what, where, and how, and call for specific information.(2) Polar questions (aka yes or no questions): can be answered in the affirmative or the negative (with a yes or a no response), and begin with an auxiliary (did, do) or modal (will, can) verb." }, { "code": null, "e": 14440, "s": 14274, "text": "You may find it helpful to visualize these question types using displaCy. The last screenshot contains a parse for a wh-question and here’s one for a polar question:" }, { "code": null, "e": 14547, "s": 14440, "text": "In addition to a visual parse, I like being able to see the pos-tag-dep triplet for each token, like this:" }, { "code": null, "e": 14957, "s": 14547, "text": "Using your knowledge of Penn Treebank annotation conventions (because that’s what spaCy uses), you can try writing v1 functions that would capture the generalizations above. I usually prefer to write separate functions for the different categories rather than writing a single function that contains complicated if/then logic. Here’s a quick first version attempting to capture the generalizations in (1)-(2)." }, { "code": null, "e": 15404, "s": 14957, "text": "Coming up with counterexamples to your initial generalizations is essential because they will challenge your basic assumptions about the linguistic phenomenon under consideration (here, question formation) and force you to identify a common thread between the different examples to express their behavior and characteristics in a unified, generalized way. Ultimately, that will help help you write simpler but more robust and comprehensive rules." }, { "code": null, "e": 15483, "s": 15404, "text": "The two generalizations given above are reproduced here to save you scrolling:" }, { "code": null, "e": 15834, "s": 15483, "text": "(1) Wh-questions (aka content questions): start with an interrogative word (a “wh-phrase”) like who, what, where, and how, and call for specific information.(2) Polar questions (aka yes or no questions): can be answered in the affirmative or the negative (with a yes or a no response), and begin with an auxiliary (did, do) or modal (will, can) verb." }, { "code": null, "e": 15905, "s": 15834, "text": "Here’s the first pair of counterexamples to the generalization in (1):" }, { "code": null, "e": 15986, "s": 15905, "text": "(3) What you say is unbelievable.(4) Who you're going to kill is not my problem." }, { "code": null, "e": 16279, "s": 15986, "text": "We see that (1) is not borne out by these sentences because despite beginning with a wh-word, they are not wh-questions! They are what linguists call wh-clefts, or pseudoclefts. Pseudoclefts are often described as giving emphasis, or “focus”, to part of the sentence and have the form in (5):" }, { "code": null, "e": 16326, "s": 16279, "text": "(5) free relative + \"be\" + focused constituent" }, { "code": null, "e": 16638, "s": 16326, "text": "A free relative is a wh-relative clause that (apparently) lacks a head noun (so “what you say” instead of “the thing you say”). This part of the pseudocleft introduces a topic (what the sentence is about) and is linked to a focused constituent which introduces new information (“unbelievable”) by the verb “be”." }, { "code": null, "e": 16687, "s": 16638, "text": "Here are some additional counterexamples to (1):" }, { "code": null, "e": 16772, "s": 16687, "text": "(5) In which article did they talk about spaCy?(6) To whom did you read the article?" }, { "code": null, "e": 17369, "s": 16772, "text": "These sentences fail to bear out (1) for a different reason: While they don’t start with a wh-phrase as the generalization says, they still are wh-questions in that they can be answered with specific information (e.g., an answer to (6) can be “I read the article to my sister.”). These sentences are so-called pied-piped constructions and are characterized by a wh-word appearing along with a preposition, as though it has “dragged” the other to the front of the sentence. (6) in particular can be contrasted with another sentence that “strands” a preposition: “Who did you read the article to?”." }, { "code": null, "e": 17467, "s": 17369, "text": "Finally, here are two counterexamples to the generalization about polar questions, stated in (2):" }, { "code": null, "e": 17535, "s": 17467, "text": "(7) Is it going to rain tonight?(8) Were you sad about her leaving?" }, { "code": null, "e": 17975, "s": 17535, "text": "These sentences show that in addition to auxiliary and modal verbs, the copula (“be”) as a main verb (vs. an auxiliary) should be included in the category of verbs that can appear at the beginning of polar questions. Stated more simply, a verb and a subject undergo inversion in polar questions when the verb is an auxiliary, a modal, or a form of “be” that serves as the main verb. This brings us to the following revised generalizations:" }, { "code": null, "e": 18406, "s": 17975, "text": "(1') Wh-questions (aka content questions): contain an interrogative word (a “wh-phrase”) like who, what, where, and how, and call for more specific information.(2') Polar questions (aka yes or no questions): can be answered in the affirmative or the negative (with a yes or a no response), and display subject-verb inversion where the verb must be either an auxiliary (did, do), a modal (will, can), or a form of the main verb be." }, { "code": null, "e": 18908, "s": 18406, "text": "I think this step demonstrates quite palpably that linguistic knowledge is indispensable to writing sophisticated feature-extracting rules. Knowing that English employs various strategies to signal interrogative sentences such as subject-verb inversion and wh-movement, as well as recognizing (and having names for) interesting linguistic phenomena, like pied-piping and clefting, can help you formulate generalizations that can in turn help you write comprehensive rules that are not overly specific." }, { "code": null, "e": 19257, "s": 18908, "text": "We can now modify the earlier versions of the functions, is_wh_question_v1 and is_polar_question_v1, to conform to the new generalizations (1') and (2'). This part will require some time and practice before we can feel very confident and comfortable, so be patient! Below I’ll highlight a few core things that characterize each of the v2 functions:" }, { "code": null, "e": 19279, "s": 19257, "text": "In is_wh_question_v2:" }, { "code": null, "e": 19411, "s": 19279, "text": "Referring to spaCy tags (e.g., \"WDT\", \"WP\", etc.) makes your rules more general than referring to the individual wh-words (line 3)." }, { "code": null, "e": 19563, "s": 19411, "text": "Pied-piping can be captured by a prep dependency relation between the wh-word and its head (the syntactic parent, or “governor” of the token) (line 8)." }, { "code": null, "e": 19686, "s": 19563, "text": "Pseudoclefts are excluded by returning False if the wh-word stands in a csubj or advcl relation to its head (lines 11–13)." }, { "code": null, "e": 19750, "s": 19686, "text": "In is_polar_question_v2, we need to account for two situations:" }, { "code": null, "e": 20049, "s": 19750, "text": "The question occurs in a non-copular construction in which “is” (or another form of “be”, like “were”) functions as an auxiliary, e.g., “Is she using spaCy?” (the main verb here is “using”.)The question occurs in a copular construction in which “is” functions as the main verb, “Is the mouse dead?”" }, { "code": null, "e": 20240, "s": 20049, "text": "The question occurs in a non-copular construction in which “is” (or another form of “be”, like “were”) functions as an auxiliary, e.g., “Is she using spaCy?” (the main verb here is “using”.)" }, { "code": null, "e": 20349, "s": 20240, "text": "The question occurs in a copular construction in which “is” functions as the main verb, “Is the mouse dead?”" }, { "code": null, "e": 20556, "s": 20349, "text": "Type 1 is captured in lines 14–16, and the inversion of the subject is with respect to the auxiliary. (The same lines of code can also account for subject-modal inversion, like “Can you read the article?”)." }, { "code": null, "e": 20718, "s": 20556, "text": "Type II is captured in lines 20–22, and the inversion of the subject is with respect to the root, i.e., the sole token whose dependency tag is \"ROOT\" in the doc." }, { "code": null, "e": 20804, "s": 20718, "text": "The mutual exclusivity of polar questions and wh-questions is captured in lines 9–10." }, { "code": null, "e": 20963, "s": 20804, "text": "Finally, to put all of the above together, we can write a test function that takes a list of example sentences and prints the question type for each sentence." }, { "code": null, "e": 21032, "s": 20963, "text": "When I run get_question_type(sentences), I get the following output:" }, { "code": null, "e": 21673, "s": 21032, "text": "In [352]: get_question_type(sentences)Is that for real? -- polarCan you stop? -- polarDo you love John? -- polarAre you sad? -- polarWas she singing? -- polarWon't you come over for dinner? -- polarWould you help me? -- polarWho do you love? -- whWhose child is that. -- whHow do you know him? -- whTo whom did she read the book? -- whI'm hungry. -- not a questionSpacy is so fun! -- not a questionTell me what you mean. -- not a questionWould love to help you. -- not a questionDon't be sad. -- not a questionWhatever you want. -- wh # false positive What you say is impossible. -- not a questionWhere you go, I will go. -- not a question" }, { "code": null, "e": 22094, "s": 21673, "text": "Everything is correct except for the third to last sentence, “Whatever you want.”. With the v2 functions, we have achieved an accuracy of 18/19 = 94.7%. Not bad! Note that these rules are truly sensitive to the underlying syntactic structure of each sentence and not to some superficial properties like the presence of a question mark (as illustrated by the correct classification of the example “Whose child is that.”)." }, { "code": null, "e": 22116, "s": 22094, "text": "And for good measure:" }, { "code": null, "e": 22453, "s": 22116, "text": "from sklearn.metrics import classification_reportcr = classification_report(true_values, rules_predictions)print(cr) precision recall f1-score supportnot a question 1.00 0.88 0.93 8 polar 1.00 1.00 1.00 7 wh 0.80 1.00 0.89 4" }, { "code": null, "e": 23013, "s": 22453, "text": "As a final step, you will want to fine-tune your rules by addressing any false positives to increase precision (e.g., “Whatever you want.” was incorrectly classified as a wh-question) and testing with more examples (and more complex examples) to increase recall. When you are satisfied, apply the rules to new data and use the results at any stage of your workflow that you deem appropriate. For example, you may choose to incorporate them as features during feature engineering or use them as early as the data pipeline to generate noisy data for annotation." } ]
SQL Tryit Editor v1.6
SELECT * FROM Customers WHERE City LIKE 'ber%'; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 24, "s": 0, "text": "SELECT * FROM Customers" }, { "code": null, "e": 48, "s": 24, "text": "WHERE City LIKE 'ber%';" }, { "code": null, "e": 50, "s": 48, "text": "​" }, { "code": null, "e": 113, "s": 50, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 173, "s": 113, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 241, "s": 173, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 279, "s": 241, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 364, "s": 279, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 538, "s": 364, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 589, "s": 538, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 657, "s": 589, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 828, "s": 657, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 928, "s": 828, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 988, "s": 928, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Basic AI Algorithms. Search Algorithms for Traveling... | by Mengsay Loem | Towards Data Science
To solve a problem with a computer, it is necessary to represent the problem in numerical or symbolic form and offer a specific procedure using a programming language. However, working with problem-solving in the artificial intelligence (AI) field, it is difficult to specify a formulation of a problem from the beginning. Therefore, the flexibility of choosing a solution procedure during the observation of state changes is highly required. Some problems can be represented by a graph or tree structure where each node represents a state of the problem. This kind of problem formulation method is called State-space representation. In a state-space representation method, each state of the problem is represented by a node of a graph or tree structure. In this case, the problem is translated as a search problem to determine the goal under specific operators and restrains. In this post, I will introduce Traveling Salesman Problem (TSP) as an example. Representation a problem with the state-space representation needs:(1). A set of states of the problem(2). A set of operators to operate between states of the problem(3). Initial state and final state(goal) Consider the following situation. You are given a list of n cities with the distance between any two cities. Now, you have to start with your office and to visit all the cities only once each and return to your office. What is the shortest path can you take? This problem is called the Traveling Salesman Problem (TSP). To make the problem simple, we consider 3-city-problem. Let’s call the office ( A )and the 3 cities ( B ) ( C ) ( D ) respectively. We initialize the problem state by {A} means the salesman departed from his office. As an operator, when he visited city-B, the problem state is updated to {A, B}, where the order of elements in { } is considered. When the salesman visited all the cities, {A, B, C, D} in this case, the departed point A is automatically added to the state which means {A, B, C, D, A}. Therefore, the initial state of this TSP is {A} and the final state(goal) is {A, X1, X2, X3, A} where traveled distance is minimized. Taking each state as a node of a tree structure, we can represent this TSP as the following tree search problem. The depth-first search algorithm starts at the root node and explores as deep as possible along each branch before taking backtracking. In our TSP, when a state node with all city labels is visited, its total distance is memorized. This information will later be used to define the shortest path. Let VISIT be a stack to save visited nodes, PATH be a set to save distances from the root node to the goal. The depth-first algorithm can be written as The depth-first search algorithm starts at the root node and explores all of the nodes at the present depth level before moving on to the nodes at the next depth level. In our TSP, when a state node with all city labels is visited, its total distance is memorized. This information will later be used to define the shortest path. Let VISIT be a queue to save visited nodes, PATH be a set to save distances from the root node to the goal. The breadth-first algorithm can be written as In Brute-force search, all nodes are visited and the information from each node (distance from a node to a node) is not considered. This leads to a large amount of time and memory consumption. To solve this problem, a heuristic search is a solution. The information of each state node is used to consider visiting a node or not. This information is represented by a heuristic function which commonly set up by user’s experiences. For example, we can define the heuristic function by the distance from the root node to the present visit node, or the distance from the present visit node to the goal node. In the Best-first search, we use the information of distance from the root node to decide which node to visit first. Let g(X) be the distance from the root node to node-X. Therefore, the distance from the root node to node-Y by visiting node-X is g(Y)=g(X)+d(X, Y), where d(X, Y) is the distance between X and Y. Let VISIT be a list to save visited nodes. The best-first algorithm can be written as In the A algorithm search, we use the information of distance from the present visit node to the goal as a heuristic function, h(X). Let g(X) be the distance from the root node to node-X. In this case, we consider the priority of node visit order by f(X)=g(X)+h(X). In real-world problems, it is impossible to obtain the exact value of h(X). In that case, an estimation value of h(X), h’(X), is used. However, setting h’(X) takes risks in falling into a local optimal answer. To prevent this problem, choosing h’(X) which h’(X)≤h(X) for all X is recommended. In this case, it is known as A*-algorithm and it can be shown that the obtained answer is the global optimal answer. In our experiment described in the following part, we are setting h’(X) as the sum of the minimum distance of all possible routes from each city which is not presented in the current visit node label, and the present city. For example, if the present node is {A, D}, then city-B and C is not present in the label. Therefore, h’(D)=min(all possible route distance from C)+min(all possible route distance from B)+min(all possible route distance from D). Let VISIT be a list to save visited nodes. The A-algorithm can be written as We simulate the TSP with each introduced algorithm and focus on effectiveness as a search problem. Here, the effectiveness of a search problem is evaluated by the number of nodes visited to reach the answer and theeffective branch number comparing to the tree’s depth level. The effective branch number b* of a problem where N nodes have been visited and the answer is a d depth-level of the tree, is calculated by N+1 = 1 + b* + (b*)2+(b*)3+...+(b*)^d . An algorithm with a smaller b* is a more effective algorithm. In this experiment, we use Newton’s method to solve this equation to obtain the approximate value of b*. Discussion on the number of visited nodes Discussion on the effective branch number # Randomly generate problemimport randommax_city_number = 8Gs = []for NN in range(2,max_city_number):Gs.append([[random.randint(1,10) for e in range(NN+1)] for e in range(NN+1)])# Problem state representation: Tree structureclass node(object):def __init__(self,number=None):self.pre = Noneself.no = numberself.label = []self.child = []self.cost = Nonedef add_child(self,number):tmp_node = node(number=number)tmp_node.pre = selftmp_node.label=[i for i in self.label]tmp_node.label.append(number)tmp_node.cost= get_bound(tmp_node.label)self.child.append(tmp_node)# Evaluate Function for A Algorithmdef get_bound(label):f = 0for i in range(0,len(label)-1):f = f+graph[label[i]-1][label[i+1]-1]remain = city.difference(set(label))remain = list(remain)remain.append(label[-1])for i in remain:f = f+min_bound[i-1]if len(remain)==2:f=0label.append(remain[0])label.append(1)for i in range(0,len(label)-1):f = f+graph[label[i]-1][label[i+1]-1]return f# Evaluate Function for Best-first Algorithmdef get_bound(label):f = 0remain = city.difference(set(label))remain = list(remain)remain.append(label[-1])for i in remain:f = f+min_bound[i-1]if len(remain)==2:f=0label.append(remain[0])label.append(1)for i in range(0,len(label)-1):f = f+graph[label[i]-1][label[i+1]-1]return f# Evaluate Function for Depth-first/Breadth-first Algorithmdef get_bound(label,n_city):f = 0for i in range(0,len(label)-1):f = f+graph[label[i]-1][label[i+1]-1]if len(label)==len(graph):f = f+graph[label[-1]-1][0]return f# Effective Branch Number calculation (Newton's Method)def f(N,d,x):return (x**(d+1) - (N+1)*x + N)**2def df(N,d,x):return 2*f(N,d,x)*((d+1)*x**d-(N+1))def ddf(N,d,x):return 2*df(N,d,x)*((d+1)*x**d-(N+1))+2*f(N,d,x)*((d+1)*d*x**(d-1))def solve(N,d):x = 1.9delta = 1.0count = 0while abs(delta)>0.000001 and count<10000:delta = df(N,d,x)/(ddf(N,d,x)+0.00001)x = x - deltacount = count + 1return x# EXPERIMENT1/2: # Search for GOAL (for A algorithm/Best-first Algorithm)tree = node(number=1)tree.label.append(1)tree.cost=0for i in range(len(Gs)):print("----------i=%d------------"%i)graph = Gs[i]NN = len(graph)for idx in range(NN):graph[idx][idx] = float('inf')city = range(1,len(graph)+1)city = set(city)min_bound = [min(graph[i]) for i in range(len(graph))]tree = node(number=1)tree.label.append(1)tree.cost=0visit=[]visit.append(tree)count = 0fcnt = 0ans = 0while len(visit)>0:N = visit[0]if len(N.label)==(len(city)-2):fcnt = fcnt+1del(visit[0])count = count+1child_list = set(city).difference(set(N.label))if len(child_list)==0:ans = 1breakfor c in child_list:N.add_child(number=c)tmp = N.childfor i in tmp:visit.append(i)visit = sorted(visit,key= lambda x:x.cost)if ans==1:print("RESULT:",N.label,N.cost)b = solve(count,NN-2)print("d=%d ,N= %d , b*=%f"%(NN-2,count,b))print("ROUTEs: %d"%(fcnt))resultsA.append((NN-2,count,b))else:print("FAILED")# EXPERIMENT3: # Search for GOAL (for Depth-first algorithm)tree = node(number=1)tree.label.append(1)tree.cost=0for i in range(len(Gs)):print("----------i=%d------------"%i)graph = Gs[i]NN = len(graph)for idx in range(NN):graph[idx][idx] = float('inf')city = range(1,len(graph)+1)city = set(city)tree = node(number=1,n_city=len(city))tree.label.append(1)tree.cost=0visit=[]paths = []count = 0fcnt = 0visit.append(tree)while len(visit)>0:if len(visit)==0:breakN = visit.pop()if len(N.label)==(len(graph)+1):paths.append(N)fcnt = fcnt+1paths=sorted(paths,key= lambda x:x.cost)count = count+1child_list = set(city).difference(set(N.label))if len(child_list)==0:continuefor c in child_list:N.add_child(number=c)tmp = N.childfor i in tmp:visit.append(i)print("RESULT:",paths[0].label,paths[0].cost)print("d=%d ,N= %d , b*=%f"%(NN-2,count,solve(count,NN-2)))print("ROUTEs:%d"%(fcnt))# EXPERIMENT4: # Search for GOAL (for Breadth-first algorithm)tree = node(number=1)tree.label.append(1)tree.cost=0for i in range(len(Gs)):print("----------i=%d------------"%i)graph = Gs[i]NN = len(graph)for idx in range(NN):graph[idx][idx] = float('inf')city = range(1,len(graph)+1)city = set(city)tree = node(number=1,n_city=len(city))tree.label.append(1)tree.cost=0visit=[]paths = []count = 0fcnt = 0visit.append(tree)while len(visit)>0:if len(visit)==0:breakN = visit[0]del(visit[0])if len(N.label)==(len(graph)+1):paths.append(N)fcnt = fcnt+1paths=sorted(paths,key= lambda x:x.cost)count = count+1child_list = set(city).difference(set(N.label))if len(child_list)==0:continuefor c in child_list:N.add_child(number=c)tmp = N.childfor i in tmp:visit.append(i)print("RESULT:",paths[0].label,paths[0].cost)print("d=%d ,N= %d , b*=%f"%(NN-2,count,solve(count,NN-2)))print("ROUTEs:%d"%(fcnt))
[ { "code": null, "e": 805, "s": 171, "text": "To solve a problem with a computer, it is necessary to represent the problem in numerical or symbolic form and offer a specific procedure using a programming language. However, working with problem-solving in the artificial intelligence (AI) field, it is difficult to specify a formulation of a problem from the beginning. Therefore, the flexibility of choosing a solution procedure during the observation of state changes is highly required. Some problems can be represented by a graph or tree structure where each node represents a state of the problem. This kind of problem formulation method is called State-space representation." }, { "code": null, "e": 1127, "s": 805, "text": "In a state-space representation method, each state of the problem is represented by a node of a graph or tree structure. In this case, the problem is translated as a search problem to determine the goal under specific operators and restrains. In this post, I will introduce Traveling Salesman Problem (TSP) as an example." }, { "code": null, "e": 1334, "s": 1127, "text": "Representation a problem with the state-space representation needs:(1). A set of states of the problem(2). A set of operators to operate between states of the problem(3). Initial state and final state(goal)" }, { "code": null, "e": 1654, "s": 1334, "text": "Consider the following situation. You are given a list of n cities with the distance between any two cities. Now, you have to start with your office and to visit all the cities only once each and return to your office. What is the shortest path can you take? This problem is called the Traveling Salesman Problem (TSP)." }, { "code": null, "e": 2289, "s": 1654, "text": "To make the problem simple, we consider 3-city-problem. Let’s call the office ( A )and the 3 cities ( B ) ( C ) ( D ) respectively. We initialize the problem state by {A} means the salesman departed from his office. As an operator, when he visited city-B, the problem state is updated to {A, B}, where the order of elements in { } is considered. When the salesman visited all the cities, {A, B, C, D} in this case, the departed point A is automatically added to the state which means {A, B, C, D, A}. Therefore, the initial state of this TSP is {A} and the final state(goal) is {A, X1, X2, X3, A} where traveled distance is minimized." }, { "code": null, "e": 2402, "s": 2289, "text": "Taking each state as a node of a tree structure, we can represent this TSP as the following tree search problem." }, { "code": null, "e": 2699, "s": 2402, "text": "The depth-first search algorithm starts at the root node and explores as deep as possible along each branch before taking backtracking. In our TSP, when a state node with all city labels is visited, its total distance is memorized. This information will later be used to define the shortest path." }, { "code": null, "e": 2851, "s": 2699, "text": "Let VISIT be a stack to save visited nodes, PATH be a set to save distances from the root node to the goal. The depth-first algorithm can be written as" }, { "code": null, "e": 3181, "s": 2851, "text": "The depth-first search algorithm starts at the root node and explores all of the nodes at the present depth level before moving on to the nodes at the next depth level. In our TSP, when a state node with all city labels is visited, its total distance is memorized. This information will later be used to define the shortest path." }, { "code": null, "e": 3335, "s": 3181, "text": "Let VISIT be a queue to save visited nodes, PATH be a set to save distances from the root node to the goal. The breadth-first algorithm can be written as" }, { "code": null, "e": 3939, "s": 3335, "text": "In Brute-force search, all nodes are visited and the information from each node (distance from a node to a node) is not considered. This leads to a large amount of time and memory consumption. To solve this problem, a heuristic search is a solution. The information of each state node is used to consider visiting a node or not. This information is represented by a heuristic function which commonly set up by user’s experiences. For example, we can define the heuristic function by the distance from the root node to the present visit node, or the distance from the present visit node to the goal node." }, { "code": null, "e": 4252, "s": 3939, "text": "In the Best-first search, we use the information of distance from the root node to decide which node to visit first. Let g(X) be the distance from the root node to node-X. Therefore, the distance from the root node to node-Y by visiting node-X is g(Y)=g(X)+d(X, Y), where d(X, Y) is the distance between X and Y." }, { "code": null, "e": 4338, "s": 4252, "text": "Let VISIT be a list to save visited nodes. The best-first algorithm can be written as" }, { "code": null, "e": 4604, "s": 4338, "text": "In the A algorithm search, we use the information of distance from the present visit node to the goal as a heuristic function, h(X). Let g(X) be the distance from the root node to node-X. In this case, we consider the priority of node visit order by f(X)=g(X)+h(X)." }, { "code": null, "e": 5014, "s": 4604, "text": "In real-world problems, it is impossible to obtain the exact value of h(X). In that case, an estimation value of h(X), h’(X), is used. However, setting h’(X) takes risks in falling into a local optimal answer. To prevent this problem, choosing h’(X) which h’(X)≤h(X) for all X is recommended. In this case, it is known as A*-algorithm and it can be shown that the obtained answer is the global optimal answer." }, { "code": null, "e": 5466, "s": 5014, "text": "In our experiment described in the following part, we are setting h’(X) as the sum of the minimum distance of all possible routes from each city which is not presented in the current visit node label, and the present city. For example, if the present node is {A, D}, then city-B and C is not present in the label. Therefore, h’(D)=min(all possible route distance from C)+min(all possible route distance from B)+min(all possible route distance from D)." }, { "code": null, "e": 5543, "s": 5466, "text": "Let VISIT be a list to save visited nodes. The A-algorithm can be written as" }, { "code": null, "e": 6165, "s": 5543, "text": "We simulate the TSP with each introduced algorithm and focus on effectiveness as a search problem. Here, the effectiveness of a search problem is evaluated by the number of nodes visited to reach the answer and theeffective branch number comparing to the tree’s depth level. The effective branch number b* of a problem where N nodes have been visited and the answer is a d depth-level of the tree, is calculated by N+1 = 1 + b* + (b*)2+(b*)3+...+(b*)^d . An algorithm with a smaller b* is a more effective algorithm. In this experiment, we use Newton’s method to solve this equation to obtain the approximate value of b*." }, { "code": null, "e": 6207, "s": 6165, "text": "Discussion on the number of visited nodes" }, { "code": null, "e": 6249, "s": 6207, "text": "Discussion on the effective branch number" } ]
Python - Merge Pandas DataFrame with Right Outer Join
To merge Pandas DataFrame, use the merge() function. The right outer join is implemented on both the DataFrames by setting under the “how” parameter of the merge() function i.e. − how = “right” At first, let us import the pandas library with an alias − import pandas as pd Create two dataframes to be merged − # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] } ) # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000] } ) Merge DataFrames with common column Car and "right" in "how" parameter implements Right Outer Join − mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="right") Following is the code − import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] } ) print"DataFrame1 ...\n",dataFrame1 # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000] } ) print"\nDataFrame2 ...\n",dataFrame2 # merge DataFrames with common column Car and "right" in "how" parameter implements Right Outer Join mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="right") print"\nMerged dataframe with right outer join...\n", mergedRes This will produce the following output − DataFrame1 ... Car Units 0 BMW 100 1 Lexus 150 2 Audi 110 3 Mustang 80 4 Bentley 110 5 Jaguar 90 DataFrame2 ... Car Reg_Price 0 BMW 7000 1 Lexus 1500 2 Tesla 5000 3 Mustang 8000 4 Mercedes 9000 5 Jaguar 6000 Merged dataframe with right outer join... Car Units Reg_Price 0 BMW 100.0 7000 1 Lexus 150.0 1500 2 Mustang 80.0 8000 3 Jaguar 90.0 6000 4 Tesla NaN 5000 5 Mercedes NaN 9000
[ { "code": null, "e": 1242, "s": 1062, "text": "To merge Pandas DataFrame, use the merge() function. The right outer join is implemented on both the DataFrames by setting under the “how” parameter of the merge() function i.e. −" }, { "code": null, "e": 1256, "s": 1242, "text": "how = “right”" }, { "code": null, "e": 1315, "s": 1256, "text": "At first, let us import the pandas library with an alias −" }, { "code": null, "e": 1336, "s": 1315, "text": "import pandas as pd\n" }, { "code": null, "e": 1373, "s": 1336, "text": "Create two dataframes to be merged −" }, { "code": null, "e": 1722, "s": 1373, "text": "# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000]\n }\n)" }, { "code": null, "e": 1823, "s": 1722, "text": "Merge DataFrames with common column Car and \"right\" in \"how\" parameter implements Right Outer Join −" }, { "code": null, "e": 1894, "s": 1823, "text": "mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how =\"right\")\n" }, { "code": null, "e": 1918, "s": 1894, "text": "Following is the code −" }, { "code": null, "e": 2599, "s": 1918, "text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\nprint\"DataFrame1 ...\\n\",dataFrame1\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000]\n\n }\n)\n\nprint\"\\nDataFrame2 ...\\n\",dataFrame2\n\n# merge DataFrames with common column Car and \"right\" in \"how\" parameter implements Right Outer Join\nmergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how =\"right\")\nprint\"\\nMerged dataframe with right outer join...\\n\", mergedRes" }, { "code": null, "e": 2640, "s": 2599, "text": "This will produce the following output −" }, { "code": null, "e": 3239, "s": 2640, "text": "DataFrame1 ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Mustang 80\n4 Bentley 110\n5 Jaguar 90\n\nDataFrame2 ...\n Car Reg_Price\n0 BMW 7000\n1 Lexus 1500\n2 Tesla 5000\n3 Mustang 8000\n4 Mercedes 9000\n5 Jaguar 6000\n\nMerged dataframe with right outer join...\n Car Units Reg_Price\n0 BMW 100.0 7000\n1 Lexus 150.0 1500\n2 Mustang 80.0 8000\n3 Jaguar 90.0 6000\n4 Tesla NaN 5000\n5 Mercedes NaN 9000" } ]
AWT FileDialog Class
FileDialog control represents a dialog window from which the user can select a file. Following is the declaration for java.awt.FileDialog class: public class FileDialog extends Dialog Following are the fields for java.awt.Image class: static int LOAD -- This constant value indicates that the purpose of the file dialog window is to locate a file from which to read. static int LOAD -- This constant value indicates that the purpose of the file dialog window is to locate a file from which to read. static int SAVE -- This constant value indicates that the purpose of the file dialog window is to locate a file to which to write. static int SAVE -- This constant value indicates that the purpose of the file dialog window is to locate a file to which to write. FileDialog(Dialog parent) Creates a file dialog for loading a file. FileDialog(Dialog parent, String title) Creates a file dialog window with the specified title for loading a file. FileDialog(Dialog parent, String title, int mode) Creates a file dialog window with the specified title for loading or saving a file. FileDialog(Frame parent) Creates a file dialog for loading a file. FileDialog(Frame parent, String title) Creates a file dialog window with the specified title for loading a file. FileDialog(Frame parent, String title, int mode) Creates a file dialog window with the specified title for loading or saving a file. void addNotify() Creates the file dialog's peer. String getDirectory() Gets the directory of this file dialog. String getFile() Gets the selected file of this file dialog. FilenameFilter getFilenameFilter() Determines this file dialog's filename filter. int getMode() Indicates whether this file dialog box is for loading from a file or for saving to a file. protected String paramString() Returns a string representing the state of this FileDialog window. void setDirectory(String dir) Sets the directory of this file dialog window to be the specified directory. void setFile(String file) Sets the selected file for this file dialog window to be the specified file. void setFilenameFilter(FilenameFilter filter) Sets the filename filter for this file dialog window to the specified filter. void setMode(int mode) Sets the mode of the file dialog. This class inherits methods from the following classes: java.awt.Dialog java.awt.Dialog java.awt.Window java.awt.Window java.awt.Component java.awt.Component java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtControlDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtControlDemo(){ prepareGUI(); } public static void main(String[] args){ AwtControlDemo awtControlDemo = new AwtControlDemo(); awtControlDemo.showFileDialogDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showFileDialogDemo(){ headerLabel.setText("Control in action: FileDialog"); final FileDialog fileDialog = new FileDialog(mainFrame,"Select file"); Button showFileDialogButton = new Button("Open File"); showFileDialogButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fileDialog.setVisible(true); statusLabel.setText("File Selected :" + fileDialog.getDirectory() + fileDialog.getFile()); } }); controlPanel.add(showFileDialogButton); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtControlDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1832, "s": 1747, "text": "FileDialog control represents a dialog window from which the user can select a file." }, { "code": null, "e": 1892, "s": 1832, "text": "Following is the declaration for java.awt.FileDialog class:" }, { "code": null, "e": 1934, "s": 1892, "text": "public class FileDialog\n extends Dialog" }, { "code": null, "e": 1985, "s": 1934, "text": "Following are the fields for java.awt.Image class:" }, { "code": null, "e": 2118, "s": 1985, "text": "static int LOAD -- This constant value indicates that the purpose of the file dialog window is to locate a file from which to read." }, { "code": null, "e": 2251, "s": 2118, "text": "static int LOAD -- This constant value indicates that the purpose of the file dialog window is to locate a file from which to read." }, { "code": null, "e": 2383, "s": 2251, "text": "static int SAVE -- This constant value indicates that the purpose of the file dialog window is to locate a file to which to write." }, { "code": null, "e": 2515, "s": 2383, "text": "static int SAVE -- This constant value indicates that the purpose of the file dialog window is to locate a file to which to write." }, { "code": null, "e": 2542, "s": 2515, "text": "FileDialog(Dialog parent) " }, { "code": null, "e": 2584, "s": 2542, "text": "Creates a file dialog for loading a file." }, { "code": null, "e": 2624, "s": 2584, "text": "FileDialog(Dialog parent, String title)" }, { "code": null, "e": 2699, "s": 2624, "text": " Creates a file dialog window with the specified title for loading a file." }, { "code": null, "e": 2750, "s": 2699, "text": "FileDialog(Dialog parent, String title, int mode) " }, { "code": null, "e": 2834, "s": 2750, "text": "Creates a file dialog window with the specified title for loading or saving a file." }, { "code": null, "e": 2859, "s": 2834, "text": "FileDialog(Frame parent)" }, { "code": null, "e": 2902, "s": 2859, "text": " Creates a file dialog for loading a file." }, { "code": null, "e": 2942, "s": 2902, "text": "FileDialog(Frame parent, String title) " }, { "code": null, "e": 3016, "s": 2942, "text": "Creates a file dialog window with the specified title for loading a file." }, { "code": null, "e": 3066, "s": 3016, "text": "FileDialog(Frame parent, String title, int mode) " }, { "code": null, "e": 3150, "s": 3066, "text": "Creates a file dialog window with the specified title for loading or saving a file." }, { "code": null, "e": 3169, "s": 3150, "text": "void addNotify() " }, { "code": null, "e": 3201, "s": 3169, "text": "Creates the file dialog's peer." }, { "code": null, "e": 3223, "s": 3201, "text": "String\tgetDirectory()" }, { "code": null, "e": 3263, "s": 3223, "text": "Gets the directory of this file dialog." }, { "code": null, "e": 3282, "s": 3263, "text": "String\tgetFile() " }, { "code": null, "e": 3326, "s": 3282, "text": "Gets the selected file of this file dialog." }, { "code": null, "e": 3361, "s": 3326, "text": "FilenameFilter\tgetFilenameFilter()" }, { "code": null, "e": 3408, "s": 3361, "text": "Determines this file dialog's filename filter." }, { "code": null, "e": 3424, "s": 3408, "text": "int getMode() " }, { "code": null, "e": 3515, "s": 3424, "text": "Indicates whether this file dialog box is for loading from a file or for saving to a file." }, { "code": null, "e": 3548, "s": 3515, "text": "protected String paramString() " }, { "code": null, "e": 3615, "s": 3548, "text": "Returns a string representing the state of this FileDialog window." }, { "code": null, "e": 3647, "s": 3615, "text": "void setDirectory(String dir) " }, { "code": null, "e": 3724, "s": 3647, "text": "Sets the directory of this file dialog window to be the specified directory." }, { "code": null, "e": 3752, "s": 3724, "text": "void setFile(String file) " }, { "code": null, "e": 3829, "s": 3752, "text": "Sets the selected file for this file dialog window to be the specified file." }, { "code": null, "e": 3877, "s": 3829, "text": "void setFilenameFilter(FilenameFilter filter) " }, { "code": null, "e": 3955, "s": 3877, "text": "Sets the filename filter for this file dialog window to the specified filter." }, { "code": null, "e": 3978, "s": 3955, "text": "void setMode(int mode)" }, { "code": null, "e": 4012, "s": 3978, "text": "Sets the mode of the file dialog." }, { "code": null, "e": 4068, "s": 4012, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 4084, "s": 4068, "text": "java.awt.Dialog" }, { "code": null, "e": 4100, "s": 4084, "text": "java.awt.Dialog" }, { "code": null, "e": 4116, "s": 4100, "text": "java.awt.Window" }, { "code": null, "e": 4132, "s": 4116, "text": "java.awt.Window" }, { "code": null, "e": 4151, "s": 4132, "text": "java.awt.Component" }, { "code": null, "e": 4170, "s": 4151, "text": "java.awt.Component" }, { "code": null, "e": 4187, "s": 4170, "text": "java.lang.Object" }, { "code": null, "e": 4204, "s": 4187, "text": "java.lang.Object" }, { "code": null, "e": 4318, "s": 4204, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 6173, "s": 4318, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtControlDemo {\n\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtControlDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtControlDemo awtControlDemo = new AwtControlDemo();\n awtControlDemo.showFileDialogDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showFileDialogDemo(){\n headerLabel.setText(\"Control in action: FileDialog\"); \n\n final FileDialog fileDialog = new FileDialog(mainFrame,\"Select file\");\n Button showFileDialogButton = new Button(\"Open File\");\n showFileDialogButton.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n fileDialog.setVisible(true);\n statusLabel.setText(\"File Selected :\" \n + fileDialog.getDirectory() + fileDialog.getFile());\n }\n });\n\n controlPanel.add(showFileDialogButton);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 6264, "s": 6173, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 6320, "s": 6264, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtControlDemo.java" }, { "code": null, "e": 6417, "s": 6320, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 6467, "s": 6417, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtControlDemo" }, { "code": null, "e": 6495, "s": 6467, "text": "Verify the following output" }, { "code": null, "e": 6528, "s": 6495, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 6536, "s": 6528, "text": " EduOLC" }, { "code": null, "e": 6543, "s": 6536, "text": " Print" }, { "code": null, "e": 6554, "s": 6543, "text": " Add Notes" } ]
Finding average marks of students for different subjects and display only the highest average marks in MySQL
For this, you can use subquery. Let us first create a table − mysql> create table DemoTable ( StudentName varchar(40), StudentMarks int ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Adam',56); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris',78); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Adam',89); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Robert',98); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Chris',65); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Robert',34); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Adam | 56 | | Chris | 78 | | Adam | 89 | | Robert | 98 | | Chris | 65 | | Robert | 34 | +-------------+--------------+ 6 rows in set (0.00 sec) Following is the query to find average marks of students and display only the highest average marks − mysql> select max(avSal.StudentMarks) from (select avg(StudentMarks) as `StudentMarks` from DemoTable group by StudentName) as avSal; This will produce the following output − +-------------------------+ | max(avSal.StudentMarks) | +-------------------------+ | 72.5000 | +-------------------------+ 1 row in set (0.09 sec)
[ { "code": null, "e": 1124, "s": 1062, "text": "For this, you can use subquery. Let us first create a table −" }, { "code": null, "e": 1244, "s": 1124, "text": "mysql> create table DemoTable\n(\n StudentName varchar(40),\n StudentMarks int\n);\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1300, "s": 1244, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1810, "s": 1300, "text": "mysql> insert into DemoTable values('Adam',56);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Chris',78);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('Adam',89);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('Robert',98);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('Chris',65);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('Robert',34);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1870, "s": 1810, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1901, "s": 1870, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1942, "s": 1901, "text": "This will produce the following output −" }, { "code": null, "e": 2277, "s": 1942, "text": "+-------------+--------------+\n| StudentName | StudentMarks |\n+-------------+--------------+\n| Adam | 56 |\n| Chris | 78 |\n| Adam | 89 |\n| Robert | 98 |\n| Chris | 65 |\n| Robert | 34 |\n+-------------+--------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2379, "s": 2277, "text": "Following is the query to find average marks of students and display only the highest average marks −" }, { "code": null, "e": 2513, "s": 2379, "text": "mysql> select max(avSal.StudentMarks)\nfrom (select avg(StudentMarks) as `StudentMarks` from DemoTable group by StudentName) as avSal;" }, { "code": null, "e": 2554, "s": 2513, "text": "This will produce the following output −" }, { "code": null, "e": 2718, "s": 2554, "text": "+-------------------------+\n| max(avSal.StudentMarks) |\n+-------------------------+\n| 72.5000 |\n+-------------------------+\n1 row in set (0.09 sec)" } ]
A Minimalist End-to-End Scrapy Tutorial (Part I) | by Harry Wang | Towards Data Science
Part I, Part II, Part III, Part IV, Part V Web scraping is an important skill for data scientists. I have developed a number of ad hoc web scraping projects using Python, BeautifulSoup, and Scrapy in the past few years and read a few books and tons of online tutorials along the way. However, I have not found a simple beginner level tutorial that is end-to-end in the sense that covers all basic steps and concepts in a typical Scrapy web scraping project (therefore Minimalist in the title) — that’s why I am writing this and hope the code repo can serve as a template to help jumpstart your web scraping projects. Many people ask: should I use BeautifulSoup or Scrapy? They are different things: BeautifulSoup is a library for parsing HTML and XML and Scrapy is a web scraping framework. You can use BeautifulSoup instead of Scrapy build-in selectors if you want but comparing BeautifulSoup to Scrapy is like comparing the Mac keyboard to the iMac or a better metaphor as stated in the official documentation “like comparing jinja2 to Django” if you know what they are :) — In short, you should learn Scrapy if you want to do serious and systematic web scraping. TL;DR, show me the code: github.com In this tutorial series, I am going to cover the following steps: (This tutorial) Start a Scrapy project from scratch and develop a simple spider. One important thing is the use of Scrapy Shell for analyzing pages and debugging, which is one of the main reasons you should use Scrapy over BeautifulSoup.(Part II) Introduce Item and ItemLoader and explain why you want to use them (although they make your code seem more complicated at first).(Part III) Store the data to the database using ORM (SQLAlchemy) via Pipelines and show how to set up the most common One-to-Many and Many-to-Many relationships.(Part IV) Deploy the project to Scrapinghub (you have to pay for service such as scheduled crawling jobs) or set up your own servers completely free of charge by using the great open source project ScrapydWeb and Heroku.(Part V) I created a separate repo (Scrapy + Selenium) to show how to crawl dynamic web pages (such as a page that loads additional content via scrolling) and how to use proxy networks (ProxyMesh) to avoid getting banned. (This tutorial) Start a Scrapy project from scratch and develop a simple spider. One important thing is the use of Scrapy Shell for analyzing pages and debugging, which is one of the main reasons you should use Scrapy over BeautifulSoup. (Part II) Introduce Item and ItemLoader and explain why you want to use them (although they make your code seem more complicated at first). (Part III) Store the data to the database using ORM (SQLAlchemy) via Pipelines and show how to set up the most common One-to-Many and Many-to-Many relationships. (Part IV) Deploy the project to Scrapinghub (you have to pay for service such as scheduled crawling jobs) or set up your own servers completely free of charge by using the great open source project ScrapydWeb and Heroku. (Part V) I created a separate repo (Scrapy + Selenium) to show how to crawl dynamic web pages (such as a page that loads additional content via scrolling) and how to use proxy networks (ProxyMesh) to avoid getting banned. Some prerequisites: Basic knowledge on Python (Python 3 for this tutorial), virtual environment, Homebrew, etc., see my other article for how to set up the environment: How to Setup Mac for Python Development Basic knowledge of Git and Github. I recommend the Pro Git book. Basic knowledge of database and ORM, e.g., Introduction to Structured Query Language (SQL). Let’s get started! First, create a new folder, setup Python 3 virtual environment inside the folder, and install Scrapy. To make this step easy, I created a starter repo, which you can fork and clone (see Python3 virtual environment documentation if needed): $ git clone https://github.com/yourusername/scrapy-tutorial-starter.git$ cd scrapy-tutorial-starter$ python3.6 -m venv venv$ source venv/bin/activate$ pip install -r requirements.txt Your folder should look like the following and I assume we always work in the virtual environment. Note that we only have one package in the requirements.txt so far. run scrapy startproject tutorial to create an empty scrapy project and your folder looks like: Two identical “tutorial” folders were created. We don’t need the first level “tutorial” folder — delete it and move the second level “tutorial” folder with its contents one-level up — I know this is confusing but that’s all you have to do with the folder structure. Now, your folder should look like: Don’t worry about the auto-generated files so far, we will come back to those files later. This tutorial is based on the official Scrapy tutorial. Therefore, the website we are going to crawl is http://quotes.toscrape.com, which is quite simple: there are pages of quotes with authors and tags: When you click the author, it goes to the author detail page with name, birthday, and bio. Now, create a new file named “quotes-spider.py” in the “spider” folder with the following content: You just created a spider named “quotes”, which sends a request to http://quotes.toscrape.com and gets the response from the server. However, the spider does not do anything so far when parsing the response and simply outputs a string to the console. Let’s run this spider: scrapy crawl quotes , you should see the output like: Next, let’s analyze the response, i.e., the HTML page at http://quotes.toscrape.com using Scrapy Shell by running: $ scrapy shell http://quotes.toscrape.com/...2019-08-21 20:10:40 [scrapy.core.engine] INFO: Spider opened2019-08-21 20:10:41 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quotes.toscrape.com/robots.txt> (referer: None)2019-08-21 20:10:41 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/> (referer: None)[s] Available Scrapy objects:[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)[s] crawler <scrapy.crawler.Crawler object at 0x105d01dd8>[s] item {}[s] request <GET http://quotes.toscrape.com/>[s] response <200 http://quotes.toscrape.com/>[s] settings <scrapy.settings.Settings object at 0x106ae34e0>[s] spider <DefaultSpider 'default' at 0x106f13780>[s] Useful shortcuts:[s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)[s] fetch(req) Fetch a scrapy.Request and update local objects[s] shelp() Shell help (print this help)[s] view(response) View response in a browser>>> You can select elements using either Xpath selector or CSS selector and Chrome DevTools is often used to analyze the page (we won’t cover the selector details, please read the documents to learn how to use them): For example, you can test the selector and see the results in Scrapy Shell — assume we want to get the quote block shown above: You can either use Xpath response.xpath(“//div[@class=’quote’]”).get() (.get() shows the first selected element, use .getall() to show all) or CSSresponse.css(“div .quote”).get() . I bolded the quote text, author, and tags we want to get from this quote block: >>> response.xpath("//div[@class='quote']").get()'<div class="quote" itemscope itemtype="http://schema.org/CreativeWork">\n <span class="text" itemprop="text">“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”</span>\n <span>by <small class="author" itemprop="author">Albert Einstein</small>\n <a href="/author/Albert-Einstein">(about)</a>\n </span>\n <div class="tags">\n Tags:\n <meta class="keywords" itemprop="keywords" content="change,deep-thoughts,thinking,world"> \n \n <a class="tag" href="/tag/change/page/1/">change</a>\n \n <a class="tag" href="/tag/deep-thoughts/page/1/">deep-thoughts</a>\n \n <a class="tag" href="/tag/thinking/page/1/">thinking</a>\n \n <a class="tag" href="/tag/world/page/1/">world</a>\n \n </div>\n </div>' We can proceed in the shell to get the data as follows: get all quote blocks into “quotes” use the first quote in “quotes”: quotes[0] try the css selectors >>> quotes = response.xpath("//div[@class='quote']")>>> quotes[0].css(".text::text").getall()['“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”']>>> quotes[0].css(".author::text").getall()['Albert Einstein']>>> quotes[0].css(".tag::text").getall()['change', 'deep-thoughts', 'thinking', 'world'] It seems that the selectors shown above get what we need. Note that I am mixing Xpath and CSS selectors for the demonstration purpose here — no need to use both in this tutorial. Now, let’s revise the spider file and use keyword yield to output the selected data to the console (note that each page has many quotes and we use a loop to go over all of them): import scrapyclass QuotesSpider(scrapy.Spider): name = "quotes"start_urls = ['http://quotes.toscrape.com']def parse(self, response): self.logger.info('hello this is my first spider') quotes = response.css('div.quote') for quote in quotes: yield { 'text': quote.css('.text::text').get(), 'author': quote.css('.author::text').get(), 'tags': quote.css('.tag::text').getall(), } Run the spider again: scrapy crawl quotes and you can see the extracted data in the log: You can save the data in a JSON file by running: scrapy crawl quotes -o quotes.json So far, we get all quote information from the first page, and our next task is to crawl all pages. You should notice a “Next” button at the bottom of the front page for page navigation — the logic is: click the Next button to go to the next page, get the quotes, click Next again till the last page without the Next button. Via Chrome DevTools, we can get the URL of the next page: Let’s test it out in Scrapy Shell by running scrapy shell http://quotes.toscrape.com/ again: $ scrapy shell http://quotes.toscrape.com/...>>> response.css('li.next a::attr(href)').get()'/page/2/' Now we can write the following code for the spider to go over all pages to get all quotes: next_page = response.urljoin(next_page) gets the full URL and yield scrapy.Request(next_page, callback=self.parse) sends a new request to get the next page and use a callback function to call the same parse function to get the quotes from the new page. Shortcuts can be used to further simplify the code above: see this section. Essentially, response.follow supports relative URLs (no need to call urljoin) and automatically uses the href attribute for <a> . So, the code can be shortened further: for a in response.css('li.next a'): yield response.follow(a, callback=self.parse) Now, run the spider again scrapy crawl quotes you should see quotes from all 10 pages have been extracted. Hang in there — we are almost done for this first part. The next task is to crawl the individual author's page. As shown above, when we process each quote, we can go to the individual author’s page by following the highlighted link — let’s use Scrapy Shell to get the link: $ scrapy shell http://quotes.toscrape.com/...>>> response.css('.author + a::attr(href)').get()'/author/Albert-Einstein' So, during the loop of extracting each quote, we issue another request to go to the corresponding author’s page and create another parse_author function to extract the author’s name, birthday, born location and bio and output to the console. The updated spider looks like the following: Run the spider again scrapy crawl quotes and double-check that everything you need to extract is output to the console correctly. Note that Scrapy is based on Twisted, a popular event-driven networking framework for Python and thus is asynchronous. This means that the individual author page may not be processed in sync with the corresponding quote, e.g., the order of the author page results may not match the quote order on the page. We will discuss how to link the quote with its corresponding author page in the later part. Congratulations, you have finished Part I of this tutorial. Learn more about Item and ItemLoader in Part II. Part I, Part II, Part III, Part IV, Part V
[ { "code": null, "e": 214, "s": 171, "text": "Part I, Part II, Part III, Part IV, Part V" }, { "code": null, "e": 788, "s": 214, "text": "Web scraping is an important skill for data scientists. I have developed a number of ad hoc web scraping projects using Python, BeautifulSoup, and Scrapy in the past few years and read a few books and tons of online tutorials along the way. However, I have not found a simple beginner level tutorial that is end-to-end in the sense that covers all basic steps and concepts in a typical Scrapy web scraping project (therefore Minimalist in the title) — that’s why I am writing this and hope the code repo can serve as a template to help jumpstart your web scraping projects." }, { "code": null, "e": 1337, "s": 788, "text": "Many people ask: should I use BeautifulSoup or Scrapy? They are different things: BeautifulSoup is a library for parsing HTML and XML and Scrapy is a web scraping framework. You can use BeautifulSoup instead of Scrapy build-in selectors if you want but comparing BeautifulSoup to Scrapy is like comparing the Mac keyboard to the iMac or a better metaphor as stated in the official documentation “like comparing jinja2 to Django” if you know what they are :) — In short, you should learn Scrapy if you want to do serious and systematic web scraping." }, { "code": null, "e": 1362, "s": 1337, "text": "TL;DR, show me the code:" }, { "code": null, "e": 1373, "s": 1362, "text": "github.com" }, { "code": null, "e": 1439, "s": 1373, "text": "In this tutorial series, I am going to cover the following steps:" }, { "code": null, "e": 2418, "s": 1439, "text": "(This tutorial) Start a Scrapy project from scratch and develop a simple spider. One important thing is the use of Scrapy Shell for analyzing pages and debugging, which is one of the main reasons you should use Scrapy over BeautifulSoup.(Part II) Introduce Item and ItemLoader and explain why you want to use them (although they make your code seem more complicated at first).(Part III) Store the data to the database using ORM (SQLAlchemy) via Pipelines and show how to set up the most common One-to-Many and Many-to-Many relationships.(Part IV) Deploy the project to Scrapinghub (you have to pay for service such as scheduled crawling jobs) or set up your own servers completely free of charge by using the great open source project ScrapydWeb and Heroku.(Part V) I created a separate repo (Scrapy + Selenium) to show how to crawl dynamic web pages (such as a page that loads additional content via scrolling) and how to use proxy networks (ProxyMesh) to avoid getting banned." }, { "code": null, "e": 2656, "s": 2418, "text": "(This tutorial) Start a Scrapy project from scratch and develop a simple spider. One important thing is the use of Scrapy Shell for analyzing pages and debugging, which is one of the main reasons you should use Scrapy over BeautifulSoup." }, { "code": null, "e": 2796, "s": 2656, "text": "(Part II) Introduce Item and ItemLoader and explain why you want to use them (although they make your code seem more complicated at first)." }, { "code": null, "e": 2958, "s": 2796, "text": "(Part III) Store the data to the database using ORM (SQLAlchemy) via Pipelines and show how to set up the most common One-to-Many and Many-to-Many relationships." }, { "code": null, "e": 3179, "s": 2958, "text": "(Part IV) Deploy the project to Scrapinghub (you have to pay for service such as scheduled crawling jobs) or set up your own servers completely free of charge by using the great open source project ScrapydWeb and Heroku." }, { "code": null, "e": 3401, "s": 3179, "text": "(Part V) I created a separate repo (Scrapy + Selenium) to show how to crawl dynamic web pages (such as a page that loads additional content via scrolling) and how to use proxy networks (ProxyMesh) to avoid getting banned." }, { "code": null, "e": 3421, "s": 3401, "text": "Some prerequisites:" }, { "code": null, "e": 3610, "s": 3421, "text": "Basic knowledge on Python (Python 3 for this tutorial), virtual environment, Homebrew, etc., see my other article for how to set up the environment: How to Setup Mac for Python Development" }, { "code": null, "e": 3675, "s": 3610, "text": "Basic knowledge of Git and Github. I recommend the Pro Git book." }, { "code": null, "e": 3767, "s": 3675, "text": "Basic knowledge of database and ORM, e.g., Introduction to Structured Query Language (SQL)." }, { "code": null, "e": 3786, "s": 3767, "text": "Let’s get started!" }, { "code": null, "e": 4026, "s": 3786, "text": "First, create a new folder, setup Python 3 virtual environment inside the folder, and install Scrapy. To make this step easy, I created a starter repo, which you can fork and clone (see Python3 virtual environment documentation if needed):" }, { "code": null, "e": 4209, "s": 4026, "text": "$ git clone https://github.com/yourusername/scrapy-tutorial-starter.git$ cd scrapy-tutorial-starter$ python3.6 -m venv venv$ source venv/bin/activate$ pip install -r requirements.txt" }, { "code": null, "e": 4375, "s": 4209, "text": "Your folder should look like the following and I assume we always work in the virtual environment. Note that we only have one package in the requirements.txt so far." }, { "code": null, "e": 4470, "s": 4375, "text": "run scrapy startproject tutorial to create an empty scrapy project and your folder looks like:" }, { "code": null, "e": 4771, "s": 4470, "text": "Two identical “tutorial” folders were created. We don’t need the first level “tutorial” folder — delete it and move the second level “tutorial” folder with its contents one-level up — I know this is confusing but that’s all you have to do with the folder structure. Now, your folder should look like:" }, { "code": null, "e": 5066, "s": 4771, "text": "Don’t worry about the auto-generated files so far, we will come back to those files later. This tutorial is based on the official Scrapy tutorial. Therefore, the website we are going to crawl is http://quotes.toscrape.com, which is quite simple: there are pages of quotes with authors and tags:" }, { "code": null, "e": 5157, "s": 5066, "text": "When you click the author, it goes to the author detail page with name, birthday, and bio." }, { "code": null, "e": 5256, "s": 5157, "text": "Now, create a new file named “quotes-spider.py” in the “spider” folder with the following content:" }, { "code": null, "e": 5584, "s": 5256, "text": "You just created a spider named “quotes”, which sends a request to http://quotes.toscrape.com and gets the response from the server. However, the spider does not do anything so far when parsing the response and simply outputs a string to the console. Let’s run this spider: scrapy crawl quotes , you should see the output like:" }, { "code": null, "e": 5699, "s": 5584, "text": "Next, let’s analyze the response, i.e., the HTML page at http://quotes.toscrape.com using Scrapy Shell by running:" }, { "code": null, "e": 6760, "s": 5699, "text": "$ scrapy shell http://quotes.toscrape.com/...2019-08-21 20:10:40 [scrapy.core.engine] INFO: Spider opened2019-08-21 20:10:41 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quotes.toscrape.com/robots.txt> (referer: None)2019-08-21 20:10:41 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/> (referer: None)[s] Available Scrapy objects:[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)[s] crawler <scrapy.crawler.Crawler object at 0x105d01dd8>[s] item {}[s] request <GET http://quotes.toscrape.com/>[s] response <200 http://quotes.toscrape.com/>[s] settings <scrapy.settings.Settings object at 0x106ae34e0>[s] spider <DefaultSpider 'default' at 0x106f13780>[s] Useful shortcuts:[s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)[s] fetch(req) Fetch a scrapy.Request and update local objects[s] shelp() Shell help (print this help)[s] view(response) View response in a browser>>>" }, { "code": null, "e": 6973, "s": 6760, "text": "You can select elements using either Xpath selector or CSS selector and Chrome DevTools is often used to analyze the page (we won’t cover the selector details, please read the documents to learn how to use them):" }, { "code": null, "e": 7101, "s": 6973, "text": "For example, you can test the selector and see the results in Scrapy Shell — assume we want to get the quote block shown above:" }, { "code": null, "e": 7362, "s": 7101, "text": "You can either use Xpath response.xpath(“//div[@class=’quote’]”).get() (.get() shows the first selected element, use .getall() to show all) or CSSresponse.css(“div .quote”).get() . I bolded the quote text, author, and tags we want to get from this quote block:" }, { "code": null, "e": 8335, "s": 7362, "text": ">>> response.xpath(\"//div[@class='quote']\").get()'<div class=\"quote\" itemscope itemtype=\"http://schema.org/CreativeWork\">\\n <span class=\"text\" itemprop=\"text\">“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”</span>\\n <span>by <small class=\"author\" itemprop=\"author\">Albert Einstein</small>\\n <a href=\"/author/Albert-Einstein\">(about)</a>\\n </span>\\n <div class=\"tags\">\\n Tags:\\n <meta class=\"keywords\" itemprop=\"keywords\" content=\"change,deep-thoughts,thinking,world\"> \\n \\n <a class=\"tag\" href=\"/tag/change/page/1/\">change</a>\\n \\n <a class=\"tag\" href=\"/tag/deep-thoughts/page/1/\">deep-thoughts</a>\\n \\n <a class=\"tag\" href=\"/tag/thinking/page/1/\">thinking</a>\\n \\n <a class=\"tag\" href=\"/tag/world/page/1/\">world</a>\\n \\n </div>\\n </div>'" }, { "code": null, "e": 8391, "s": 8335, "text": "We can proceed in the shell to get the data as follows:" }, { "code": null, "e": 8426, "s": 8391, "text": "get all quote blocks into “quotes”" }, { "code": null, "e": 8469, "s": 8426, "text": "use the first quote in “quotes”: quotes[0]" }, { "code": null, "e": 8491, "s": 8469, "text": "try the css selectors" }, { "code": null, "e": 8854, "s": 8491, "text": ">>> quotes = response.xpath(\"//div[@class='quote']\")>>> quotes[0].css(\".text::text\").getall()['“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”']>>> quotes[0].css(\".author::text\").getall()['Albert Einstein']>>> quotes[0].css(\".tag::text\").getall()['change', 'deep-thoughts', 'thinking', 'world']" }, { "code": null, "e": 9033, "s": 8854, "text": "It seems that the selectors shown above get what we need. Note that I am mixing Xpath and CSS selectors for the demonstration purpose here — no need to use both in this tutorial." }, { "code": null, "e": 9212, "s": 9033, "text": "Now, let’s revise the spider file and use keyword yield to output the selected data to the console (note that each page has many quotes and we use a loop to go over all of them):" }, { "code": null, "e": 9678, "s": 9212, "text": "import scrapyclass QuotesSpider(scrapy.Spider): name = \"quotes\"start_urls = ['http://quotes.toscrape.com']def parse(self, response): self.logger.info('hello this is my first spider') quotes = response.css('div.quote') for quote in quotes: yield { 'text': quote.css('.text::text').get(), 'author': quote.css('.author::text').get(), 'tags': quote.css('.tag::text').getall(), }" }, { "code": null, "e": 9767, "s": 9678, "text": "Run the spider again: scrapy crawl quotes and you can see the extracted data in the log:" }, { "code": null, "e": 9851, "s": 9767, "text": "You can save the data in a JSON file by running: scrapy crawl quotes -o quotes.json" }, { "code": null, "e": 10175, "s": 9851, "text": "So far, we get all quote information from the first page, and our next task is to crawl all pages. You should notice a “Next” button at the bottom of the front page for page navigation — the logic is: click the Next button to go to the next page, get the quotes, click Next again till the last page without the Next button." }, { "code": null, "e": 10233, "s": 10175, "text": "Via Chrome DevTools, we can get the URL of the next page:" }, { "code": null, "e": 10326, "s": 10233, "text": "Let’s test it out in Scrapy Shell by running scrapy shell http://quotes.toscrape.com/ again:" }, { "code": null, "e": 10429, "s": 10326, "text": "$ scrapy shell http://quotes.toscrape.com/...>>> response.css('li.next a::attr(href)').get()'/page/2/'" }, { "code": null, "e": 10520, "s": 10429, "text": "Now we can write the following code for the spider to go over all pages to get all quotes:" }, { "code": null, "e": 10773, "s": 10520, "text": "next_page = response.urljoin(next_page) gets the full URL and yield scrapy.Request(next_page, callback=self.parse) sends a new request to get the next page and use a callback function to call the same parse function to get the quotes from the new page." }, { "code": null, "e": 11018, "s": 10773, "text": "Shortcuts can be used to further simplify the code above: see this section. Essentially, response.follow supports relative URLs (no need to call urljoin) and automatically uses the href attribute for <a> . So, the code can be shortened further:" }, { "code": null, "e": 11111, "s": 11018, "text": "for a in response.css('li.next a'): yield response.follow(a, callback=self.parse)" }, { "code": null, "e": 11330, "s": 11111, "text": "Now, run the spider again scrapy crawl quotes you should see quotes from all 10 pages have been extracted. Hang in there — we are almost done for this first part. The next task is to crawl the individual author's page." }, { "code": null, "e": 11492, "s": 11330, "text": "As shown above, when we process each quote, we can go to the individual author’s page by following the highlighted link — let’s use Scrapy Shell to get the link:" }, { "code": null, "e": 11612, "s": 11492, "text": "$ scrapy shell http://quotes.toscrape.com/...>>> response.css('.author + a::attr(href)').get()'/author/Albert-Einstein'" }, { "code": null, "e": 11899, "s": 11612, "text": "So, during the loop of extracting each quote, we issue another request to go to the corresponding author’s page and create another parse_author function to extract the author’s name, birthday, born location and bio and output to the console. The updated spider looks like the following:" }, { "code": null, "e": 12428, "s": 11899, "text": "Run the spider again scrapy crawl quotes and double-check that everything you need to extract is output to the console correctly. Note that Scrapy is based on Twisted, a popular event-driven networking framework for Python and thus is asynchronous. This means that the individual author page may not be processed in sync with the corresponding quote, e.g., the order of the author page results may not match the quote order on the page. We will discuss how to link the quote with its corresponding author page in the later part." }, { "code": null, "e": 12488, "s": 12428, "text": "Congratulations, you have finished Part I of this tutorial." }, { "code": null, "e": 12537, "s": 12488, "text": "Learn more about Item and ItemLoader in Part II." } ]
How to flush the internal buffer in Python?
Python buffers writes to files. That is, file.write returns before the data is actually written to your hard drive. The main motivation of this is that a few large writes are much faster than many tiny writes, so by saving up the output of file.write until a bit has accumulated, Python can maintain good writing speeds. file.flush forces the data to be written out at that moment. To flush contents you wrote actually to the file, use: with open("my_file.txt", "w+") as file: file.write("foo") file.write("bar") file.flush()
[ { "code": null, "e": 1383, "s": 1062, "text": "Python buffers writes to files. That is, file.write returns before the data is actually written to your hard drive. The main motivation of this is that a few large writes are much faster than many tiny writes, so by saving up the output of file.write until a bit has accumulated, Python can maintain good writing speeds." }, { "code": null, "e": 1499, "s": 1383, "text": "file.flush forces the data to be written out at that moment. To flush contents you wrote actually to the file, use:" }, { "code": null, "e": 1601, "s": 1499, "text": "with open(\"my_file.txt\", \"w+\") as file:\n file.write(\"foo\")\n file.write(\"bar\")\n file.flush()" } ]
Java - String Buffer append() Method
This method updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings, etc. Here is a separate method for each primitive data type − public StringBuffer append(boolean b) public StringBuffer append(char c) public StringBuffer append(char[] str) public StringBuffer append(char[] str, int offset, int len) public StringBuffer append(double d) public StringBuffer append(float f) public StringBuffer append(int i) public StringBuffer append(long l) public StringBuffer append(Object obj) public StringBuffer append(StringBuffer sb) public StringBuffer append(String str) Here is the detail of parameters − Here the parameter depends on what you are trying to append in the String Buffer. Here the parameter depends on what you are trying to append in the String Buffer. These methods return the updated StringBuffer objects. public class Test { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Test"); sb.append(" String Buffer"); System.out.println(sb); } } This will produce the following result − Test String Buffer 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": 2503, "s": 2377, "text": "This method updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings, etc." }, { "code": null, "e": 2560, "s": 2503, "text": "Here is a separate method for each primitive data type −" }, { "code": null, "e": 2997, "s": 2560, "text": "public StringBuffer append(boolean b)\npublic StringBuffer append(char c)\npublic StringBuffer append(char[] str)\npublic StringBuffer append(char[] str, int offset, int len)\npublic StringBuffer append(double d)\npublic StringBuffer append(float f)\npublic StringBuffer append(int i)\npublic StringBuffer append(long l)\npublic StringBuffer append(Object obj)\npublic StringBuffer append(StringBuffer sb)\npublic StringBuffer append(String str)\n" }, { "code": null, "e": 3032, "s": 2997, "text": "Here is the detail of parameters −" }, { "code": null, "e": 3114, "s": 3032, "text": "Here the parameter depends on what you are trying to append in the String Buffer." }, { "code": null, "e": 3196, "s": 3114, "text": "Here the parameter depends on what you are trying to append in the String Buffer." }, { "code": null, "e": 3251, "s": 3196, "text": "These methods return the updated StringBuffer objects." }, { "code": null, "e": 3441, "s": 3251, "text": "public class Test {\n\n public static void main(String args[]) {\n StringBuffer sb = new StringBuffer(\"Test\");\n sb.append(\" String Buffer\");\n System.out.println(sb); \n } \n}" }, { "code": null, "e": 3482, "s": 3441, "text": "This will produce the following result −" }, { "code": null, "e": 3502, "s": 3482, "text": "Test String Buffer\n" }, { "code": null, "e": 3535, "s": 3502, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3551, "s": 3535, "text": " Malhar Lathkar" }, { "code": null, "e": 3584, "s": 3551, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3600, "s": 3584, "text": " Malhar Lathkar" }, { "code": null, "e": 3635, "s": 3600, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3649, "s": 3635, "text": " Anadi Sharma" }, { "code": null, "e": 3683, "s": 3649, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3697, "s": 3683, "text": " Tushar Kale" }, { "code": null, "e": 3734, "s": 3697, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3749, "s": 3734, "text": " Monica Mittal" }, { "code": null, "e": 3782, "s": 3749, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3801, "s": 3782, "text": " Arnab Chakraborty" }, { "code": null, "e": 3808, "s": 3801, "text": " Print" }, { "code": null, "e": 3819, "s": 3808, "text": " Add Notes" } ]
Hyperparameter Tuning in Python | Towards Data Science
Kaggle’s Don’t Overfit II competition presents an interesting problem. We have 20,000 rows of continuous variables, with only 250 of them belonging to the training set. The challenge is not to overfit. With such a small dataset — and even smaller training set, this can be a difficult task! In this article, we’ll explore hyperparameter optimization as a means of preventing overfitting. The full notebook can be found here. Wikipedia states that “hyperparameter tuning is choosing a set of optimal hyperparameters for a learning algorithm”. So what is a hyperparameter? A hyperparameter is a parameter whose value is set before the learning process begins. Some examples of hyperparameters include penalty in logistic regression and loss in stochastic gradient descent. In sklearn, hyperparameters are passed in as arguments to the constructor of the model classes. We will explore two different methods for optimizing hyperparameters: Grid Search Random Search We’ll begin by preparing the data and trying several different models with their default hyperparameters. From these we’ll select the top two performing methods for hyperparameter tuning. We then find the mean cross validation score and standard deviation: RidgeCV Mean: 0.6759762475523124STD: 0.1170461756924883LassoCV Mean: 0.5STD: 0.0ElasticNetCV Mean: 0.5STD: 0.0LassoLarsCV Mean: 0.5STD: 0.0BayesianRidgeCV Mean: 0.688224616492365STD: 0.13183095412112777LogisticRegressionCV Mean: 0.7447916666666667STD: 0.053735373404660246SGDClassifierCV Mean: 0.7333333333333333STD: 0.03404902964480909 Our top performing models here are logistic regression and stochastic gradient descent. Let’s see if we can improve their performance through hyperparameter optimization. Grid search is a traditional way to perform hyperparameter optimization. It works by searching exhaustively through a specified subset of hyperparameters. Using sklearn’sGridSearchCV, we first define our grid of parameters to search over and then run the grid search. Fitting 3 folds for each of 128 candidates, totalling 384 fitsBest Score: 0.7899186582809224Best Params: {'C': 1, 'class_weight': {1: 0.6, 0: 0.4}, 'penalty': 'l1', 'solver': 'liblinear'} We improved our cross validation score from 0.744 to 0.789! The benefit of grid search is that it is guaranteed to find the optimal combination of parameters supplied. The drawback is that it can be very time consuming and computationally expensive. We can combat this with random search. Random search differs from grid search mainly in that it searches the specified subset of hyperparameters randomly instead of exhaustively. The major benefit being decreased processing time. There is a tradeoff to decreased processing time, however. We aren’t guaranteed to find the optimal combination of hyperparameters. Let’s give random search a try with sklearn’s RandomizedSearchCV. Very similar to grid search above, we define the hyperparameters to search over before running the search. An important additional parameter to specify here is n_iter. This specifies the number of combinations to randomly try. Selecting too low of a number will decrease our chance of finding the best combination. Selecting too large of a number will increase our processing time. Fitting 3 folds for each of 1000 candidates, totalling 3000 fitsBest Score: 0.7972911250873514Best Params: {'penalty': 'elasticnet', 'loss': 'log', 'learning_rate': 'optimal', 'eta0': 100, 'class_weight': {1: 0.7, 0: 0.3}, 'alpha': 0.1} Here we improved the cross validation score from 0.733 to 0.780! Here we explored two methods for hyperparameter turning and saw improvement in model performance. While this is an important step in modeling, it is by no means the only way to improve performance. In future articles we will explore other means to prevent overfitting including feature selection and ensembling.
[ { "code": null, "e": 341, "s": 172, "text": "Kaggle’s Don’t Overfit II competition presents an interesting problem. We have 20,000 rows of continuous variables, with only 250 of them belonging to the training set." }, { "code": null, "e": 374, "s": 341, "text": "The challenge is not to overfit." }, { "code": null, "e": 463, "s": 374, "text": "With such a small dataset — and even smaller training set, this can be a difficult task!" }, { "code": null, "e": 560, "s": 463, "text": "In this article, we’ll explore hyperparameter optimization as a means of preventing overfitting." }, { "code": null, "e": 597, "s": 560, "text": "The full notebook can be found here." }, { "code": null, "e": 743, "s": 597, "text": "Wikipedia states that “hyperparameter tuning is choosing a set of optimal hyperparameters for a learning algorithm”. So what is a hyperparameter?" }, { "code": null, "e": 830, "s": 743, "text": "A hyperparameter is a parameter whose value is set before the learning process begins." }, { "code": null, "e": 943, "s": 830, "text": "Some examples of hyperparameters include penalty in logistic regression and loss in stochastic gradient descent." }, { "code": null, "e": 1039, "s": 943, "text": "In sklearn, hyperparameters are passed in as arguments to the constructor of the model classes." }, { "code": null, "e": 1109, "s": 1039, "text": "We will explore two different methods for optimizing hyperparameters:" }, { "code": null, "e": 1121, "s": 1109, "text": "Grid Search" }, { "code": null, "e": 1135, "s": 1121, "text": "Random Search" }, { "code": null, "e": 1323, "s": 1135, "text": "We’ll begin by preparing the data and trying several different models with their default hyperparameters. From these we’ll select the top two performing methods for hyperparameter tuning." }, { "code": null, "e": 1392, "s": 1323, "text": "We then find the mean cross validation score and standard deviation:" }, { "code": null, "e": 1742, "s": 1392, "text": "RidgeCV Mean: 0.6759762475523124STD: 0.1170461756924883LassoCV Mean: 0.5STD: 0.0ElasticNetCV Mean: 0.5STD: 0.0LassoLarsCV Mean: 0.5STD: 0.0BayesianRidgeCV Mean: 0.688224616492365STD: 0.13183095412112777LogisticRegressionCV Mean: 0.7447916666666667STD: 0.053735373404660246SGDClassifierCV Mean: 0.7333333333333333STD: 0.03404902964480909" }, { "code": null, "e": 1913, "s": 1742, "text": "Our top performing models here are logistic regression and stochastic gradient descent. Let’s see if we can improve their performance through hyperparameter optimization." }, { "code": null, "e": 2068, "s": 1913, "text": "Grid search is a traditional way to perform hyperparameter optimization. It works by searching exhaustively through a specified subset of hyperparameters." }, { "code": null, "e": 2181, "s": 2068, "text": "Using sklearn’sGridSearchCV, we first define our grid of parameters to search over and then run the grid search." }, { "code": null, "e": 2371, "s": 2181, "text": "Fitting 3 folds for each of 128 candidates, totalling 384 fitsBest Score: 0.7899186582809224Best Params: {'C': 1, 'class_weight': {1: 0.6, 0: 0.4}, 'penalty': 'l1', 'solver': 'liblinear'}" }, { "code": null, "e": 2431, "s": 2371, "text": "We improved our cross validation score from 0.744 to 0.789!" }, { "code": null, "e": 2621, "s": 2431, "text": "The benefit of grid search is that it is guaranteed to find the optimal combination of parameters supplied. The drawback is that it can be very time consuming and computationally expensive." }, { "code": null, "e": 2660, "s": 2621, "text": "We can combat this with random search." }, { "code": null, "e": 2851, "s": 2660, "text": "Random search differs from grid search mainly in that it searches the specified subset of hyperparameters randomly instead of exhaustively. The major benefit being decreased processing time." }, { "code": null, "e": 2983, "s": 2851, "text": "There is a tradeoff to decreased processing time, however. We aren’t guaranteed to find the optimal combination of hyperparameters." }, { "code": null, "e": 3156, "s": 2983, "text": "Let’s give random search a try with sklearn’s RandomizedSearchCV. Very similar to grid search above, we define the hyperparameters to search over before running the search." }, { "code": null, "e": 3276, "s": 3156, "text": "An important additional parameter to specify here is n_iter. This specifies the number of combinations to randomly try." }, { "code": null, "e": 3431, "s": 3276, "text": "Selecting too low of a number will decrease our chance of finding the best combination. Selecting too large of a number will increase our processing time." }, { "code": null, "e": 3670, "s": 3431, "text": "Fitting 3 folds for each of 1000 candidates, totalling 3000 fitsBest Score: 0.7972911250873514Best Params: {'penalty': 'elasticnet', 'loss': 'log', 'learning_rate': 'optimal', 'eta0': 100, 'class_weight': {1: 0.7, 0: 0.3}, 'alpha': 0.1}" }, { "code": null, "e": 3735, "s": 3670, "text": "Here we improved the cross validation score from 0.733 to 0.780!" }, { "code": null, "e": 3833, "s": 3735, "text": "Here we explored two methods for hyperparameter turning and saw improvement in model performance." }, { "code": null, "e": 3933, "s": 3833, "text": "While this is an important step in modeling, it is by no means the only way to improve performance." } ]
Hibernate Criteria Example | Hibernate Criteria Tutorials Point
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to learn about Hibernate Criteria API. While working with Hibernate Query Language (HQL), we manually prepare the HQL queries for reading the data from database. For the better performance, it is always recommended to write a query as tuned query. In the case of HQL, we need to prepare the tuned queries. Hibernate will only translate HQL into SQL and then executes it, but it will not tune the queries. Here (HQL) the responsibility of tuning the queries on the developer. Instead of writing the HQL queries and tuning them explicitly, we can use Hibernate Criteria API. In the Hibernate Criteria API, there is no need to create a query. Instead, hibernate itself will prepare a tuned query. So that we can get better performance with criteria while reading the data from the database. Query tuning is required only while selecting the data, so hibernate Criteria API is for select operations only. Here is the complete example for hibernate criteria : Hibernate Criteria is an interface, it is a simplified API for retrieving entities. We can obtain a reference of Criteria interface by calling the createCriteria() method on the session by passing the object of a pojo class. Criteria criteria = session.createCriteria(Employee.class); Project Structure : Creating Employee Pojo : Employee.java package com.otp.hibernate.pojo; public class Employee { private int employeeId; private String employeeName; private int departmentId; private int salary; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public int getDepartmentId() { return departmentId; } public void setDepartmentId(int departmentId) { this.departmentId = departmentId; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } @Override public String toString() { return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", departmentId=" + departmentId + ", salary=" + salary + "]"; } } Hibernate mapping file : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.otp.hibernate.pojo.Employee" table="employee" schema="onlinetutorialspoint"> <id name="employeeId" column="id"> <generator class="increment" /> </id> <property name="employeeName" column="ename" /> <property name="departmentId" column="deptNo" /> <property name="salary" column="salary" /> </class> </hibernate-mapping> As we discussed in HQL example, we can read the data from database in three forms, like Reading complete entity Reading partial entity Reading partial entity with single column import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Projection; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import com.otp.hibernate.pojo.Employee; public class Main { public static void main(String[] args) { Configuration configuration = new Configuration() .configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); SessionFactory factory = configuration.buildSessionFactory(builder .build()); Session session = factory.openSession(); System.out.println("Reading Complete Entity"); Criteria crit = session.createCriteria(Employee.class); List list = crit.list(); Iterator it = list.iterator(); while (it.hasNext()) { Employee emp = (Employee) it.next(); System.out.println("Employee : " + emp.toString()); } session.close(); } } Output : Reading Complete Entity Employee : Employee [employeeId=1, employeeName=Chandra, departmentId=101, salary=6000] Employee : Employee [employeeId=2, employeeName=Shekhar, departmentId=101, salary=8000] Employee : Employee [employeeId=3, employeeName=Rahul, departmentId=105, salary=4000] Employee : Employee [employeeId=4, employeeName=Mahesh, departmentId=103, salary=5000] Employee : Employee [employeeId=5, employeeName=Vinay, departmentId=101, salary=4000] Employee : Employee [employeeId=6, employeeName=Vijay, departmentId=105, salary=3000] To read the partial entity, hibernate criteria provides us, Projection interface. By using the Projection interface, we can set the columns as parameters, which we want to read. Projection projection = Projections.property("salary"); Finally, we need to add the projection to criteria. criteria.setProjection(projection); If we want to read the multiple columns, we can create the multiple Projection instances like below : Projection projection = Projections.property("salary"); Projection projection2 = Projections.property("departmentId"); Projection projection3 = Projections.property("employeeName"); Get the ProjectionsList object and add all projections to projectionslist object like below : ProjectionList pList = Projections.projectionList(); pList.add(projection); pList.add(projection2); pList.add(projection3); Complete Example : Criteria crit3 = session.createCriteria(Employee.class); Projection projection = Projections.property("salary"); Projection projection2 = Projections.property("departmentId"); Projection projection3 = Projections.property("employeeName"); ProjectionList pList = Projections.projectionList(); pList.add(projection); pList.add(projection2); pList.add(projection3); crit3.setProjection(pList); List list3 = crit3.list(); Iterator it3 = list3.iterator(); while (it3.hasNext()) { Object[] obj = (Object[]) it3.next(); System.out.println("Salary : " + obj[0] + " DeptId : " + obj[1] + " empName : " + obj[2]); } To add a condition to criteria, hibernate provides us Criterion interface. We can obtain criterion object by calling the static methods of Restrictions class. To add the criterion object to criteria, we call add() method like below : Criteria crit = session.createCriteria(Employee.class); Criterion criterion = Restrictions.eq("departmentId", 101); crit.add(criterion); The above statements represents, get the employee records from database, whose department id is 101; Complete Example : Criteria crit2 = session.createCriteria(Employee.class); Criterion criterion = Restrictions.eq("departmentId", 101); crit2.add(criterion); List list2 = crit2.list(); Iterator it2 = list2.iterator(); while (it2.hasNext()) { Employee emp = (Employee) it2.next(); System.out.println("Employee : " + emp.toString()); } The complete Example is available to download. Happy Learning 🙂 Hibernate-CriteriaAPI-Example File size: 14 KB Downloads: 921 Hibernate Restrictions with Example Hibernate Filters Example Annotation @Formula Annotation in Hibernate Example Hibernate Filter Example Xml Configuration Hibernate Native SQL Query Example hibernate update query example Hibernate One to One Mapping using primary key (XML) Hibernate orderby criteria Example Hibernate groupby criteria HQL query Example What is Hibernate Hibernate 4 Example with Annotations Mysql Different types of Object States in Hibernate Difference between update vs merge in Hibernate example Hibernate cache first level example Table per Class Strategy in Hibernate Inheritance Hibernate Restrictions with Example Hibernate Filters Example Annotation @Formula Annotation in Hibernate Example Hibernate Filter Example Xml Configuration Hibernate Native SQL Query Example hibernate update query example Hibernate One to One Mapping using primary key (XML) Hibernate orderby criteria Example Hibernate groupby criteria HQL query Example What is Hibernate Hibernate 4 Example with Annotations Mysql Different types of Object States in Hibernate Difference between update vs merge in Hibernate example Hibernate cache first level example Table per Class Strategy in Hibernate Inheritance Elvin Antonio Mendoza September 11, 2019 at 2:21 am - Reply Thank you for your help, I was looking for a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok. Elvin Antonio Mendoza September 11, 2019 at 2:21 am - Reply Thank you for your help, I was looking for a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok. Thank you for your help, I was looking for a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok. Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 677, "s": 398, "text": "In this tutorial, we are going to learn about Hibernate Criteria API. While working with Hibernate Query Language (HQL), we manually prepare the HQL queries for reading the data from database. For the better performance, it is always recommended to write a query as tuned query." }, { "code": null, "e": 904, "s": 677, "text": "In the case of HQL, we need to prepare the tuned queries. Hibernate will only translate HQL into SQL and then executes it, but it will not tune the queries. Here (HQL) the responsibility of tuning the queries on the developer." }, { "code": null, "e": 1002, "s": 904, "text": "Instead of writing the HQL queries and tuning them explicitly, we can use Hibernate Criteria API." }, { "code": null, "e": 1217, "s": 1002, "text": "In the Hibernate Criteria API, there is no need to create a query. Instead, hibernate itself will prepare a tuned query. So that we can get better performance with criteria while reading the data from the database." }, { "code": null, "e": 1330, "s": 1217, "text": "Query tuning is required only while selecting the data, so hibernate Criteria API is for select operations only." }, { "code": null, "e": 1384, "s": 1330, "text": "Here is the complete example for hibernate criteria :" }, { "code": null, "e": 1689, "s": 1384, "text": "Hibernate Criteria is an interface, it is a simplified API for retrieving entities. We can obtain a reference of Criteria interface by calling the createCriteria() method on the session by passing the object of a pojo class.\nCriteria criteria = session.createCriteria(Employee.class);\nProject Structure :" }, { "code": null, "e": 1714, "s": 1689, "text": "Creating Employee Pojo :" }, { "code": null, "e": 1728, "s": 1714, "text": "Employee.java" }, { "code": null, "e": 2785, "s": 1728, "text": "package com.otp.hibernate.pojo;\n\npublic class Employee {\n private int employeeId;\n private String employeeName;\n private int departmentId;\n private int salary;\n\n public int getEmployeeId() {\n return employeeId;\n }\n\n public void setEmployeeId(int employeeId) {\n this.employeeId = employeeId;\n }\n\n public String getEmployeeName() {\n return employeeName;\n }\n\n public void setEmployeeName(String employeeName) {\n this.employeeName = employeeName;\n }\n\n public int getDepartmentId() {\n return departmentId;\n }\n\n public void setDepartmentId(int departmentId) {\n this.departmentId = departmentId;\n }\n\n public int getSalary() {\n return salary;\n }\n\n public void setSalary(int salary) {\n this.salary = salary;\n }\n\n @Override\n public String toString() {\n return \"Employee [employeeId=\" + employeeId + \", employeeName=\"\n + employeeName + \", departmentId=\" + departmentId + \", salary=\"\n + salary + \"]\";\n }\n}\n" }, { "code": null, "e": 2810, "s": 2785, "text": "Hibernate mapping file :" }, { "code": null, "e": 3420, "s": 2810, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC\n \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n<hibernate-mapping>\n <class name=\"com.otp.hibernate.pojo.Employee\" table=\"employee\"\n schema=\"onlinetutorialspoint\">\n <id name=\"employeeId\" column=\"id\">\n <generator class=\"increment\" />\n </id>\n <property name=\"employeeName\" column=\"ename\" />\n <property name=\"departmentId\" column=\"deptNo\" />\n <property name=\"salary\" column=\"salary\" />\n </class>\n</hibernate-mapping>" }, { "code": null, "e": 3508, "s": 3420, "text": "As we discussed in HQL example, we can read the data from database in three forms, like" }, { "code": null, "e": 3532, "s": 3508, "text": "Reading complete entity" }, { "code": null, "e": 3555, "s": 3532, "text": "Reading partial entity" }, { "code": null, "e": 3597, "s": 3555, "text": "Reading partial entity with single column" }, { "code": null, "e": 4975, "s": 3597, "text": "import java.util.Iterator;\nimport java.util.List;\n\nimport org.hibernate.Criteria;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.boot.registry.StandardServiceRegistryBuilder;\nimport org.hibernate.cfg.Configuration;\nimport org.hibernate.criterion.Criterion;\nimport org.hibernate.criterion.Projection;\nimport org.hibernate.criterion.ProjectionList;\nimport org.hibernate.criterion.Projections;\nimport org.hibernate.criterion.Restrictions;\n\nimport com.otp.hibernate.pojo.Employee;\n\npublic class Main {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration()\n .configure(\"hibernate.cfg.xml\");\n StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()\n .applySettings(configuration.getProperties());\n SessionFactory factory = configuration.buildSessionFactory(builder\n .build());\n\n Session session = factory.openSession();\n\n System.out.println(\"Reading Complete Entity\");\n\n Criteria crit = session.createCriteria(Employee.class);\n List list = crit.list();\n\n Iterator it = list.iterator();\n\n while (it.hasNext()) {\n Employee emp = (Employee) it.next();\n System.out.println(\"Employee : \" + emp.toString());\n\n }\n\n session.close();\n }\n}\n" }, { "code": null, "e": 4986, "s": 4977, "text": "Output :" }, { "code": null, "e": 5531, "s": 4986, "text": "Reading Complete Entity\nEmployee : Employee [employeeId=1, employeeName=Chandra, departmentId=101, salary=6000]\nEmployee : Employee [employeeId=2, employeeName=Shekhar, departmentId=101, salary=8000]\nEmployee : Employee [employeeId=3, employeeName=Rahul, departmentId=105, salary=4000]\nEmployee : Employee [employeeId=4, employeeName=Mahesh, departmentId=103, salary=5000]\nEmployee : Employee [employeeId=5, employeeName=Vinay, departmentId=101, salary=4000]\nEmployee : Employee [employeeId=6, employeeName=Vijay, departmentId=105, salary=3000]" }, { "code": null, "e": 5613, "s": 5531, "text": "To read the partial entity, hibernate criteria provides us, Projection interface." }, { "code": null, "e": 5853, "s": 5613, "text": "By using the Projection interface, we can set the columns as parameters, which we want to read.\nProjection projection = Projections.property(\"salary\");\nFinally, we need to add the projection to criteria.\ncriteria.setProjection(projection);" }, { "code": null, "e": 5955, "s": 5853, "text": "If we want to read the multiple columns, we can create the multiple Projection instances like below :" }, { "code": null, "e": 6357, "s": 5955, "text": "Projection projection = Projections.property(\"salary\");\nProjection projection2 = Projections.property(\"departmentId\");\nProjection projection3 = Projections.property(\"employeeName\");\n\nGet the ProjectionsList object and add all projections to projectionslist object like below :\n\nProjectionList pList = Projections.projectionList();\npList.add(projection);\npList.add(projection2);\npList.add(projection3);" }, { "code": null, "e": 6376, "s": 6357, "text": "Complete Example :" }, { "code": null, "e": 7127, "s": 6376, "text": "\nCriteria crit3 = session.createCriteria(Employee.class);\n Projection projection = Projections.property(\"salary\");\n Projection projection2 = Projections.property(\"departmentId\");\n Projection projection3 = Projections.property(\"employeeName\");\n\n ProjectionList pList = Projections.projectionList();\n pList.add(projection);\n pList.add(projection2);\n pList.add(projection3);\n crit3.setProjection(pList);\n\n List list3 = crit3.list();\n\n Iterator it3 = list3.iterator();\n\n while (it3.hasNext()) {\n Object[] obj = (Object[]) it3.next();\n System.out.println(\"Salary : \" + obj[0] + \" DeptId : \" + obj[1]\n + \" empName : \" + obj[2]);\n }" }, { "code": null, "e": 7361, "s": 7127, "text": "To add a condition to criteria, hibernate provides us Criterion interface. We can obtain criterion object by calling the static methods of Restrictions class. To add the criterion object to criteria, we call add() method like below :" }, { "code": null, "e": 7500, "s": 7361, "text": "Criteria crit = session.createCriteria(Employee.class);\n\nCriterion criterion = Restrictions.eq(\"departmentId\", 101);\n\ncrit.add(criterion);" }, { "code": null, "e": 7601, "s": 7500, "text": "The above statements represents, get the employee records from database, whose department id is 101;" }, { "code": null, "e": 7620, "s": 7601, "text": "Complete Example :" }, { "code": null, "e": 8013, "s": 7620, "text": "\nCriteria crit2 = session.createCriteria(Employee.class);\n\n Criterion criterion = Restrictions.eq(\"departmentId\", 101);\n\n crit2.add(criterion);\n\n List list2 = crit2.list();\n\n Iterator it2 = list2.iterator();\n\n while (it2.hasNext()) {\n Employee emp = (Employee) it2.next();\n System.out.println(\"Employee : \" + emp.toString());\n }" }, { "code": null, "e": 8060, "s": 8013, "text": "The complete Example is available to download." }, { "code": null, "e": 8077, "s": 8060, "text": "Happy Learning 🙂" }, { "code": null, "e": 8143, "s": 8077, "text": "\n\nHibernate-CriteriaAPI-Example\n\nFile size: 14 KB\nDownloads: 921\n" }, { "code": null, "e": 8750, "s": 8143, "text": "\nHibernate Restrictions with Example\nHibernate Filters Example Annotation\n@Formula Annotation in Hibernate Example\nHibernate Filter Example Xml Configuration\nHibernate Native SQL Query Example\nhibernate update query example\nHibernate One to One Mapping using primary key (XML)\nHibernate orderby criteria Example\nHibernate groupby criteria HQL query Example\nWhat is Hibernate\nHibernate 4 Example with Annotations Mysql\nDifferent types of Object States in Hibernate\nDifference between update vs merge in Hibernate example\nHibernate cache first level example\nTable per Class Strategy in Hibernate Inheritance\n" }, { "code": null, "e": 8786, "s": 8750, "text": "Hibernate Restrictions with Example" }, { "code": null, "e": 8823, "s": 8786, "text": "Hibernate Filters Example Annotation" }, { "code": null, "e": 8864, "s": 8823, "text": "@Formula Annotation in Hibernate Example" }, { "code": null, "e": 8907, "s": 8864, "text": "Hibernate Filter Example Xml Configuration" }, { "code": null, "e": 8942, "s": 8907, "text": "Hibernate Native SQL Query Example" }, { "code": null, "e": 8973, "s": 8942, "text": "hibernate update query example" }, { "code": null, "e": 9026, "s": 8973, "text": "Hibernate One to One Mapping using primary key (XML)" }, { "code": null, "e": 9061, "s": 9026, "text": "Hibernate orderby criteria Example" }, { "code": null, "e": 9106, "s": 9061, "text": "Hibernate groupby criteria HQL query Example" }, { "code": null, "e": 9124, "s": 9106, "text": "What is Hibernate" }, { "code": null, "e": 9167, "s": 9124, "text": "Hibernate 4 Example with Annotations Mysql" }, { "code": null, "e": 9213, "s": 9167, "text": "Different types of Object States in Hibernate" }, { "code": null, "e": 9269, "s": 9213, "text": "Difference between update vs merge in Hibernate example" }, { "code": null, "e": 9305, "s": 9269, "text": "Hibernate cache first level example" }, { "code": null, "e": 9355, "s": 9305, "text": "Table per Class Strategy in Hibernate Inheritance" }, { "code": null, "e": 9617, "s": 9355, "text": "\n\n\n\n\n\nElvin Antonio Mendoza\nSeptember 11, 2019 at 2:21 am - Reply \n\nThank you for your help, I was looking for a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok.\n\n\n\n\n" }, { "code": null, "e": 9877, "s": 9617, "text": "\n\n\n\n\nElvin Antonio Mendoza\nSeptember 11, 2019 at 2:21 am - Reply \n\nThank you for your help, I was looking for a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok.\n\n\n\n" }, { "code": null, "e": 10066, "s": 9877, "text": "Thank you for your help, I was looking for a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok." }, { "code": null, "e": 10072, "s": 10070, "text": "Δ" }, { "code": null, "e": 10098, "s": 10072, "text": " Hibernate – Introduction" }, { "code": null, "e": 10122, "s": 10098, "text": " Hibernate – Advantages" }, { "code": null, "e": 10154, "s": 10122, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 10184, "s": 10154, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 10214, "s": 10184, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 10252, "s": 10214, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 10279, "s": 10252, "text": " Hibernate – Object States" }, { "code": null, "e": 10317, "s": 10279, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 10355, "s": 10317, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 10405, "s": 10355, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 10435, "s": 10405, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 10474, "s": 10435, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 10514, "s": 10474, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 10545, "s": 10514, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 10580, "s": 10545, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 10605, "s": 10580, "text": " Hibernate – Named Query" }, { "code": null, "e": 10635, "s": 10605, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 10664, "s": 10635, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 10701, "s": 10664, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 10727, "s": 10701, "text": " Hibernate – Restrictions" }, { "code": null, "e": 10751, "s": 10727, "text": " Hibernate – Projection" }, { "code": null, "e": 10785, "s": 10751, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 10819, "s": 10785, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 10849, "s": 10819, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 10882, "s": 10849, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 10914, "s": 10882, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 10940, "s": 10914, "text": " Hibernate – Update Query" }, { "code": null, "e": 10969, "s": 10940, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 10993, "s": 10969, "text": " Hibernate – Right Join" }, { "code": null, "e": 11016, "s": 10993, "text": " Hibernate – Left Join" }, { "code": null, "e": 11040, "s": 11016, "text": " Hibernate – Pagination" }, { "code": null, "e": 11071, "s": 11040, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 11101, "s": 11071, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 11135, "s": 11101, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 11164, "s": 11135, "text": " Hibernate – Table per Class" }, { "code": null, "e": 11197, "s": 11164, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 11235, "s": 11197, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 11277, "s": 11235, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 11308, "s": 11277, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 11341, "s": 11308, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 11379, "s": 11341, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 11404, "s": 11379, "text": " Hibernate – Interceptor" }, { "code": null, "e": 11450, "s": 11404, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
Data Scientist vs Senior Data Scientist. Here’s the Difference. | by Matt Przybyla | Towards Data Science
IntroductionData ScientistSenior Data ScientistSummaryReferences Introduction Data Scientist Senior Data Scientist Summary References This article is for current data scientists who want to move up in their careers as well as for people switching careers to the data science landscape and want to know what separates and defines a senior role. It is important to note that not every workplace or company will offer both of these positions; however, if you satisfy the characteristics of a senior data scientist, you may be able to prove to your company why getting that title is worth it for you and them. The senior data scientist position does not just mean that you are a data scientist with a certain amount of years of experience. It is rather, a position that entails a difference in responsibility of the impact of your data science or machine learning models on the business that you work for. Not only are there key differences between the two job titles, but there are also some interesting differences and overlaps between the amount of machine learning, business intelligence, and product management from each role. Below, I will discuss both my experience in the two positions as well as reference material on distinguishing the two titles. A data scientist is someone who defines a business problem, pulls data, performs exploratory data analysis, develops a machine learning model, and ultimately executes the model to display usable results or predictions for the end-user. While both the normal and senior titles overlap considerably in terms of required skills, programming languages, and overall knowledge, the main differences lie in what the two titles focus on — namely their responsibility in each of their respective facets of the data science process. As you will later see in this section and the next, the role of a senior position focuses on the beginning and end parts of the data science process, while the non-senior position focuses more on the middle part of that same process. Below, I will outline these key defining characteristics. Overall, the main process, in order, is typically the following: 1. defines the business problem (SR)2. develops data (SR)3. exploratory data analysis4. builds the model5. explains results to stakeholders (SR) While this setup is different for each company and its respective job descriptions, I believe it makes sense generally from my personal experiences. The normal data scientist position focuses on model building and the senior position focuses on defining the statement and using that model as the solution, which will ultimately be described in a meeting with either senior leadership or the company board. Here are the two parts of the overall process that a traditional, non-senior data scientist will focus on: exploratory data analysis — once you have the data or dataset, you will look for missing values, test for normality, check if classes are balanced, feature engineer, and more to polish your input data for your model. builds the model — the next step in the process is to build base models that do not focus on hyperparameters, but focus on whether the problem is supervised or unsupervised, (time series, etc...). Once you establish which model and library are appropriate to employ, it will be applied in your Jupyter Notebook or platform that houses all your exploratory data analysis. Next, you will perform iterations on that model and tune hyperparameters, and either deploy it yourself or rely on a machine learning engineer to deploy that model into production (once again, every company is different). A senior data scientist can and should be able to perform all the tasks of a typical data scientist while also interacting with the business-facing side more often. You will collaborate with stakeholders, subject matter experts, and company leadership to get the most use and positive impact of the model on your business. defines the business problem — while a traditional data scientist will focus on the model itself, the senior position will generally entail a proof-of-concept. You will explain to the business the value that the model will drive, as well as possible complications, needed resources, and who will interact with the predictions or results. This role can sometimes be seen as a product manager who organizes the process to make sure that specific collaborators are all aligned. When data science is performed in the workplace (as opposed to academia), you will be working with subject matter experts, software engineers, data engineers, and UX/UI designers. This part of the operation is somewhat ignored in school where the main focus is building the model. You can build an incredibly accurate model, but if it is not helping the business by automating a previously manual process or driving value, then you are wasting time, money, and the model is obsolete. The senior position will make sure that the entire model is effective and everyone stays on track. develops data — once the concept of the model is proven by establishing the business problem statement and solution, you will then have to find your data sources. Similarly, this point is not stressed as much in academia and is an incredibly vital part of your position, as creating your dataset can take days or weeks. You may have to reference an API (Application Programming Interface) with software and data engineers or perform complex joins across databases and tables. explains results to stakeholders — now that the statement is defined (think of this as a hypothesis as well), data is established, exploratory data analysis is performed, the model is built, you will now need a person from your data science team, usually at the senior level, to explain your complex results to non-technical users. What if my company does not have a senior position available? — if you have satisfied the conditions above, you should outline all of the steps you do in the data science process to prove to hiring managers or leadership that you deserve that senior title. If you are building the model and running the entire project like a product manager, you should be recognized for that as it is essentially two roles you are performing. Yes, these descriptions and examples can be different at your company, but in general, from my experience, especially looking at hundreds of LinkedIn profiles and job descriptions, the consensus is that a normal, non-senior position focuses on the model and the senior position focuses on how that same model interacts with your business. Additionally, in some places, a senior position can be described as someone who just has more work experience in the number of years, but with that increased work experience, that data scientist will employ the facets of the process I described in the senior data scientist position above. There is not necessarily an official word on the formal differences between senior and non-senior, but there are several articles and job descriptions that summarize this description similarly as I have here. Here [4] is an article outlining the senior data scientist position that is helpful. I hope you found this article interesting and useful. Thank you for reading! [1] Photo by Christina @ wocintechchat.com, (2019) [2] Photo by Christina @ wocintechchat.com, (2019) [3] Photo by Christina @ wocintechchat.com, (2019) [4] Peadar Coyle, What Does it Mean to Be a Senior Data Scientist?, (2020)
[ { "code": null, "e": 237, "s": 172, "text": "IntroductionData ScientistSenior Data ScientistSummaryReferences" }, { "code": null, "e": 250, "s": 237, "text": "Introduction" }, { "code": null, "e": 265, "s": 250, "text": "Data Scientist" }, { "code": null, "e": 287, "s": 265, "text": "Senior Data Scientist" }, { "code": null, "e": 295, "s": 287, "text": "Summary" }, { "code": null, "e": 306, "s": 295, "text": "References" }, { "code": null, "e": 778, "s": 306, "text": "This article is for current data scientists who want to move up in their careers as well as for people switching careers to the data science landscape and want to know what separates and defines a senior role. It is important to note that not every workplace or company will offer both of these positions; however, if you satisfy the characteristics of a senior data scientist, you may be able to prove to your company why getting that title is worth it for you and them." }, { "code": null, "e": 1074, "s": 778, "text": "The senior data scientist position does not just mean that you are a data scientist with a certain amount of years of experience. It is rather, a position that entails a difference in responsibility of the impact of your data science or machine learning models on the business that you work for." }, { "code": null, "e": 1426, "s": 1074, "text": "Not only are there key differences between the two job titles, but there are also some interesting differences and overlaps between the amount of machine learning, business intelligence, and product management from each role. Below, I will discuss both my experience in the two positions as well as reference material on distinguishing the two titles." }, { "code": null, "e": 2306, "s": 1426, "text": "A data scientist is someone who defines a business problem, pulls data, performs exploratory data analysis, develops a machine learning model, and ultimately executes the model to display usable results or predictions for the end-user. While both the normal and senior titles overlap considerably in terms of required skills, programming languages, and overall knowledge, the main differences lie in what the two titles focus on — namely their responsibility in each of their respective facets of the data science process. As you will later see in this section and the next, the role of a senior position focuses on the beginning and end parts of the data science process, while the non-senior position focuses more on the middle part of that same process. Below, I will outline these key defining characteristics. Overall, the main process, in order, is typically the following:" }, { "code": null, "e": 2451, "s": 2306, "text": "1. defines the business problem (SR)2. develops data (SR)3. exploratory data analysis4. builds the model5. explains results to stakeholders (SR)" }, { "code": null, "e": 2600, "s": 2451, "text": "While this setup is different for each company and its respective job descriptions, I believe it makes sense generally from my personal experiences." }, { "code": null, "e": 2857, "s": 2600, "text": "The normal data scientist position focuses on model building and the senior position focuses on defining the statement and using that model as the solution, which will ultimately be described in a meeting with either senior leadership or the company board." }, { "code": null, "e": 2964, "s": 2857, "text": "Here are the two parts of the overall process that a traditional, non-senior data scientist will focus on:" }, { "code": null, "e": 3181, "s": 2964, "text": "exploratory data analysis — once you have the data or dataset, you will look for missing values, test for normality, check if classes are balanced, feature engineer, and more to polish your input data for your model." }, { "code": null, "e": 3774, "s": 3181, "text": "builds the model — the next step in the process is to build base models that do not focus on hyperparameters, but focus on whether the problem is supervised or unsupervised, (time series, etc...). Once you establish which model and library are appropriate to employ, it will be applied in your Jupyter Notebook or platform that houses all your exploratory data analysis. Next, you will perform iterations on that model and tune hyperparameters, and either deploy it yourself or rely on a machine learning engineer to deploy that model into production (once again, every company is different)." }, { "code": null, "e": 4097, "s": 3774, "text": "A senior data scientist can and should be able to perform all the tasks of a typical data scientist while also interacting with the business-facing side more often. You will collaborate with stakeholders, subject matter experts, and company leadership to get the most use and positive impact of the model on your business." }, { "code": null, "e": 4853, "s": 4097, "text": "defines the business problem — while a traditional data scientist will focus on the model itself, the senior position will generally entail a proof-of-concept. You will explain to the business the value that the model will drive, as well as possible complications, needed resources, and who will interact with the predictions or results. This role can sometimes be seen as a product manager who organizes the process to make sure that specific collaborators are all aligned. When data science is performed in the workplace (as opposed to academia), you will be working with subject matter experts, software engineers, data engineers, and UX/UI designers. This part of the operation is somewhat ignored in school where the main focus is building the model." }, { "code": null, "e": 5056, "s": 4853, "text": "You can build an incredibly accurate model, but if it is not helping the business by automating a previously manual process or driving value, then you are wasting time, money, and the model is obsolete." }, { "code": null, "e": 5155, "s": 5056, "text": "The senior position will make sure that the entire model is effective and everyone stays on track." }, { "code": null, "e": 5631, "s": 5155, "text": "develops data — once the concept of the model is proven by establishing the business problem statement and solution, you will then have to find your data sources. Similarly, this point is not stressed as much in academia and is an incredibly vital part of your position, as creating your dataset can take days or weeks. You may have to reference an API (Application Programming Interface) with software and data engineers or perform complex joins across databases and tables." }, { "code": null, "e": 5963, "s": 5631, "text": "explains results to stakeholders — now that the statement is defined (think of this as a hypothesis as well), data is established, exploratory data analysis is performed, the model is built, you will now need a person from your data science team, usually at the senior level, to explain your complex results to non-technical users." }, { "code": null, "e": 6025, "s": 5963, "text": "What if my company does not have a senior position available?" }, { "code": null, "e": 6390, "s": 6025, "text": "— if you have satisfied the conditions above, you should outline all of the steps you do in the data science process to prove to hiring managers or leadership that you deserve that senior title. If you are building the model and running the entire project like a product manager, you should be recognized for that as it is essentially two roles you are performing." }, { "code": null, "e": 7019, "s": 6390, "text": "Yes, these descriptions and examples can be different at your company, but in general, from my experience, especially looking at hundreds of LinkedIn profiles and job descriptions, the consensus is that a normal, non-senior position focuses on the model and the senior position focuses on how that same model interacts with your business. Additionally, in some places, a senior position can be described as someone who just has more work experience in the number of years, but with that increased work experience, that data scientist will employ the facets of the process I described in the senior data scientist position above." }, { "code": null, "e": 7313, "s": 7019, "text": "There is not necessarily an official word on the formal differences between senior and non-senior, but there are several articles and job descriptions that summarize this description similarly as I have here. Here [4] is an article outlining the senior data scientist position that is helpful." }, { "code": null, "e": 7390, "s": 7313, "text": "I hope you found this article interesting and useful. Thank you for reading!" }, { "code": null, "e": 7441, "s": 7390, "text": "[1] Photo by Christina @ wocintechchat.com, (2019)" }, { "code": null, "e": 7492, "s": 7441, "text": "[2] Photo by Christina @ wocintechchat.com, (2019)" }, { "code": null, "e": 7543, "s": 7492, "text": "[3] Photo by Christina @ wocintechchat.com, (2019)" } ]
Difference between ++*p, *p++ and *++p in c++
In this section we will see what are the differences between *ptr++, *++ptr and ++*ptr in C++. Here we will see the precedence of postfix++ and prefix++ in C or C++. The precedence of prefix ++ or -- has higher priority than dereference operator ‘*’ and postfix ++ or -- has priority higher than both prefix ++ and dereference operator ‘*’. When ptr is a pointer, then *ptr++ indicates *(ptr++) and ++*prt refers ++(*ptr) Live Demo #include<iostream> using namespace std; int main() { char arr[] = "Hello World"; char *ptr = arr; ++*ptr; cout << *ptr; return 0; } I So here at first ptr is pointing ‘H’. after using ++*ptr it increases H by 1, and now the value is ‘I’. #include<iostream> using namespace std; int main() { char arr[] = "Hello World"; char *ptr = arr; *ptr++; cout << *ptr; return 0; } e So here at first ptr is pointing ‘H’. after using *ptr++ it increases the pointer, so ptr will point to the next element. so the result is ‘e’. Live Demo #include<iostream> using namespace std; int main() { char arr[] = "Hello World"; char *ptr = arr; *++ptr; cout << *ptr; return 0; } e In this example also we are increasing the ptr using ++, where the precedence of pre-increment ++ is higher, then it increases the pointer first, then taking the value using *. so it is printing ‘e’.
[ { "code": null, "e": 1157, "s": 1062, "text": "In this section we will see what are the differences between *ptr++, *++ptr and ++*ptr in C++." }, { "code": null, "e": 1403, "s": 1157, "text": "Here we will see the precedence of postfix++ and prefix++ in C or C++. The precedence of prefix ++ or -- has higher priority than dereference operator ‘*’ and postfix ++ or -- has priority higher than both prefix ++ and dereference operator ‘*’." }, { "code": null, "e": 1484, "s": 1403, "text": "When ptr is a pointer, then *ptr++ indicates *(ptr++) and ++*prt refers ++(*ptr)" }, { "code": null, "e": 1495, "s": 1484, "text": " Live Demo" }, { "code": null, "e": 1642, "s": 1495, "text": "#include<iostream>\nusing namespace std;\nint main() {\n char arr[] = \"Hello World\";\n char *ptr = arr;\n ++*ptr;\n cout << *ptr;\n return 0;\n}" }, { "code": null, "e": 1644, "s": 1642, "text": "I" }, { "code": null, "e": 1748, "s": 1644, "text": "So here at first ptr is pointing ‘H’. after using ++*ptr it increases H by 1, and now the value is ‘I’." }, { "code": null, "e": 1895, "s": 1748, "text": "#include<iostream>\nusing namespace std;\nint main() {\n char arr[] = \"Hello World\";\n char *ptr = arr;\n *ptr++;\n cout << *ptr;\n return 0;\n}" }, { "code": null, "e": 1897, "s": 1895, "text": "e" }, { "code": null, "e": 2041, "s": 1897, "text": "So here at first ptr is pointing ‘H’. after using *ptr++ it increases the pointer, so ptr will point to the next element. so the result is ‘e’." }, { "code": null, "e": 2052, "s": 2041, "text": " Live Demo" }, { "code": null, "e": 2199, "s": 2052, "text": "#include<iostream>\nusing namespace std;\nint main() {\n char arr[] = \"Hello World\";\n char *ptr = arr;\n *++ptr;\n cout << *ptr;\n return 0;\n}" }, { "code": null, "e": 2201, "s": 2199, "text": "e" }, { "code": null, "e": 2401, "s": 2201, "text": "In this example also we are increasing the ptr using ++, where the precedence of pre-increment ++ is higher, then it increases the pointer first, then taking the value using *. so it is printing ‘e’." } ]
Selenium Webdriver submit() vs click().
The click() and submit() functions are quite similar in terms of functionalities. However there are minor differences. Let us discuss some differences between them. The submit() function is applicable only for <form> and makes handling of form easier. It can be used with any element inside a form. The click() is only applicable to buttons with type submit in a form. The submit() function shall wait for the page to load however the click() waits only if any explicit wait condition is provided. If a form has a submit of type button, the submit() method cannot be used. Also, if a button is outside <form>, then submit() will not work. Thus we see that click() works for both type buttons irrespective of the fact that the button is inside or outside of <form>. Let us take up the below form for implementation. Code Implementation with submit(). import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class SubmitForm{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.facebook.com/"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify elements driver.findElement(By.id("email")).sendKeys("[email protected]"); driver.findElement(By.id("pass")).sendKeys("123456"); // submitting form with submit() driver.findElement(By.id("pass")).submit(); driver.quit() } } Code Implementation with click(). import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class ClickForm{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.facebook.com/"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify elements driver.findElement(By.id("email")).sendKeys("[email protected]"); driver.findElement(By.id("pass")).sendKeys("123456"); // submitting form with click() driver.findElement(By.name("login")).click(); driver.quit() } }
[ { "code": null, "e": 1227, "s": 1062, "text": "The click() and submit() functions are quite similar in terms of functionalities. However there are minor differences. Let us discuss some differences between them." }, { "code": null, "e": 1431, "s": 1227, "text": "The submit() function is applicable only for <form> and makes handling of form easier. It can be used with any element inside a form. The click() is only applicable to buttons with type submit in a form." }, { "code": null, "e": 1701, "s": 1431, "text": "The submit() function shall wait for the page to load however the click() waits only if any explicit wait condition is provided. If a form has a submit of type button, the submit() method cannot be used. Also, if a button is outside <form>, then submit() will not work." }, { "code": null, "e": 1877, "s": 1701, "text": "Thus we see that click() works for both type buttons irrespective of the fact that the button is inside or outside of <form>. Let us take up the below form for implementation." }, { "code": null, "e": 1912, "s": 1877, "text": "Code Implementation with submit()." }, { "code": null, "e": 2740, "s": 1912, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class SubmitForm{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.facebook.com/\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify elements\n driver.findElement(By.id(\"email\")).sendKeys(\"[email protected]\");\n driver.findElement(By.id(\"pass\")).sendKeys(\"123456\");\n // submitting form with submit()\n driver.findElement(By.id(\"pass\")).submit();\n driver.quit()\n }\n}" }, { "code": null, "e": 2774, "s": 2740, "text": "Code Implementation with click()." }, { "code": null, "e": 3602, "s": 2774, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ClickForm{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.facebook.com/\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify elements\n driver.findElement(By.id(\"email\")).sendKeys(\"[email protected]\");\n driver.findElement(By.id(\"pass\")).sendKeys(\"123456\");\n // submitting form with click()\n driver.findElement(By.name(\"login\")).click();\n driver.quit()\n }\n}" } ]
Cleaning & Preprocessing Text Data for Sentiment Analysis | by Muriel Kosaka | Towards Data Science
Sentiment analysis for text data combined natural language processing (NLP) and machine learning techniques to assign weighted sentiment scores to the systems, topics, or categories within a sentence or document. In business setting, sentiment analysis is extremely helpful as it can help understand customer experiences, gauge public opinion, and monitor brand and product reputation. For this example, we are examining a dataset of Amazon Alexa reviews which can be found here on Kaggle. First, let’s import the necessary libraries: import reimport pandas as pdfrom nltk.corpus import stopwordsfrom wordcloud import WordCloud, STOPWORDSimport spacy Next, let’s read in our .csv file and see the first few rows: df=pd.read_csv('amazon_alexa.tsv', sep='\t')df.head() After further examining, we see that rating ranges from 1–5 and feedback is categorized as either 0 or 1 for each review, but for right now we’ll just focus on the verified_reviews column. I initialize Spacy ‘en’ model, keeping only the component need for lemmatization and creating an engine: nlp = spacy.load('en', disable=['parser', 'ner']) The first pre-processing step we’ll do is transform all reviews in verified_reviews into lower case and create a new column new_reviews. df['new_reviews'] = df['verified_reviews'].apply(lambda x: " ".join(x.lower() for x in x.split()))df['new_reviews'].head() Next, we will remove punctuation: df['new_reviews'] = df['new_reviews'].str.replace('[^\w\s]','')df['new_reviews'].head() Upon further inspection of the reviews, I noticed there were emoji’s used so I will remove those using a function provided by Kamil Slowikowski and apply it to new_reviews. # REFERENCE : https://gist.github.com/slowkow/7a7f61f495e3dbb7e3d767f97bd7304bdef remove_emoji(text): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" "]+", flags=re.UNICODE) return emoji_pattern.sub(r'', text)df['new_reviews'] = df['new_reviews'].apply(lambda x: remove_emoji(x)) After some transformation, the reviews are much cleaner, but we still have some words that we should remove, namely the stopwords. Stopwords are commonly used words (i.e. “the”, “a”, “an”) that do not add meaning to a sentence and can be ignored without having a drastic effect on the meaning of the sentence. stop = stopwords.words('english')df['new_reviews'] = df['new_reviews'].apply(lambda x: " ".join(x for x in x.split() if x not in stop))df.head(20) Lastly, we will implement lemmatization using Spacy so that we can count the appearance of each word. Lemmatization removes the grammar tense and transforms each word into its original form. Another way of converting words to its original form is called stemming. While stemming takes the linguistic root of a word, lemmatization is taking a word into its original lemma. For example, if we performed stemming on the word “apples”, the result would be “appl”, whereas lemmatization would give us “apple”. Therefore I prefer lemmatization over stemming, as its much easier to interpret. def space(comment): doc = nlp(comment) return " ".join([token.lemma_ for token in doc])df['new_reviews']= df['new_reviews'].apply(space)df.head(20) To review, the steps used to complete preprocessing our data were: Make text lowercaseRemove punctuationRemove emoji’sRemove stopwordsLemmatization Make text lowercase Remove punctuation Remove emoji’s Remove stopwords Lemmatization Now our text is ready for analysis! There are a lot of ways of preprocessing unstructured text data to make it understandable for computers for analysis. For the next step, I will explore sentiment analysis using VADER (Valence Aware Dictionary and sEntiment Reasoner). Thank you for reading! :)
[ { "code": null, "e": 558, "s": 172, "text": "Sentiment analysis for text data combined natural language processing (NLP) and machine learning techniques to assign weighted sentiment scores to the systems, topics, or categories within a sentence or document. In business setting, sentiment analysis is extremely helpful as it can help understand customer experiences, gauge public opinion, and monitor brand and product reputation." }, { "code": null, "e": 662, "s": 558, "text": "For this example, we are examining a dataset of Amazon Alexa reviews which can be found here on Kaggle." }, { "code": null, "e": 707, "s": 662, "text": "First, let’s import the necessary libraries:" }, { "code": null, "e": 823, "s": 707, "text": "import reimport pandas as pdfrom nltk.corpus import stopwordsfrom wordcloud import WordCloud, STOPWORDSimport spacy" }, { "code": null, "e": 885, "s": 823, "text": "Next, let’s read in our .csv file and see the first few rows:" }, { "code": null, "e": 939, "s": 885, "text": "df=pd.read_csv('amazon_alexa.tsv', sep='\\t')df.head()" }, { "code": null, "e": 1128, "s": 939, "text": "After further examining, we see that rating ranges from 1–5 and feedback is categorized as either 0 or 1 for each review, but for right now we’ll just focus on the verified_reviews column." }, { "code": null, "e": 1233, "s": 1128, "text": "I initialize Spacy ‘en’ model, keeping only the component need for lemmatization and creating an engine:" }, { "code": null, "e": 1283, "s": 1233, "text": "nlp = spacy.load('en', disable=['parser', 'ner'])" }, { "code": null, "e": 1420, "s": 1283, "text": "The first pre-processing step we’ll do is transform all reviews in verified_reviews into lower case and create a new column new_reviews." }, { "code": null, "e": 1543, "s": 1420, "text": "df['new_reviews'] = df['verified_reviews'].apply(lambda x: \" \".join(x.lower() for x in x.split()))df['new_reviews'].head()" }, { "code": null, "e": 1577, "s": 1543, "text": "Next, we will remove punctuation:" }, { "code": null, "e": 1665, "s": 1577, "text": "df['new_reviews'] = df['new_reviews'].str.replace('[^\\w\\s]','')df['new_reviews'].head()" }, { "code": null, "e": 1838, "s": 1665, "text": "Upon further inspection of the reviews, I noticed there were emoji’s used so I will remove those using a function provided by Kamil Slowikowski and apply it to new_reviews." }, { "code": null, "e": 2514, "s": 1838, "text": "# REFERENCE : https://gist.github.com/slowkow/7a7f61f495e3dbb7e3d767f97bd7304bdef remove_emoji(text): emoji_pattern = re.compile(\"[\" u\"\\U0001F600-\\U0001F64F\" # emoticons u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols u\"\\U0001F1E0-\\U0001F1FF\" # flags u\"\\U00002702-\\U000027B0\" u\"\\U000024C2-\\U0001F251\" \"]+\", flags=re.UNICODE) return emoji_pattern.sub(r'', text)df['new_reviews'] = df['new_reviews'].apply(lambda x: remove_emoji(x))" }, { "code": null, "e": 2824, "s": 2514, "text": "After some transformation, the reviews are much cleaner, but we still have some words that we should remove, namely the stopwords. Stopwords are commonly used words (i.e. “the”, “a”, “an”) that do not add meaning to a sentence and can be ignored without having a drastic effect on the meaning of the sentence." }, { "code": null, "e": 2971, "s": 2824, "text": "stop = stopwords.words('english')df['new_reviews'] = df['new_reviews'].apply(lambda x: \" \".join(x for x in x.split() if x not in stop))df.head(20)" }, { "code": null, "e": 3557, "s": 2971, "text": "Lastly, we will implement lemmatization using Spacy so that we can count the appearance of each word. Lemmatization removes the grammar tense and transforms each word into its original form. Another way of converting words to its original form is called stemming. While stemming takes the linguistic root of a word, lemmatization is taking a word into its original lemma. For example, if we performed stemming on the word “apples”, the result would be “appl”, whereas lemmatization would give us “apple”. Therefore I prefer lemmatization over stemming, as its much easier to interpret." }, { "code": null, "e": 3711, "s": 3557, "text": "def space(comment): doc = nlp(comment) return \" \".join([token.lemma_ for token in doc])df['new_reviews']= df['new_reviews'].apply(space)df.head(20)" }, { "code": null, "e": 3778, "s": 3711, "text": "To review, the steps used to complete preprocessing our data were:" }, { "code": null, "e": 3859, "s": 3778, "text": "Make text lowercaseRemove punctuationRemove emoji’sRemove stopwordsLemmatization" }, { "code": null, "e": 3879, "s": 3859, "text": "Make text lowercase" }, { "code": null, "e": 3898, "s": 3879, "text": "Remove punctuation" }, { "code": null, "e": 3913, "s": 3898, "text": "Remove emoji’s" }, { "code": null, "e": 3930, "s": 3913, "text": "Remove stopwords" }, { "code": null, "e": 3944, "s": 3930, "text": "Lemmatization" }, { "code": null, "e": 4214, "s": 3944, "text": "Now our text is ready for analysis! There are a lot of ways of preprocessing unstructured text data to make it understandable for computers for analysis. For the next step, I will explore sentiment analysis using VADER (Valence Aware Dictionary and sEntiment Reasoner)." } ]
Avoid Unexpected string concatenation in JavaScript?
To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks. We have the following − const concatValue = 'John,David,Mike'; var friendNames= `${concatValue}`; The above value is concatenated with a string and number − var studentNameWithFriends=` ${concatValue}| 'Carol' | 24 ` ; Following is the complete JavaScript code for concatenation − const concatValue = 'John,David,Mike'; var friendNames= `${concatValue}`; var studentNameWithFriends=` ${concatValue}| 'Carol' | 24 ` ; console.log(friendNames); console.log(studentNameWithFriends); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo37.js This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo37.js John,David,Mike John,David,Mike| 'Carol' | 24
[ { "code": null, "e": 1178, "s": 1062, "text": "To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks." }, { "code": null, "e": 1202, "s": 1178, "text": "We have the following −" }, { "code": null, "e": 1276, "s": 1202, "text": "const concatValue = 'John,David,Mike';\nvar friendNames= `${concatValue}`;" }, { "code": null, "e": 1335, "s": 1276, "text": "The above value is concatenated with a string and number −" }, { "code": null, "e": 1397, "s": 1335, "text": "var studentNameWithFriends=` ${concatValue}| 'Carol' | 24 ` ;" }, { "code": null, "e": 1459, "s": 1397, "text": "Following is the complete JavaScript code for concatenation −" }, { "code": null, "e": 1658, "s": 1459, "text": "const concatValue = 'John,David,Mike';\nvar friendNames= `${concatValue}`;\nvar studentNameWithFriends=` ${concatValue}| 'Carol' | 24 ` ;\nconsole.log(friendNames);\nconsole.log(studentNameWithFriends);" }, { "code": null, "e": 1724, "s": 1658, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1742, "s": 1724, "text": "node fileName.js." }, { "code": null, "e": 1774, "s": 1742, "text": "Here, my file name is demo37.js" }, { "code": null, "e": 1815, "s": 1774, "text": "This will produce the following output −" }, { "code": null, "e": 1910, "s": 1815, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo37.js\nJohn,David,Mike\nJohn,David,Mike| 'Carol' | 24" } ]
How to set the current figure in Matplotlib?
Using the figure() method, we can set the current figure. Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”. Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”. Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”. Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”. Using plt.show(), show the figures. Using plt.show(), show the figures. from matplotlib import pyplot as plt plt.figure("Welcome to figure 1") plt.figure("Welcome to figure 2") # Active Figure plt.show()
[ { "code": null, "e": 1120, "s": 1062, "text": "Using the figure() method, we can set the current figure." }, { "code": null, "e": 1218, "s": 1120, "text": "Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”." }, { "code": null, "e": 1316, "s": 1218, "text": "Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”." }, { "code": null, "e": 1414, "s": 1316, "text": "Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”." }, { "code": null, "e": 1512, "s": 1414, "text": "Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”." }, { "code": null, "e": 1548, "s": 1512, "text": "Using plt.show(), show the figures." }, { "code": null, "e": 1584, "s": 1548, "text": "Using plt.show(), show the figures." }, { "code": null, "e": 1721, "s": 1584, "text": "from matplotlib import pyplot as plt\n\nplt.figure(\"Welcome to figure 1\")\nplt.figure(\"Welcome to figure 2\") # Active Figure\n\nplt.show()" } ]
Causal Inference. Answering causal questions with Python | by Shawhin Talebi | Towards Data Science
This is the second post in a series of three on causality. In the last post I introduced this “new science of cause and effect” [1], and gave a flavor for causal inference and causal discovery. In this post we will dive further into some details of causal inference and finish with a concrete example in Python. In the last post I discussed how causality can be represented mathematically via Structural Causal Models (SCMs). SCMs consist of two parts: a graph, which visualizes causal connections, and equations, which express the details of the connections. As a recap, a graph is a mathematical construction that consists of vertices (nodes) and edges (links). Here, I will use the terms graph and network interchangeably. SCMs use a special kind of graph, called a Directed Acyclic Graph (DAG), for which all edges are directed and no cycles exist. DAGs are a common starting place for causal inference. An ambiguity for me when first exploring this subject was the difference between Bayesian networks and causal networks. So I will briefly mention the difference. The enlightened reader can feel free to skip this section. On the surface, Bayesian and causal networks are completely identical. However, the difference lies in their interpretations. Consider the example in the figure below. Here we have a network with 2 nodes (fire icon and smoke icon) and 1 edge (arrow pointing from fire to smoke). This network can be both a Bayesian or causal network. The key distinction, however, is when interpreting this network. For a Bayesian network, we view the nodes as variables and the arrow as a conditional probability, namely the probability of smoke given information about fire. When interpreting this as a causal network, we still view nodes as variables, however the arrow indicates a causal connection. In this case both interpretations are valid. However, if we were to flip the edge direction, the causal network interpretation would be invalid, since smoke does not cause fire. Causal inference aims at answering causal questions as opposed to just statistical ones. There are countless applications of causal inference. Answering any of the questions below falls under the umbrella of causal inference. Did the treatment directly help those who took it? Was it the marketing campaign that lead to increased sales this month or the holiday? How big of an effect would increasing wages have on productivity? These are significant and practical questions that may not be easily answered using more traditional approaches (e.g. linear regression or standard machine learning). I hope to illustrate how causal inference can help answering these questions through what I will call the 3 gifts of causal inference. In the last post, I defined causality in terms of interventions. Omitting some technicalities, it was said that X causes Y if an intervention in X results in a change in Y, while an intervention in Y does not necessarily result in a change in X. Interventions are easy to understand in the real world (like when your friend’s candy habit gets out of control), however how does that fit into causality’s mathematical representation? Enter the do-operator. The do-operator is a mathematical representation of a physical intervention. If we start with the model Z → X → Y, we can simulate an intervention in X by deleting all the incoming arrows to X, and manually setting X to some value x_0. The power of do-operator is that it allows us to simulate experiments, given we know the details of the causal connections. For example, suppose we want to ask, will increasing the marketing budget boost sales? If we are armed with a causal model that includes marketing spend and sales, we can simulate what would happen if we were to increase marketing spend, and assess whether the change in sales (if any) is worth it. In other words, we can evaluate the causal effect of marketing on sales. More on causal effects later. A major contribution of Pearl and colleagues are the rules of do-calculus. This is a complete set of rules that outline how to use the do-operator. Notably, do-calculus can translate interventional distributions (i.e. probabilities with the do-operator) into observational distributions (i.e. probabilities without the do-operator). This can be seen by rules 2 and 3 in the figure below. Notice the notation. P(Y|X) is the conditional probability that we are all familiar with, that is, the probability of Y given an observation of X. While, P(Y|do(X)) is the probability of Y given an intervention in X. The do-operator is a key tool in the causal inference toolbox. In fact, the next 2 gifts rely on the do-operator. Confounding is a notion thrown around in statistics. Although I didn’t call it by name, this appeared in the previous post via Simpson’s paradox. A simple example of confounding is shown in the figure below. In this example, age is a confounder of education and wealth. In other words, if trying to evaluate the impact of education on wealth one would need to adjust for age. Adjusting for (or conditioning on) age just means that when looking at age, education, and wealth data, one would compare data points within age groups, not between age groups. If age were not adjusted for, it would not be clear whether education is a true cause of wealth or just a correlate of wealth. In other words, you couldn’t tell whether education directly affects wealth, or just has a common cause with it. For simple examples, confounding is pretty straight forward when looking at a DAG. For 3 variables, the confounder is the variable that points to 2 other variables. But what about for more complicated problems? This is where the do-operator provides clarity. Pearl uses the do-operator to define confounding in a clear cut way. He states, confounding is anything that leads to P(Y|X) being different than P(Y|do(X)) [1]. This final gift is the main attraction of causal inference. In life, we not only ask ourselves why, but how much? Estimating causal effects boils down to answering this 2nd question. Consider graduate school. It is one thing to know that people with graduate degrees make (mostly) more money than those without graduate degrees, but a natural question is, how much of that is attributable to their degree? In other words, what is the treatment effect of a graduate degree on income? I will use answering this question as an opportunity to work through a concrete example of using Python to do causal inference. In this example, we will use the Microsoft DoWhy library for causal inference [3]. The goal here is to estimate the causal effect of having a graduate degree on making more than $50k annually. Data is obtained from the UCI machine learning repository [4]. Example code and data can be found at the GitHub repo. It is important to stress the starting point of all causal inference is a causal model. Here we assume income has only two causes: age and education, where age also is a cause of education. Clearly, this simple model may be missing other important factors. We we will investigate alternative models in the next post on causal discovery. For now, however, we will focus on this simplified case. First we load libraries and data. If you do not have the libraries check out the requirements.txt in the repo. # Import librariesimport pickleimport matplotlib.pyplot as pltimport econmlimport dowhyfrom dowhy import CausalModel# Load Datadf = pickle.load( open( "df_causal_inference.p", "rb" ) ) Again the first step is defining our causal model i.e. DAG. DoWhy makes it easy to create and view models. # Define causal modelmodel=CausalModel(data = df, treatment= "hasGraduateDegree", outcome= "greaterThan50k", common_causes="age", )# View modelmodel.view_model() from IPython.display import Image, display display(Image(filename="causal_model.png")) Next we need an estimand. This is basically a recipe that gives us our desired causal effect. In other words, it tells us how to compute the effect of education on income. # Generate estimandidentified_estimand= model.identify_effect(proceed_when_unidentifiable=True)print(identified_estimand) Finally, we compute the causal effect based on the estimand. Here we use a meta-learner [5] from the EconML library, which estimates conditional average treatment effects for discrete targets. # Compute causal effect using metalearneridentified_estimand_experiment = model.identify_effect(proceed_when_unidentifiable=True)from sklearn.ensemble import RandomForestRegressormetalearner_estimate = model.estimate_effect(identified_estimand_experiment, method_name="backdoor.econml.metalearners.TLearner",confidence_intervals=False,method_params={ "init_params":{'models': RandomForestRegressor()}, "fit_params":{} })print(metalearner_estimate) The average causal effect is about 0.20. This can be interpreted as, having a graduate degree increases your probability of making more than $50k annually by 20%. Noting this is the average effect, it is important to consider the full distribution of values to assess whether the average is representative. # Print histogram of causal effectsplt.hist(metalearner_estimate.cate_estimates) In the figure above we see the distribution of causal effects across samples. Clearly, the distribution is not Gaussian. Which tells us the mean is not representative of the overall distribution. Further analysis diving into cohorts based on causal effects may help uncover actionable information about “who” benefits most from a graduate degree. Regardless, solely basing a decision to go to grad school on potential income, may be an indication you don’t really want go to grad school. 🤷🏽‍♀️ Causal inference is a powerful tool for answering natural questions that more traditional approaches may not resolve. Here I sketched some big ideas from causal inference, and worked through a concrete example with code. As stated before, the starting point for all causal inference is a causal model. Usually, however, we don’t have a good causal model in hand. This is where causal discovery can be helpful, which is topic of the next post. My website | Example code | 1st post: Causality | 3rd post: Causal Discovery [1] The Book of Why: The New Science of Cause and Effect by Judea Pearl [2] Pearl, J. (2012). The Do-Calculus Revisited. arXiv:1210.4852 [cs.AI] [3] Amit Sharma, Emre Kiciman. DoWhy: An End-to-End Library for Causal Inference. 2020. https://arxiv.org/abs/2011.04216 [4] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science. https://archive.ics.uci.edu/ml/datasets/census+income [5] Künzel, Sören R., et al. “Metalearners for Estimating Heterogeneous Treatment Effects Using Machine Learning.” Proceedings of the National Academy of Sciences, vol. 116, no. 10, Mar. 2019, pp. 4156–65. www.pnas.org, https://doi.org/10.1073/pnas.1804597116.
[ { "code": null, "e": 484, "s": 172, "text": "This is the second post in a series of three on causality. In the last post I introduced this “new science of cause and effect” [1], and gave a flavor for causal inference and causal discovery. In this post we will dive further into some details of causal inference and finish with a concrete example in Python." }, { "code": null, "e": 732, "s": 484, "text": "In the last post I discussed how causality can be represented mathematically via Structural Causal Models (SCMs). SCMs consist of two parts: a graph, which visualizes causal connections, and equations, which express the details of the connections." }, { "code": null, "e": 1080, "s": 732, "text": "As a recap, a graph is a mathematical construction that consists of vertices (nodes) and edges (links). Here, I will use the terms graph and network interchangeably. SCMs use a special kind of graph, called a Directed Acyclic Graph (DAG), for which all edges are directed and no cycles exist. DAGs are a common starting place for causal inference." }, { "code": null, "e": 1301, "s": 1080, "text": "An ambiguity for me when first exploring this subject was the difference between Bayesian networks and causal networks. So I will briefly mention the difference. The enlightened reader can feel free to skip this section." }, { "code": null, "e": 1469, "s": 1301, "text": "On the surface, Bayesian and causal networks are completely identical. However, the difference lies in their interpretations. Consider the example in the figure below." }, { "code": null, "e": 1635, "s": 1469, "text": "Here we have a network with 2 nodes (fire icon and smoke icon) and 1 edge (arrow pointing from fire to smoke). This network can be both a Bayesian or causal network." }, { "code": null, "e": 2166, "s": 1635, "text": "The key distinction, however, is when interpreting this network. For a Bayesian network, we view the nodes as variables and the arrow as a conditional probability, namely the probability of smoke given information about fire. When interpreting this as a causal network, we still view nodes as variables, however the arrow indicates a causal connection. In this case both interpretations are valid. However, if we were to flip the edge direction, the causal network interpretation would be invalid, since smoke does not cause fire." }, { "code": null, "e": 2392, "s": 2166, "text": "Causal inference aims at answering causal questions as opposed to just statistical ones. There are countless applications of causal inference. Answering any of the questions below falls under the umbrella of causal inference." }, { "code": null, "e": 2443, "s": 2392, "text": "Did the treatment directly help those who took it?" }, { "code": null, "e": 2529, "s": 2443, "text": "Was it the marketing campaign that lead to increased sales this month or the holiday?" }, { "code": null, "e": 2595, "s": 2529, "text": "How big of an effect would increasing wages have on productivity?" }, { "code": null, "e": 2897, "s": 2595, "text": "These are significant and practical questions that may not be easily answered using more traditional approaches (e.g. linear regression or standard machine learning). I hope to illustrate how causal inference can help answering these questions through what I will call the 3 gifts of causal inference." }, { "code": null, "e": 3352, "s": 2897, "text": "In the last post, I defined causality in terms of interventions. Omitting some technicalities, it was said that X causes Y if an intervention in X results in a change in Y, while an intervention in Y does not necessarily result in a change in X. Interventions are easy to understand in the real world (like when your friend’s candy habit gets out of control), however how does that fit into causality’s mathematical representation? Enter the do-operator." }, { "code": null, "e": 3588, "s": 3352, "text": "The do-operator is a mathematical representation of a physical intervention. If we start with the model Z → X → Y, we can simulate an intervention in X by deleting all the incoming arrows to X, and manually setting X to some value x_0." }, { "code": null, "e": 4114, "s": 3588, "text": "The power of do-operator is that it allows us to simulate experiments, given we know the details of the causal connections. For example, suppose we want to ask, will increasing the marketing budget boost sales? If we are armed with a causal model that includes marketing spend and sales, we can simulate what would happen if we were to increase marketing spend, and assess whether the change in sales (if any) is worth it. In other words, we can evaluate the causal effect of marketing on sales. More on causal effects later." }, { "code": null, "e": 4262, "s": 4114, "text": "A major contribution of Pearl and colleagues are the rules of do-calculus. This is a complete set of rules that outline how to use the do-operator." }, { "code": null, "e": 4502, "s": 4262, "text": "Notably, do-calculus can translate interventional distributions (i.e. probabilities with the do-operator) into observational distributions (i.e. probabilities without the do-operator). This can be seen by rules 2 and 3 in the figure below." }, { "code": null, "e": 4719, "s": 4502, "text": "Notice the notation. P(Y|X) is the conditional probability that we are all familiar with, that is, the probability of Y given an observation of X. While, P(Y|do(X)) is the probability of Y given an intervention in X." }, { "code": null, "e": 4833, "s": 4719, "text": "The do-operator is a key tool in the causal inference toolbox. In fact, the next 2 gifts rely on the do-operator." }, { "code": null, "e": 5041, "s": 4833, "text": "Confounding is a notion thrown around in statistics. Although I didn’t call it by name, this appeared in the previous post via Simpson’s paradox. A simple example of confounding is shown in the figure below." }, { "code": null, "e": 5386, "s": 5041, "text": "In this example, age is a confounder of education and wealth. In other words, if trying to evaluate the impact of education on wealth one would need to adjust for age. Adjusting for (or conditioning on) age just means that when looking at age, education, and wealth data, one would compare data points within age groups, not between age groups." }, { "code": null, "e": 5626, "s": 5386, "text": "If age were not adjusted for, it would not be clear whether education is a true cause of wealth or just a correlate of wealth. In other words, you couldn’t tell whether education directly affects wealth, or just has a common cause with it." }, { "code": null, "e": 5837, "s": 5626, "text": "For simple examples, confounding is pretty straight forward when looking at a DAG. For 3 variables, the confounder is the variable that points to 2 other variables. But what about for more complicated problems?" }, { "code": null, "e": 6047, "s": 5837, "text": "This is where the do-operator provides clarity. Pearl uses the do-operator to define confounding in a clear cut way. He states, confounding is anything that leads to P(Y|X) being different than P(Y|do(X)) [1]." }, { "code": null, "e": 6230, "s": 6047, "text": "This final gift is the main attraction of causal inference. In life, we not only ask ourselves why, but how much? Estimating causal effects boils down to answering this 2nd question." }, { "code": null, "e": 6530, "s": 6230, "text": "Consider graduate school. It is one thing to know that people with graduate degrees make (mostly) more money than those without graduate degrees, but a natural question is, how much of that is attributable to their degree? In other words, what is the treatment effect of a graduate degree on income?" }, { "code": null, "e": 6658, "s": 6530, "text": "I will use answering this question as an opportunity to work through a concrete example of using Python to do causal inference." }, { "code": null, "e": 6969, "s": 6658, "text": "In this example, we will use the Microsoft DoWhy library for causal inference [3]. The goal here is to estimate the causal effect of having a graduate degree on making more than $50k annually. Data is obtained from the UCI machine learning repository [4]. Example code and data can be found at the GitHub repo." }, { "code": null, "e": 7363, "s": 6969, "text": "It is important to stress the starting point of all causal inference is a causal model. Here we assume income has only two causes: age and education, where age also is a cause of education. Clearly, this simple model may be missing other important factors. We we will investigate alternative models in the next post on causal discovery. For now, however, we will focus on this simplified case." }, { "code": null, "e": 7474, "s": 7363, "text": "First we load libraries and data. If you do not have the libraries check out the requirements.txt in the repo." }, { "code": null, "e": 7659, "s": 7474, "text": "# Import librariesimport pickleimport matplotlib.pyplot as pltimport econmlimport dowhyfrom dowhy import CausalModel# Load Datadf = pickle.load( open( \"df_causal_inference.p\", \"rb\" ) )" }, { "code": null, "e": 7766, "s": 7659, "text": "Again the first step is defining our causal model i.e. DAG. DoWhy makes it easy to create and view models." }, { "code": null, "e": 8119, "s": 7766, "text": "# Define causal modelmodel=CausalModel(data = df, treatment= \"hasGraduateDegree\", outcome= \"greaterThan50k\", common_causes=\"age\", )# View modelmodel.view_model() from IPython.display import Image, display display(Image(filename=\"causal_model.png\"))" }, { "code": null, "e": 8291, "s": 8119, "text": "Next we need an estimand. This is basically a recipe that gives us our desired causal effect. In other words, it tells us how to compute the effect of education on income." }, { "code": null, "e": 8413, "s": 8291, "text": "# Generate estimandidentified_estimand= model.identify_effect(proceed_when_unidentifiable=True)print(identified_estimand)" }, { "code": null, "e": 8606, "s": 8413, "text": "Finally, we compute the causal effect based on the estimand. Here we use a meta-learner [5] from the EconML library, which estimates conditional average treatment effects for discrete targets." }, { "code": null, "e": 9103, "s": 8606, "text": "# Compute causal effect using metalearneridentified_estimand_experiment = model.identify_effect(proceed_when_unidentifiable=True)from sklearn.ensemble import RandomForestRegressormetalearner_estimate = model.estimate_effect(identified_estimand_experiment, method_name=\"backdoor.econml.metalearners.TLearner\",confidence_intervals=False,method_params={ \"init_params\":{'models': RandomForestRegressor()}, \"fit_params\":{} })print(metalearner_estimate)" }, { "code": null, "e": 9410, "s": 9103, "text": "The average causal effect is about 0.20. This can be interpreted as, having a graduate degree increases your probability of making more than $50k annually by 20%. Noting this is the average effect, it is important to consider the full distribution of values to assess whether the average is representative." }, { "code": null, "e": 9491, "s": 9410, "text": "# Print histogram of causal effectsplt.hist(metalearner_estimate.cate_estimates)" }, { "code": null, "e": 9838, "s": 9491, "text": "In the figure above we see the distribution of causal effects across samples. Clearly, the distribution is not Gaussian. Which tells us the mean is not representative of the overall distribution. Further analysis diving into cohorts based on causal effects may help uncover actionable information about “who” benefits most from a graduate degree." }, { "code": null, "e": 9985, "s": 9838, "text": "Regardless, solely basing a decision to go to grad school on potential income, may be an indication you don’t really want go to grad school. 🤷🏽‍♀️" }, { "code": null, "e": 10428, "s": 9985, "text": "Causal inference is a powerful tool for answering natural questions that more traditional approaches may not resolve. Here I sketched some big ideas from causal inference, and worked through a concrete example with code. As stated before, the starting point for all causal inference is a causal model. Usually, however, we don’t have a good causal model in hand. This is where causal discovery can be helpful, which is topic of the next post." }, { "code": null, "e": 10505, "s": 10428, "text": "My website | Example code | 1st post: Causality | 3rd post: Causal Discovery" }, { "code": null, "e": 10577, "s": 10505, "text": "[1] The Book of Why: The New Science of Cause and Effect by Judea Pearl" }, { "code": null, "e": 10650, "s": 10577, "text": "[2] Pearl, J. (2012). The Do-Calculus Revisited. arXiv:1210.4852 [cs.AI]" }, { "code": null, "e": 10771, "s": 10650, "text": "[3] Amit Sharma, Emre Kiciman. DoWhy: An End-to-End Library for Causal Inference. 2020. https://arxiv.org/abs/2011.04216" }, { "code": null, "e": 11006, "s": 10771, "text": "[4] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science. https://archive.ics.uci.edu/ml/datasets/census+income" } ]
Javascript Interview Questions
Dear readers, these JavaScript Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of JavaScript. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers. Following are the features of JavaScript − JavaScript is a lightweight, interpreted programming language. JavaScript is a lightweight, interpreted programming language. JavaScript is designed for creating network-centric applications. JavaScript is designed for creating network-centric applications. JavaScript is complementary to and integrated with Java. JavaScript is complementary to and integrated with Java. JavaScript is is complementary to and integrated with HTML. JavaScript is is complementary to and integrated with HTML. JavaScript is open and cross-platform. JavaScript is open and cross-platform. Following are the advantages of using JavaScript − Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something. Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something. Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors. Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors. We can not treat JavaScript as a full fledged programming language. It lacks the following important features − Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason. Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason. JavaScript can not be used for Networking applications because there is no such support available. JavaScript can not be used for Networking applications because there is no such support available. JavaScript doesn't have any multithreading or multiprocess capabilities. JavaScript doesn't have any multithreading or multiprocess capabilities. Yes! JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. JavaScript supports Object concept very well. You can create an object using the object literal as follows − var emp = { name: "Zara", age: 10 }; You can write and read properties of an object using the dot notation as follows − // Getting object properties emp.name // ==> Zara emp.age // ==> 10 // Setting object properties emp.name = "Daisy" // <== Daisy emp.age = 20 // <== 20 You can define arrays using the array literal as follows − var x = []; var y = [1, 2, 3, 4, 5]; An array has a length property that is useful for iteration. We can read elements of an array as follows − var x = [1, 2, 3, 4, 5]; for (var i = 0; i < x.length; i++) { // Do something with x[i] } A named function has a name when it is defined. A named function can be defined using function keyword as follows − function named(){ // do some stuff here } A function in JavaScript can be either named or anonymous. An anonymous function can be defined in similar way as a normal function but it would not have any name. Yes! An anonymous function can be assigned to a variable. Yes! An anonymous function can be passed as an argument to another function. JavaScript variable arguments represents the arguments passed to a function. Using typeof operator, we can get the type of arguments passed to a function. For example − function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(1); //==> "number", 1 func("1", "2", "3"); //==> "string", 3 Using arguments.length property, we can get the total number of arguments passed to a function. For example − function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(1); //==> "number", 1 func("1", "2", "3"); //==> "string", 3 The arguments object has a callee property, which refers to the function you're inside of. For example − function func() { return arguments.callee; } func(); // ==> func JavaScript famous keyword this always refers to the current context. The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes. Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code. Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. A local variable takes precedence over a global variable with the same name. A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered. Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them − function create() { var counter = 0; return { increment: function() { counter++; }, print: function() { console.log(counter); } } } var c = create(); c.increment(); c.print(); // ==> 1 charAt() method returns the character at the specified index. concat() method returns the character at the specified index. forEach() method calls a function for each element in the array. indexOf() method returns the index within the calling String object of the first occurrence of the specified value, or −1 if not found. length() method returns the length of the string. pop() method removes the last element from an array and returns that element. push() method adds one or more elements to the end of an array and returns the new length of the array. reverse() method reverses the order of the elements of an array −− the first becomes the last, and the last becomes the first. sort() method sorts the elements of an array. substr() method returns the characters in a string beginning at the specified location through the specified number of characters. toLowerCase() method returns the calling string value converted to lower case. toUpperCase() method returns the calling string value converted to upper case. toString() method returns the string representation of the number's value. While naming your variables in JavaScript keep following rules in mind. You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid. JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one. JavaScript variable names are case sensitive. For example, Name and name are two different variables. The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand. The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation. It returns "object". JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page. The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this − Syntax − document.cookie = "key1 = value1; key2 = value2; expires = date"; Here expires attribute is option. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies' value will not be accessible. Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value. You can use strings' split() function to break the string into key and values. Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past. his is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows − <head> <script type="text/javascript"> <!-- window.location="http://www.newlocation.com"; //--> </script> </head> JavaScript helps you to implement this functionality using print function of window object. The JavaScript print function window.print() will print the current web page when executed. The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ). Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time. he Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class. Syntax − Creating a number object − var val = new Number(number); If the argument cannot be converted into a number, it returns NaN (Not-a-Number). The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions. You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors. The onerror event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page. The onerror event handler provides three pieces of information to identify the exact nature of the error − Error message − The same message that the browser would display for the given error. Error message − The same message that the browser would display for the given error. URL − The file in which the error occurred. URL − The file in which the error occurred. Line number − The line number in the given URL that caused the error. Line number − The line number in the given URL that caused the error. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2910, "s": 2466, "text": "Dear readers, these JavaScript Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of JavaScript. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 3079, "s": 2910, "text": "JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages." }, { "code": null, "e": 3194, "s": 3079, "text": "The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers." }, { "code": null, "e": 3237, "s": 3194, "text": "Following are the features of JavaScript −" }, { "code": null, "e": 3300, "s": 3237, "text": "JavaScript is a lightweight, interpreted programming language." }, { "code": null, "e": 3363, "s": 3300, "text": "JavaScript is a lightweight, interpreted programming language." }, { "code": null, "e": 3429, "s": 3363, "text": "JavaScript is designed for creating network-centric applications." }, { "code": null, "e": 3495, "s": 3429, "text": "JavaScript is designed for creating network-centric applications." }, { "code": null, "e": 3552, "s": 3495, "text": "JavaScript is complementary to and integrated with Java." }, { "code": null, "e": 3609, "s": 3552, "text": "JavaScript is complementary to and integrated with Java." }, { "code": null, "e": 3669, "s": 3609, "text": "JavaScript is is complementary to and integrated with HTML." }, { "code": null, "e": 3729, "s": 3669, "text": "JavaScript is is complementary to and integrated with HTML." }, { "code": null, "e": 3768, "s": 3729, "text": "JavaScript is open and cross-platform." }, { "code": null, "e": 3807, "s": 3768, "text": "JavaScript is open and cross-platform." }, { "code": null, "e": 3858, "s": 3807, "text": "Following are the advantages of using JavaScript −" }, { "code": null, "e": 4020, "s": 3858, "text": "Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server." }, { "code": null, "e": 4182, "s": 4020, "text": "Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server." }, { "code": null, "e": 4311, "s": 4182, "text": "Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something." }, { "code": null, "e": 4440, "s": 4311, "text": "Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something." }, { "code": null, "e": 4583, "s": 4440, "text": "Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard." }, { "code": null, "e": 4726, "s": 4583, "text": "Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard." }, { "code": null, "e": 4879, "s": 4726, "text": "Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors." }, { "code": null, "e": 5032, "s": 4879, "text": "Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors." }, { "code": null, "e": 5144, "s": 5032, "text": "We can not treat JavaScript as a full fledged programming language. It lacks the following important features −" }, { "code": null, "e": 5255, "s": 5144, "text": "Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason." }, { "code": null, "e": 5366, "s": 5255, "text": "Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason." }, { "code": null, "e": 5465, "s": 5366, "text": "JavaScript can not be used for Networking applications because there is no such support available." }, { "code": null, "e": 5564, "s": 5465, "text": "JavaScript can not be used for Networking applications because there is no such support available." }, { "code": null, "e": 5637, "s": 5564, "text": "JavaScript doesn't have any multithreading or multiprocess capabilities." }, { "code": null, "e": 5710, "s": 5637, "text": "JavaScript doesn't have any multithreading or multiprocess capabilities." }, { "code": null, "e": 5910, "s": 5710, "text": "Yes! JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters." }, { "code": null, "e": 6019, "s": 5910, "text": "JavaScript supports Object concept very well. You can create an object using the object literal as follows −" }, { "code": null, "e": 6062, "s": 6019, "text": "var emp = {\n name: \"Zara\",\n age: 10\n};" }, { "code": null, "e": 6145, "s": 6062, "text": "You can write and read properties of an object using the dot notation as follows −" }, { "code": null, "e": 6308, "s": 6145, "text": "// Getting object properties\nemp.name // ==> Zara\nemp.age // ==> 10\n// Setting object properties\nemp.name = \"Daisy\" // <== Daisy\nemp.age = 20 // <== 20" }, { "code": null, "e": 6367, "s": 6308, "text": "You can define arrays using the array literal as follows −" }, { "code": null, "e": 6404, "s": 6367, "text": "var x = [];\nvar y = [1, 2, 3, 4, 5];" }, { "code": null, "e": 6511, "s": 6404, "text": "An array has a length property that is useful for iteration. We can read elements of an array as follows −" }, { "code": null, "e": 6604, "s": 6511, "text": "var x = [1, 2, 3, 4, 5];\nfor (var i = 0; i < x.length; i++) {\n // Do something with x[i]\n}" }, { "code": null, "e": 6720, "s": 6604, "text": "A named function has a name when it is defined. A named function can be defined using function keyword as follows −" }, { "code": null, "e": 6765, "s": 6720, "text": "function named(){\n // do some stuff here\n}" }, { "code": null, "e": 6824, "s": 6765, "text": "A function in JavaScript can be either named or anonymous." }, { "code": null, "e": 6929, "s": 6824, "text": "An anonymous function can be defined in similar way as a normal function but it would not have any name." }, { "code": null, "e": 6987, "s": 6929, "text": "Yes! An anonymous function can be assigned to a variable." }, { "code": null, "e": 7064, "s": 6987, "text": "Yes! An anonymous function can be passed as an argument to another function." }, { "code": null, "e": 7141, "s": 7064, "text": "JavaScript variable arguments represents the arguments passed to a function." }, { "code": null, "e": 7233, "s": 7141, "text": "Using typeof operator, we can get the type of arguments passed to a function. For example −" }, { "code": null, "e": 7423, "s": 7233, "text": "function func(x){\n console.log(typeof x, arguments.length);\n}\nfunc(); //==> \"undefined\", 0\nfunc(1); //==> \"number\", 1\nfunc(\"1\", \"2\", \"3\"); //==> \"string\", 3" }, { "code": null, "e": 7533, "s": 7423, "text": "Using arguments.length property, we can get the total number of arguments passed to a function. For example −" }, { "code": null, "e": 7723, "s": 7533, "text": "function func(x){\n console.log(typeof x, arguments.length);\n}\nfunc(); //==> \"undefined\", 0\nfunc(1); //==> \"number\", 1\nfunc(\"1\", \"2\", \"3\"); //==> \"string\", 3" }, { "code": null, "e": 7828, "s": 7723, "text": "The arguments object has a callee property, which refers to the function you're inside of. For example −" }, { "code": null, "e": 7912, "s": 7828, "text": "function func() {\n return arguments.callee; \n}\nfunc(); // ==> func" }, { "code": null, "e": 7981, "s": 7912, "text": "JavaScript famous keyword this always refers to the current context." }, { "code": null, "e": 8106, "s": 7981, "text": "The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes." }, { "code": null, "e": 8222, "s": 8106, "text": "Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code." }, { "code": null, "e": 8338, "s": 8222, "text": "Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code." }, { "code": null, "e": 8488, "s": 8338, "text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function." }, { "code": null, "e": 8638, "s": 8488, "text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function." }, { "code": null, "e": 8715, "s": 8638, "text": "A local variable takes precedence over a global variable with the same name." }, { "code": null, "e": 8914, "s": 8715, "text": "A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered." }, { "code": null, "e": 9039, "s": 8914, "text": "Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope." }, { "code": null, "e": 9176, "s": 9039, "text": "Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them −" }, { "code": null, "e": 9419, "s": 9176, "text": "function create() {\n var counter = 0;\n return {\n increment: function() {\n counter++;\n },\n \n print: function() {\n console.log(counter);\n }\n }\n}\nvar c = create();\nc.increment();\nc.print(); // ==> 1" }, { "code": null, "e": 9481, "s": 9419, "text": "charAt() method returns the character at the specified index." }, { "code": null, "e": 9543, "s": 9481, "text": "concat() method returns the character at the specified index." }, { "code": null, "e": 9608, "s": 9543, "text": "forEach() method calls a function for each element in the array." }, { "code": null, "e": 9744, "s": 9608, "text": "indexOf() method returns the index within the calling String object of the first occurrence of the specified value, or −1 if not found." }, { "code": null, "e": 9794, "s": 9744, "text": "length() method returns the length of the string." }, { "code": null, "e": 9872, "s": 9794, "text": "pop() method removes the last element from an array and returns that element." }, { "code": null, "e": 9976, "s": 9872, "text": "push() method adds one or more elements to the end of an array and returns the new length of the array." }, { "code": null, "e": 10103, "s": 9976, "text": "reverse() method reverses the order of the elements of an array −− the first becomes the last, and the last becomes the first." }, { "code": null, "e": 10149, "s": 10103, "text": "sort() method sorts the elements of an array." }, { "code": null, "e": 10280, "s": 10149, "text": "substr() method returns the characters in a string beginning at the specified location through the specified number of characters." }, { "code": null, "e": 10359, "s": 10280, "text": "toLowerCase() method returns the calling string value converted to lower case." }, { "code": null, "e": 10438, "s": 10359, "text": "toUpperCase() method returns the calling string value converted to upper case." }, { "code": null, "e": 10513, "s": 10438, "text": "toString() method returns the string representation of the number's value." }, { "code": null, "e": 10585, "s": 10513, "text": "While naming your variables in JavaScript keep following rules in mind." }, { "code": null, "e": 10771, "s": 10585, "text": "You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid." }, { "code": null, "e": 10973, "s": 10771, "text": "JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one." }, { "code": null, "e": 11075, "s": 10973, "text": "JavaScript variable names are case sensitive. For example, Name and name are two different variables." }, { "code": null, "e": 11237, "s": 11075, "text": "The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand." }, { "code": null, "e": 11407, "s": 11237, "text": "The typeof operator evaluates to \"number\", \"string\", or \"boolean\" if its operand is a number, string, or boolean value and returns true or false based on the evaluation." }, { "code": null, "e": 11428, "s": 11407, "text": "It returns \"object\"." }, { "code": null, "e": 11623, "s": 11428, "text": "JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page." }, { "code": null, "e": 11742, "s": 11623, "text": "The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this −" }, { "code": null, "e": 11751, "s": 11742, "text": "Syntax −" }, { "code": null, "e": 11817, "s": 11751, "text": "document.cookie = \"key1 = value1; key2 = value2; expires = date\";" }, { "code": null, "e": 12011, "s": 11817, "text": "Here expires attribute is option. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies' value will not be accessible." }, { "code": null, "e": 12192, "s": 12011, "text": "Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie." }, { "code": null, "e": 12349, "s": 12192, "text": "The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value." }, { "code": null, "e": 12428, "s": 12349, "text": "You can use strings' split() function to break the string into key and values." }, { "code": null, "e": 12610, "s": 12428, "text": "Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past." }, { "code": null, "e": 12792, "s": 12610, "text": "his is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows −" }, { "code": null, "e": 12909, "s": 12792, "text": "<head>\n<script type=\"text/javascript\">\n<!--\n window.location=\"http://www.newlocation.com\";\n//-->\n</script>\n</head>" }, { "code": null, "e": 13093, "s": 12909, "text": "JavaScript helps you to implement this functionality using print function of window object. The JavaScript print function window.print() will print the current web page when executed." }, { "code": null, "e": 13206, "s": 13093, "text": "The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( )." }, { "code": null, "e": 13469, "s": 13206, "text": "Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time." }, { "code": null, "e": 13707, "s": 13469, "text": "he Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class." }, { "code": null, "e": 13716, "s": 13707, "text": "Syntax −" }, { "code": null, "e": 13743, "s": 13716, "text": "Creating a number object −" }, { "code": null, "e": 13773, "s": 13743, "text": "var val = new Number(number);" }, { "code": null, "e": 13855, "s": 13773, "text": "If the argument cannot be converted into a number, it returns NaN (Not-a-Number)." }, { "code": null, "e": 14038, "s": 13855, "text": "The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions." }, { "code": null, "e": 14144, "s": 14038, "text": "You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors." }, { "code": null, "e": 14325, "s": 14144, "text": "The onerror event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page." }, { "code": null, "e": 14432, "s": 14325, "text": "The onerror event handler provides three pieces of information to identify the exact nature of the error −" }, { "code": null, "e": 14517, "s": 14432, "text": "Error message − The same message that the browser would display for the given error." }, { "code": null, "e": 14602, "s": 14517, "text": "Error message − The same message that the browser would display for the given error." }, { "code": null, "e": 14646, "s": 14602, "text": "URL − The file in which the error occurred." }, { "code": null, "e": 14690, "s": 14646, "text": "URL − The file in which the error occurred." }, { "code": null, "e": 14760, "s": 14690, "text": "Line number − The line number in the given URL that caused the error." }, { "code": null, "e": 14830, "s": 14760, "text": "Line number − The line number in the given URL that caused the error." }, { "code": null, "e": 15117, "s": 14830, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 15447, "s": 15117, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 15482, "s": 15447, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 15496, "s": 15482, "text": " Anadi Sharma" }, { "code": null, "e": 15530, "s": 15496, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 15544, "s": 15530, "text": " Lets Kode It" }, { "code": null, "e": 15579, "s": 15544, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 15596, "s": 15579, "text": " Frahaan Hussain" }, { "code": null, "e": 15631, "s": 15596, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 15648, "s": 15631, "text": " Frahaan Hussain" }, { "code": null, "e": 15681, "s": 15648, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 15709, "s": 15681, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 15743, "s": 15709, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 15771, "s": 15743, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 15778, "s": 15771, "text": " Print" }, { "code": null, "e": 15789, "s": 15778, "text": " Add Notes" } ]
How to calculate the ln of a given number in JavaScript?
To calculate the ln of a given number, use the Math.log() method in JavaScript. This method returns the natural logarithm (base E) of a number. If the value of a number is negative, the return value is always NaN. You can try to run the following code to get the ln of a given number − <html> <head> <title>JavaScript Math log() Method</title> </head> <body> <script> var value = Math.log(2); document.write("Value : " + value ); </script> </body> </html>
[ { "code": null, "e": 1276, "s": 1062, "text": "To calculate the ln of a given number, use the Math.log() method in JavaScript. This method returns the natural logarithm (base E) of a number. If the value of a number is negative, the return value is always NaN." }, { "code": null, "e": 1348, "s": 1276, "text": "You can try to run the following code to get the ln of a given number −" }, { "code": null, "e": 1566, "s": 1348, "text": "<html>\n <head>\n <title>JavaScript Math log() Method</title>\n </head>\n <body>\n <script>\n var value = Math.log(2);\n document.write(\"Value : \" + value );\n </script>\n </body>\n</html>" } ]
Why do we need generics in Java?
As we know a class is a blue print in which we define the required behaviors and properties and, an interface is similar to class but it is a Specification (containing abstract methods). These are also considered as datatypes in Java, unlike other primitive datatypes a literal of these kind of types points/refers to the location of the object. They are also known as reference types. Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class generic you are making it type-safe i.e. it can act up on any datatype. To understand generics let us consider an example − In the following Java example we are defining a class named Student whose constructor (parameterized) accepts an Integer object. While instantiating this class you can pass an integer object Live Demo class Student{ Integer age; Student(Integer age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student std = new Student(25); std.display(); } } Value of age: 25 Passing any other object to the constructor of this class generates a compile time exception public static void main(String args[]) { Student std = new Student("25"); std.display(); } GenericsExample.java:12: error: incompatible types: String cannot be converted to Integer Student std = new Student("25"); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error The age of a student could be passed as (an object of) String value, Float, Double etc. If you want to pass a value of another object you need to change the constructor as − class Student{ String age; Student(String age){ this.age = age; } } Or, class Student{ Float age; Student(Float age){ this.age = age; } } When you declare generic types they can act upon any datatypes and, they are known as parameterized types. You cannot use primitive datatypes in generics. To create a class of generic type by using generic parameter T or, GT as − class Student <T>{ T obj; } Where T (generic parameter) represents the datatype of the object you can pass to the constructor of this class. This will be determined at the compilation time. While instantiating the class you need to/can choose the type of the generic parameter as − Student<Float> obj = new Student<Float>(); Live Demo We can rewrite the above example using generics as − class Student<T>{ T age; Student(T age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student<Float> std = new Student<Float>(25.5f); std.display(); } } Value of age: 25.5 Now, while instantiating the Student class you can pass desired type of object as a parameter as − class Student<T>{ T age; Student(T age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student<Float> std1 = new Student<Float>(25.5f); std1.display(); Student<String> std2 = new Student<String>("25"); std2.display(); Student<Integer> std3 = new Student<Integer>(25); std3.display(); } } Value of age: 25.5 Value of age: 25 Value of age: 25 Usage of generics in your code you will have the following advantages − Type check at compile time −usually, when you use types (regular objects), when you pass an incorrect object as a parameter, it will prompt an error at the run time. Type check at compile time −usually, when you use types (regular objects), when you pass an incorrect object as a parameter, it will prompt an error at the run time. Whereas, when you use generics the error will be at the compile time which is easy to solve. Whereas, when you use generics the error will be at the compile time which is easy to solve. Code reuse − You can write a method or, Class or, interface using generic type once and you can use this code multiple times with various parameters. Code reuse − You can write a method or, Class or, interface using generic type once and you can use this code multiple times with various parameters. For certain types, with formal types, you need to cast the object and use. Using generics (in most cases) you can directly pass the object of required type without relying on casting. For certain types, with formal types, you need to cast the object and use. Using generics (in most cases) you can directly pass the object of required type without relying on casting. Using generic types you can implement various generic algorithms. Using generic types you can implement various generic algorithms.
[ { "code": null, "e": 1249, "s": 1062, "text": "As we know a class is a blue print in which we define the required behaviors and properties and, an interface is similar to class but it is a Specification (containing abstract methods)." }, { "code": null, "e": 1448, "s": 1249, "text": "These are also considered as datatypes in Java, unlike other primitive datatypes a literal of these kind of types points/refers to the location of the object. They are also known as reference types." }, { "code": null, "e": 1721, "s": 1448, "text": "Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically." }, { "code": null, "e": 1865, "s": 1721, "text": "By defining a class generic you are making it type-safe i.e. it can act up on any datatype. To understand generics let us consider an example −" }, { "code": null, "e": 2056, "s": 1865, "text": "In the following Java example we are defining a class named Student whose constructor (parameterized) accepts an Integer object. While instantiating this class you can pass an integer object" }, { "code": null, "e": 2067, "s": 2056, "text": " Live Demo" }, { "code": null, "e": 2377, "s": 2067, "text": "class Student{\n Integer age;\n Student(Integer age){\n this.age = age;\n }\n public void display() {\n System.out.println(\"Value of age: \"+this.age);\n }\n}\npublic class GenericsExample {\n public static void main(String args[]) {\n Student std = new Student(25);\n std.display();\n }\n}" }, { "code": null, "e": 2394, "s": 2377, "text": "Value of age: 25" }, { "code": null, "e": 2487, "s": 2394, "text": "Passing any other object to the constructor of this class generates a compile time exception" }, { "code": null, "e": 2584, "s": 2487, "text": "public static void main(String args[]) {\n Student std = new Student(\"25\");\n std.display();\n}" }, { "code": null, "e": 2842, "s": 2584, "text": "GenericsExample.java:12: error: incompatible types: String cannot be converted to Integer\n Student std = new Student(\"25\");\n ^\nNote: Some messages have been simplified; recompile with -Xdiags:verbose to get full output\n1 error" }, { "code": null, "e": 3016, "s": 2842, "text": "The age of a student could be passed as (an object of) String value, Float, Double etc. If you want to pass a value of another object you need to change the constructor as −" }, { "code": null, "e": 3184, "s": 3016, "text": "class Student{\n String age;\n Student(String age){\n this.age = age;\n }\n}\nOr,\nclass Student{\n Float age;\n Student(Float age){\n this.age = age;\n }\n}" }, { "code": null, "e": 3339, "s": 3184, "text": "When you declare generic types they can act upon any datatypes and, they are known as parameterized types. You cannot use primitive datatypes in generics." }, { "code": null, "e": 3414, "s": 3339, "text": "To create a class of generic type by using generic parameter T or, GT as −" }, { "code": null, "e": 3445, "s": 3414, "text": "class Student <T>{\n T obj;\n}" }, { "code": null, "e": 3607, "s": 3445, "text": "Where T (generic parameter) represents the datatype of the object you can pass to the constructor of this class. This will be determined at the compilation time." }, { "code": null, "e": 3699, "s": 3607, "text": "While instantiating the class you need to/can choose the type of the generic parameter as −" }, { "code": null, "e": 3742, "s": 3699, "text": "Student<Float> obj = new Student<Float>();" }, { "code": null, "e": 3753, "s": 3742, "text": " Live Demo" }, { "code": null, "e": 3806, "s": 3753, "text": "We can rewrite the above example using generics as −" }, { "code": null, "e": 4124, "s": 3806, "text": "class Student<T>{\n T age;\n Student(T age){\n this.age = age;\n }\n public void display() {\n System.out.println(\"Value of age: \"+this.age);\n }\n}\npublic class GenericsExample {\n public static void main(String args[]) {\n Student<Float> std = new Student<Float>(25.5f);\n std.display();\n }\n}" }, { "code": null, "e": 4143, "s": 4124, "text": "Value of age: 25.5" }, { "code": null, "e": 4242, "s": 4143, "text": "Now, while instantiating the Student class you can pass desired type of object as a parameter as −" }, { "code": null, "e": 4715, "s": 4242, "text": "class Student<T>{\n T age;\n Student(T age){\n this.age = age;\n}\n public void display() {\n System.out.println(\"Value of age: \"+this.age);\n }\n}\npublic class GenericsExample {\n public static void main(String args[]) {\n Student<Float> std1 = new Student<Float>(25.5f);\n std1.display();\n Student<String> std2 = new Student<String>(\"25\");\n std2.display();\n Student<Integer> std3 = new Student<Integer>(25);\n std3.display();\n }\n}" }, { "code": null, "e": 4768, "s": 4715, "text": "Value of age: 25.5\nValue of age: 25\nValue of age: 25" }, { "code": null, "e": 4840, "s": 4768, "text": "Usage of generics in your code you will have the following advantages −" }, { "code": null, "e": 5006, "s": 4840, "text": "Type check at compile time −usually, when you use types (regular objects), when you pass an incorrect object as a parameter, it will prompt an error at the run time." }, { "code": null, "e": 5172, "s": 5006, "text": "Type check at compile time −usually, when you use types (regular objects), when you pass an incorrect object as a parameter, it will prompt an error at the run time." }, { "code": null, "e": 5265, "s": 5172, "text": "Whereas, when you use generics the error will be at the compile time which is easy to solve." }, { "code": null, "e": 5358, "s": 5265, "text": "Whereas, when you use generics the error will be at the compile time which is easy to solve." }, { "code": null, "e": 5508, "s": 5358, "text": "Code reuse − You can write a method or, Class or, interface using generic type once and you can use this code multiple times with various parameters." }, { "code": null, "e": 5658, "s": 5508, "text": "Code reuse − You can write a method or, Class or, interface using generic type once and you can use this code multiple times with various parameters." }, { "code": null, "e": 5842, "s": 5658, "text": "For certain types, with formal types, you need to cast the object and use. Using generics (in most cases) you can directly pass the object of required type without relying on casting." }, { "code": null, "e": 6026, "s": 5842, "text": "For certain types, with formal types, you need to cast the object and use. Using generics (in most cases) you can directly pass the object of required type without relying on casting." }, { "code": null, "e": 6092, "s": 6026, "text": "Using generic types you can implement various generic algorithms." }, { "code": null, "e": 6158, "s": 6092, "text": "Using generic types you can implement various generic algorithms." } ]
Java Program to Convert Milliseconds to Minutes and Seconds
08 Oct, 2021 Convert Milliseconds to Minutes and Seconds in java using methods like toMinutes() and toSeconds(), TimeUnit which is in the concurrent package. Milliseconds: 1 millisecond = 0.001 second or (1/1000) seconds Seconds: 1 second = 1000 millisecond 1 second = (1/60) minutes Minute: 1 minute = 60000 milliseconds 1 minute = 60 seconds 1 minute = (1/60)hour Example: Input : Milliseconds = 400000 Output: 6 minutes and 40 seconds Input : Milliseconds = 5400000 Output: 90 minutes and 0 seconds Algorithm: Take Input in milliseconds.Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60).Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).The print output from Milliseconds to minutes and seconds Take Input in milliseconds. Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60). The print output from Milliseconds to minutes and seconds Methods of Solving: Java Program to Convert Milliseconds to Minutes and Seconds. Simply using Basic Input / Output in Java.Using Methods in Java. Simply using Basic Input / Output in Java. Using Methods in Java. 1. Program to Convert Milliseconds to Minutes and Seconds Java // Java Program to Convert Milliseconds// to Minutes and Seconds import java.io.*; class GFG { public static void main(String[] args) { // Take Input in Long otherwise // overflow occur for some inputs. long milliseconds = 3500000; // formula for conversion for // milliseconds to minutes. long minutes = (milliseconds / 1000) / 60; // formula for conversion for // milliseconds to seconds long seconds = (milliseconds / 1000) % 60; // Print the output System.out.println(milliseconds + " Milliseconds = " + minutes + " minutes and " + seconds + " seconds."); }} 3500000 Milliseconds = 58 minutes and 20 seconds. 2. Program to Convert Milliseconds to Minutes and Seconds using Methods. Java // Java Program to Convert Milliseconds// to Minutes and Seconds import java.io.*;import java.util.concurrent.TimeUnit; class GFG { public static void main(String[] args) { long milliseconds = 3500000; // This method uses this formula :minutes = // (milliseconds / 1000) / 60; long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds); // This method uses this formula seconds = // (milliseconds / 1000); long seconds = (TimeUnit.MILLISECONDS.toSeconds(milliseconds) % 60); // Print the answer System.out.format(milliseconds + " Milliseconds = " + minutes + " minutes and " + seconds + " seconds"); }} 3500000 Milliseconds = 58 minutes and 20 seconds sweetyty anikakapoor Java-Date-Time Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Oct, 2021" }, { "code": null, "e": 198, "s": 53, "text": "Convert Milliseconds to Minutes and Seconds in java using methods like toMinutes() and toSeconds(), TimeUnit which is in the concurrent package." }, { "code": null, "e": 212, "s": 198, "text": "Milliseconds:" }, { "code": null, "e": 261, "s": 212, "text": "1 millisecond = 0.001 second or (1/1000) seconds" }, { "code": null, "e": 271, "s": 261, "text": "Seconds: " }, { "code": null, "e": 325, "s": 271, "text": "1 second = 1000 millisecond\n1 second = (1/60) minutes" }, { "code": null, "e": 333, "s": 325, "text": "Minute:" }, { "code": null, "e": 407, "s": 333, "text": "1 minute = 60000 milliseconds\n1 minute = 60 seconds\n1 minute = (1/60)hour" }, { "code": null, "e": 416, "s": 407, "text": "Example:" }, { "code": null, "e": 544, "s": 416, "text": "Input : Milliseconds = 400000\nOutput: 6 minutes and 40 seconds\n\nInput : Milliseconds = 5400000\nOutput: 90 minutes and 0 seconds" }, { "code": null, "e": 555, "s": 544, "text": "Algorithm:" }, { "code": null, "e": 811, "s": 555, "text": "Take Input in milliseconds.Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60).Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).The print output from Milliseconds to minutes and seconds" }, { "code": null, "e": 839, "s": 811, "text": "Take Input in milliseconds." }, { "code": null, "e": 926, "s": 839, "text": "Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60)." }, { "code": null, "e": 1012, "s": 926, "text": "Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60)." }, { "code": null, "e": 1070, "s": 1012, "text": "The print output from Milliseconds to minutes and seconds" }, { "code": null, "e": 1151, "s": 1070, "text": "Methods of Solving: Java Program to Convert Milliseconds to Minutes and Seconds." }, { "code": null, "e": 1216, "s": 1151, "text": "Simply using Basic Input / Output in Java.Using Methods in Java." }, { "code": null, "e": 1259, "s": 1216, "text": "Simply using Basic Input / Output in Java." }, { "code": null, "e": 1282, "s": 1259, "text": "Using Methods in Java." }, { "code": null, "e": 1340, "s": 1282, "text": "1. Program to Convert Milliseconds to Minutes and Seconds" }, { "code": null, "e": 1345, "s": 1340, "text": "Java" }, { "code": "// Java Program to Convert Milliseconds// to Minutes and Seconds import java.io.*; class GFG { public static void main(String[] args) { // Take Input in Long otherwise // overflow occur for some inputs. long milliseconds = 3500000; // formula for conversion for // milliseconds to minutes. long minutes = (milliseconds / 1000) / 60; // formula for conversion for // milliseconds to seconds long seconds = (milliseconds / 1000) % 60; // Print the output System.out.println(milliseconds + \" Milliseconds = \" + minutes + \" minutes and \" + seconds + \" seconds.\"); }}", "e": 2049, "s": 1345, "text": null }, { "code": null, "e": 2099, "s": 2049, "text": "3500000 Milliseconds = 58 minutes and 20 seconds." }, { "code": null, "e": 2172, "s": 2099, "text": "2. Program to Convert Milliseconds to Minutes and Seconds using Methods." }, { "code": null, "e": 2177, "s": 2172, "text": "Java" }, { "code": "// Java Program to Convert Milliseconds// to Minutes and Seconds import java.io.*;import java.util.concurrent.TimeUnit; class GFG { public static void main(String[] args) { long milliseconds = 3500000; // This method uses this formula :minutes = // (milliseconds / 1000) / 60; long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds); // This method uses this formula seconds = // (milliseconds / 1000); long seconds = (TimeUnit.MILLISECONDS.toSeconds(milliseconds) % 60); // Print the answer System.out.format(milliseconds + \" Milliseconds = \" + minutes + \" minutes and \" + seconds + \" seconds\"); }}", "e": 2943, "s": 2177, "text": null }, { "code": null, "e": 2992, "s": 2943, "text": "3500000 Milliseconds = 58 minutes and 20 seconds" }, { "code": null, "e": 3003, "s": 2994, "text": "sweetyty" }, { "code": null, "e": 3015, "s": 3003, "text": "anikakapoor" }, { "code": null, "e": 3030, "s": 3015, "text": "Java-Date-Time" }, { "code": null, "e": 3037, "s": 3030, "text": "Picked" }, { "code": null, "e": 3061, "s": 3037, "text": "Technical Scripter 2020" }, { "code": null, "e": 3066, "s": 3061, "text": "Java" }, { "code": null, "e": 3080, "s": 3066, "text": "Java Programs" }, { "code": null, "e": 3099, "s": 3080, "text": "Technical Scripter" }, { "code": null, "e": 3104, "s": 3099, "text": "Java" } ]
Java.util.BitSet.flip() in Java
16 Aug, 2018 There are two variants of flip() method. This article depicts about all of them as follows: 1. flip(int value) : This method removes the value specified in the argument. public void flip(int value) Parameters : value : the value to flip. Return ValueThis method does not return a value. // Java code to demonstrate the// working of flip(int value) in Bitset import java.util.*; public class Flip1 { public static void main(String[] args) { // declaring bitset BitSet bset = new BitSet(6); // assigning values to bset bset.set(0); bset.set(1); bset.set(2); bset.set(3); // printing the original set System.out.println("The original bitset is : " + bset); // using flip() to remove 2 bset.flip(2); // printing final bitset // 2 is removed System.out.println("The flipped bitset is : " + bset); }} Output: The original bitset is : {0, 1, 2, 3} The flipped bitset is : {0, 1, 3} 2. flip(int fromnum, int tonum) : This method sets each bit from the specified fromnum (inclusive) to the specified tonum (exclusive) to the complement of its current value, i.e removes fromnum to tonum-1 values. public void flip(int fromnum,int tonum) Parameters : fromnum : start number to begin flipping. tonum : last-1 number to end flipping. Return Value : This method does not return a value. // Java code to demonstrate the// working of flip(int fromnum, int tonum) in Bitset import java.util.*; public class Flip2 { public static void main(String[] args) { // declaring bitset BitSet bset = new BitSet(6); // assigning values to bset bset.set(0); bset.set(1); bset.set(2); bset.set(3); // printing the original set System.out.println("The original bitset is : " + bset); // using flip(fromnum,tonum) to remove 1 and 2 bset.flip(1,3); // printing final bitset // 1 and 2 are removed System.out.println("The flipped bitset is : " + bset); }} Output: The original bitset is : {0, 1, 2, 3} The flipped bitset is : {0, 3} This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java - util package Java-BitSet Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2018" }, { "code": null, "e": 120, "s": 28, "text": "There are two variants of flip() method. This article depicts about all of them as follows:" }, { "code": null, "e": 198, "s": 120, "text": "1. flip(int value) : This method removes the value specified in the argument." }, { "code": null, "e": 319, "s": 198, "text": "public void flip(int value)\n\nParameters : \nvalue : the value to flip.\nReturn ValueThis method does not return a value.\n" }, { "code": "// Java code to demonstrate the// working of flip(int value) in Bitset import java.util.*; public class Flip1 { public static void main(String[] args) { // declaring bitset BitSet bset = new BitSet(6); // assigning values to bset bset.set(0); bset.set(1); bset.set(2); bset.set(3); // printing the original set System.out.println(\"The original bitset is : \" + bset); // using flip() to remove 2 bset.flip(2); // printing final bitset // 2 is removed System.out.println(\"The flipped bitset is : \" + bset); }}", "e": 868, "s": 319, "text": null }, { "code": null, "e": 876, "s": 868, "text": "Output:" }, { "code": null, "e": 949, "s": 876, "text": "The original bitset is : {0, 1, 2, 3}\nThe flipped bitset is : {0, 1, 3}\n" }, { "code": null, "e": 1162, "s": 949, "text": "2. flip(int fromnum, int tonum) : This method sets each bit from the specified fromnum (inclusive) to the specified tonum (exclusive) to the complement of its current value, i.e removes fromnum to tonum-1 values." }, { "code": null, "e": 1353, "s": 1162, "text": "public void flip(int fromnum,int tonum)\nParameters : \nfromnum : start number to begin flipping.\ntonum : last-1 number to end flipping.\nReturn Value : \nThis method does not return a value.\n" }, { "code": "// Java code to demonstrate the// working of flip(int fromnum, int tonum) in Bitset import java.util.*; public class Flip2 { public static void main(String[] args) { // declaring bitset BitSet bset = new BitSet(6); // assigning values to bset bset.set(0); bset.set(1); bset.set(2); bset.set(3); // printing the original set System.out.println(\"The original bitset is : \" + bset); // using flip(fromnum,tonum) to remove 1 and 2 bset.flip(1,3); // printing final bitset // 1 and 2 are removed System.out.println(\"The flipped bitset is : \" + bset); }}", "e": 1943, "s": 1353, "text": null }, { "code": null, "e": 1951, "s": 1943, "text": "Output:" }, { "code": null, "e": 2021, "s": 1951, "text": "The original bitset is : {0, 1, 2, 3}\nThe flipped bitset is : {0, 3}\n" }, { "code": null, "e": 2444, "s": 2021, "text": "This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2464, "s": 2444, "text": "Java - util package" }, { "code": null, "e": 2476, "s": 2464, "text": "Java-BitSet" }, { "code": null, "e": 2481, "s": 2476, "text": "Java" }, { "code": null, "e": 2486, "s": 2481, "text": "Java" } ]
Python Program to Return the Length of the Longest Word from the List of Words
28 Jul, 2021 The problem is to go through all the words in an array and the program should return the word with the longest one. Consider for example we are having an array, and we have numbers in alphabetic form, now when we pass this array as an input then we should get the word with the longest one. Below I had explained it with an example in order to give an elaborate view. Example: Input : [“one”, “two”, “three”, “four”] Output: threeExplanation: As we pass the above array as a input, our program will check which word or which value has the maximum length and after completely iterating through the array then it returns the word with longest length. Methods 1#: Iterating and finding the greater length word. Approach: First declare a function with the name ‘longest Length ‘ which accepts a list as an argument.Now, take a list where you have all the values.We are going to take this list, and we will iterate through each item using for loop.Then we take two variables max1 and temp to store the maximum length and the word with the longest length.After completing the above steps then we take the first value in the list and the first value length in order to compare.Once the above steps are completed we compare the items in the list using for loop. Below I had mentioned the logic.After completing the above steps run the program, and then we’ll get the required result. First declare a function with the name ‘longest Length ‘ which accepts a list as an argument. Now, take a list where you have all the values. We are going to take this list, and we will iterate through each item using for loop. Then we take two variables max1 and temp to store the maximum length and the word with the longest length. After completing the above steps then we take the first value in the list and the first value length in order to compare. Once the above steps are completed we compare the items in the list using for loop. Below I had mentioned the logic. After completing the above steps run the program, and then we’ll get the required result. Implementation: Python3 # function to find the longest# length in the listdef longestLength(a): max1 = len(a[0]) temp = a[0] # for loop to traverse the list for i in a: if(len(i) > max1): max1 = len(i) temp = i print("The word with the longest length is:", temp, " and length is ", max1) # Driver Programa = ["one", "two", "third", "four"]longestLength(a) Output: The word with the longest length is: third and length is 5 Methods 2#: Using sort(). Approach: First declare a function with the name ‘longest Length ‘ which accepts a list as an argument.Now, take a list where you have all the values.We are going to take this list, and we will iterate through each item using for loop.Then we take an empty list with the name final List and will append all the items.After appending we will sort the list using the sort() method.Now, as the list is sorted we can get the longest length, and we can display it.After completing the above steps run the program, and then we’ll get the required result. First declare a function with the name ‘longest Length ‘ which accepts a list as an argument. Now, take a list where you have all the values. We are going to take this list, and we will iterate through each item using for loop. Then we take an empty list with the name final List and will append all the items. After appending we will sort the list using the sort() method. Now, as the list is sorted we can get the longest length, and we can display it. After completing the above steps run the program, and then we’ll get the required result. Python3 # function to find the longest length in the listdef longestLength(words): finalList = [] for word in words: finalList.append((len(word), word)) finalList.sort() print("The word with the longest length is:", finalList[-1][1], " and length is ", len(finalList[-1][1])) # Driver Programa = ["one", "two", "third", "four"]longestLength(a) Output: The word with the longest length is: third and length is 5 sooda367 Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2021" }, { "code": null, "e": 405, "s": 28, "text": "The problem is to go through all the words in an array and the program should return the word with the longest one. Consider for example we are having an array, and we have numbers in alphabetic form, now when we pass this array as an input then we should get the word with the longest one. Below I had explained it with an example in order to give an elaborate view. Example:" }, { "code": null, "e": 681, "s": 405, "text": "Input : [“one”, “two”, “three”, “four”] Output: threeExplanation: As we pass the above array as a input, our program will check which word or which value has the maximum length and after completely iterating through the array then it returns the word with longest length. " }, { "code": null, "e": 740, "s": 681, "text": "Methods 1#: Iterating and finding the greater length word." }, { "code": null, "e": 750, "s": 740, "text": "Approach:" }, { "code": null, "e": 1408, "s": 750, "text": "First declare a function with the name ‘longest Length ‘ which accepts a list as an argument.Now, take a list where you have all the values.We are going to take this list, and we will iterate through each item using for loop.Then we take two variables max1 and temp to store the maximum length and the word with the longest length.After completing the above steps then we take the first value in the list and the first value length in order to compare.Once the above steps are completed we compare the items in the list using for loop. Below I had mentioned the logic.After completing the above steps run the program, and then we’ll get the required result." }, { "code": null, "e": 1502, "s": 1408, "text": "First declare a function with the name ‘longest Length ‘ which accepts a list as an argument." }, { "code": null, "e": 1550, "s": 1502, "text": "Now, take a list where you have all the values." }, { "code": null, "e": 1636, "s": 1550, "text": "We are going to take this list, and we will iterate through each item using for loop." }, { "code": null, "e": 1743, "s": 1636, "text": "Then we take two variables max1 and temp to store the maximum length and the word with the longest length." }, { "code": null, "e": 1865, "s": 1743, "text": "After completing the above steps then we take the first value in the list and the first value length in order to compare." }, { "code": null, "e": 1982, "s": 1865, "text": "Once the above steps are completed we compare the items in the list using for loop. Below I had mentioned the logic." }, { "code": null, "e": 2072, "s": 1982, "text": "After completing the above steps run the program, and then we’ll get the required result." }, { "code": null, "e": 2088, "s": 2072, "text": "Implementation:" }, { "code": null, "e": 2096, "s": 2088, "text": "Python3" }, { "code": "# function to find the longest# length in the listdef longestLength(a): max1 = len(a[0]) temp = a[0] # for loop to traverse the list for i in a: if(len(i) > max1): max1 = len(i) temp = i print(\"The word with the longest length is:\", temp, \" and length is \", max1) # Driver Programa = [\"one\", \"two\", \"third\", \"four\"]longestLength(a)", "e": 2485, "s": 2096, "text": null }, { "code": null, "e": 2493, "s": 2485, "text": "Output:" }, { "code": null, "e": 2554, "s": 2493, "text": "The word with the longest length is: third and length is 5" }, { "code": null, "e": 2580, "s": 2554, "text": "Methods 2#: Using sort()." }, { "code": null, "e": 2590, "s": 2580, "text": "Approach:" }, { "code": null, "e": 3129, "s": 2590, "text": "First declare a function with the name ‘longest Length ‘ which accepts a list as an argument.Now, take a list where you have all the values.We are going to take this list, and we will iterate through each item using for loop.Then we take an empty list with the name final List and will append all the items.After appending we will sort the list using the sort() method.Now, as the list is sorted we can get the longest length, and we can display it.After completing the above steps run the program, and then we’ll get the required result." }, { "code": null, "e": 3223, "s": 3129, "text": "First declare a function with the name ‘longest Length ‘ which accepts a list as an argument." }, { "code": null, "e": 3271, "s": 3223, "text": "Now, take a list where you have all the values." }, { "code": null, "e": 3357, "s": 3271, "text": "We are going to take this list, and we will iterate through each item using for loop." }, { "code": null, "e": 3440, "s": 3357, "text": "Then we take an empty list with the name final List and will append all the items." }, { "code": null, "e": 3503, "s": 3440, "text": "After appending we will sort the list using the sort() method." }, { "code": null, "e": 3584, "s": 3503, "text": "Now, as the list is sorted we can get the longest length, and we can display it." }, { "code": null, "e": 3674, "s": 3584, "text": "After completing the above steps run the program, and then we’ll get the required result." }, { "code": null, "e": 3682, "s": 3674, "text": "Python3" }, { "code": "# function to find the longest length in the listdef longestLength(words): finalList = [] for word in words: finalList.append((len(word), word)) finalList.sort() print(\"The word with the longest length is:\", finalList[-1][1], \" and length is \", len(finalList[-1][1])) # Driver Programa = [\"one\", \"two\", \"third\", \"four\"]longestLength(a)", "e": 4062, "s": 3682, "text": null }, { "code": null, "e": 4070, "s": 4062, "text": "Output:" }, { "code": null, "e": 4131, "s": 4070, "text": "The word with the longest length is: third and length is 5" }, { "code": null, "e": 4140, "s": 4131, "text": "sooda367" }, { "code": null, "e": 4161, "s": 4140, "text": "Python list-programs" }, { "code": null, "e": 4184, "s": 4161, "text": "Python string-programs" }, { "code": null, "e": 4191, "s": 4184, "text": "Python" }, { "code": null, "e": 4207, "s": 4191, "text": "Python Programs" } ]
Nested List Comprehensions in Python
07 Nov, 2018 List Comprehensions are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Let’s take a look at some examples to understand what nested list comprehensions can do: Example 1: I want to create a matrix which looks like below: matrix = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] The below code uses nested for loops for the given task: matrix = [] for i in range(5): # Append an empty sublist inside the list matrix.append([]) for j in range(5): matrix[i].append(j) print(matrix) [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] The same output can be achieved using nested list comprehension in just one line: # Nested list comprehensionmatrix = [[j for j in range(5)] for i in range(5)] print(matrix) [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] Explanation: The syntax of the above program is shown below: [expression for i in range(5)] –> which means that execute this expression and append its output to the list until variable i iterates from 0 to 4. For example:- [i for i in range(5)] –> In this case, the output of the expressionis simply the variable i itself and hence we append its output to the list while iiterates from 0 to 4. Thus the output would be –> [0, 1, 2, 3, 4] But in our case, the expression itself is a list comprehension. Hence we need to firstsolve the expression and then append its output to the list. expression = [j for j in range(5)] –> The output of this expression is same as theexample discussed above. Hence expression = [0, 1, 2, 3, 4]. Now we just simply append this output until variable i iterates from 0 to 4 which wouldbe total 5 iterations. Hence the final output would just be a list of the output of theabove expression repeated 5 times. Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] Example 2: Suppose I want to flatten a given 2-D list: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Expected Output: flatten_matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9] This can be done using nested for loops as follows: # 2-D Listmatrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] flatten_matrix = [] for sublist in matrix: for val in sublist: flatten_matrix.append(val) print(flatten_matrix) [1, 2, 3, 4, 5, 6, 7, 8, 9] Again this can be done using nested list comprehension which has been shown below: # 2-D Listmatrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Nested List Comprehension to flatten a given 2-D matrixflatten_matrix = [val for sublist in matrix for val in sublist] print(flatten_matrix) [1, 2, 3, 4, 5, 6, 7, 8, 9] Explanation: In this case, we need to loop over each element in the given 2-D list and append itto another list. For better understanding, we can divide the list comprehension intothree parts: flatten_matrix = [val for sublist in matrix for val in sublist] The first line suggests what we want to append to the list. The second line is theouter loop and the third line is the inner loop. ‘for sublist in matrix’ returns the sublists inside the matrix one by one which would be: [1, 2, 3], [4, 5], [6, 7, 8, 9] ‘for val in sublist’ returns all the values inside the sublist. Hence if sublist = [1, 2, 3], ‘for val in sublist’ –> gives 1, 2, 3 as output one by one. For every such val, we get the output as val and we append it to the list. Example 3: Suppose I want to flatten a given 2-D list and only include those strings whose lengths are less than 6: planets = [[‘Mercury’, ‘Venus’, ‘Earth’], [‘Mars’, ‘Jupiter’, ‘Saturn’], [‘Uranus’, ‘Neptune’, ‘Pluto’]] Expected Output: flatten_planets = [‘Venus’, ‘Earth’, ‘Mars’, ‘Pluto’] This can be done using an if condition inside a nested for loop which is shown below: # 2-D List of planetsplanets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']] flatten_planets = [] for sublist in planets: for planet in sublist: if len(planet) < 6: flatten_planets.append(planet) print(flatten_planets) ['Venus', 'Earth', 'Mars', 'Pluto'] This can also be done using nested list comprehensions which has been shown below: # 2-D List of planetsplanets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']] # Nested List comprehension with an if conditionflatten_planets = [planet for sublist in planets for planet in sublist if len(planet) < 6] print(flatten_planets) ['Venus', 'Earth', 'Mars', 'Pluto'] Explanation: This example is quite similar to the previous example but in this example, we justneed an extra if condition to check if the length of a particular planet is less than6 or not. This can be divided into 4 parts as follows: flatten_planets = [planet for sublist in planets for planet in sublist if len(planet) < 6] Picked python-list Technical Scripter 2018 Python Technical Scripter python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Nov, 2018" }, { "code": null, "e": 348, "s": 52, "text": "List Comprehensions are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops." }, { "code": null, "e": 437, "s": 348, "text": "Let’s take a look at some examples to understand what nested list comprehensions can do:" }, { "code": null, "e": 448, "s": 437, "text": "Example 1:" }, { "code": null, "e": 635, "s": 448, "text": "I want to create a matrix which looks like below:\n\nmatrix = [[0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4]]\n" }, { "code": null, "e": 692, "s": 635, "text": "The below code uses nested for loops for the given task:" }, { "code": "matrix = [] for i in range(5): # Append an empty sublist inside the list matrix.append([]) for j in range(5): matrix[i].append(j) print(matrix)", "e": 874, "s": 692, "text": null }, { "code": null, "e": 961, "s": 874, "text": "[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]\n" }, { "code": null, "e": 1043, "s": 961, "text": "The same output can be achieved using nested list comprehension in just one line:" }, { "code": "# Nested list comprehensionmatrix = [[j for j in range(5)] for i in range(5)] print(matrix)", "e": 1136, "s": 1043, "text": null }, { "code": null, "e": 1223, "s": 1136, "text": "[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]\n" }, { "code": null, "e": 1236, "s": 1223, "text": "Explanation:" }, { "code": null, "e": 1284, "s": 1236, "text": "The syntax of the above program is shown below:" }, { "code": null, "e": 1432, "s": 1284, "text": "[expression for i in range(5)] –> which means that execute this expression and append its output to the list until variable i iterates from 0 to 4." }, { "code": null, "e": 1617, "s": 1432, "text": "For example:- [i for i in range(5)] –> In this case, the output of the expressionis simply the variable i itself and hence we append its output to the list while iiterates from 0 to 4." }, { "code": null, "e": 1661, "s": 1617, "text": "Thus the output would be –> [0, 1, 2, 3, 4]" }, { "code": null, "e": 1808, "s": 1661, "text": "But in our case, the expression itself is a list comprehension. Hence we need to firstsolve the expression and then append its output to the list." }, { "code": null, "e": 1915, "s": 1808, "text": "expression = [j for j in range(5)] –> The output of this expression is same as theexample discussed above." }, { "code": null, "e": 1951, "s": 1915, "text": "Hence expression = [0, 1, 2, 3, 4]." }, { "code": null, "e": 2160, "s": 1951, "text": "Now we just simply append this output until variable i iterates from 0 to 4 which wouldbe total 5 iterations. Hence the final output would just be a list of the output of theabove expression repeated 5 times." }, { "code": null, "e": 2254, "s": 2160, "text": "Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]" }, { "code": null, "e": 2265, "s": 2254, "text": "Example 2:" }, { "code": null, "e": 2417, "s": 2265, "text": "Suppose I want to flatten a given 2-D list:\n\nmatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\nExpected Output: flatten_matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n" }, { "code": null, "e": 2469, "s": 2417, "text": "This can be done using nested for loops as follows:" }, { "code": "# 2-D Listmatrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] flatten_matrix = [] for sublist in matrix: for val in sublist: flatten_matrix.append(val) print(flatten_matrix)", "e": 2655, "s": 2469, "text": null }, { "code": null, "e": 2684, "s": 2655, "text": "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" }, { "code": null, "e": 2767, "s": 2684, "text": "Again this can be done using nested list comprehension which has been shown below:" }, { "code": "# 2-D Listmatrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Nested List Comprehension to flatten a given 2-D matrixflatten_matrix = [val for sublist in matrix for val in sublist] print(flatten_matrix)", "e": 2965, "s": 2767, "text": null }, { "code": null, "e": 2994, "s": 2965, "text": "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" }, { "code": null, "e": 3007, "s": 2994, "text": "Explanation:" }, { "code": null, "e": 3187, "s": 3007, "text": "In this case, we need to loop over each element in the given 2-D list and append itto another list. For better understanding, we can divide the list comprehension intothree parts:" }, { "code": null, "e": 3287, "s": 3187, "text": "flatten_matrix = [val\n for sublist in matrix\n for val in sublist]" }, { "code": null, "e": 3418, "s": 3287, "text": "The first line suggests what we want to append to the list. The second line is theouter loop and the third line is the inner loop." }, { "code": null, "e": 3508, "s": 3418, "text": "‘for sublist in matrix’ returns the sublists inside the matrix one by one which would be:" }, { "code": null, "e": 3540, "s": 3508, "text": "[1, 2, 3], [4, 5], [6, 7, 8, 9]" }, { "code": null, "e": 3604, "s": 3540, "text": "‘for val in sublist’ returns all the values inside the sublist." }, { "code": null, "e": 3694, "s": 3604, "text": "Hence if sublist = [1, 2, 3], ‘for val in sublist’ –> gives 1, 2, 3 as output one by one." }, { "code": null, "e": 3769, "s": 3694, "text": "For every such val, we get the output as val and we append it to the list." }, { "code": null, "e": 3780, "s": 3769, "text": "Example 3:" }, { "code": null, "e": 3885, "s": 3780, "text": "Suppose I want to flatten a given 2-D list and only include those strings whose lengths are less than 6:" }, { "code": null, "e": 3990, "s": 3885, "text": "planets = [[‘Mercury’, ‘Venus’, ‘Earth’], [‘Mars’, ‘Jupiter’, ‘Saturn’], [‘Uranus’, ‘Neptune’, ‘Pluto’]]" }, { "code": null, "e": 4061, "s": 3990, "text": "Expected Output: flatten_planets = [‘Venus’, ‘Earth’, ‘Mars’, ‘Pluto’]" }, { "code": null, "e": 4147, "s": 4061, "text": "This can be done using an if condition inside a nested for loop which is shown below:" }, { "code": "# 2-D List of planetsplanets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']] flatten_planets = [] for sublist in planets: for planet in sublist: if len(planet) < 6: flatten_planets.append(planet) print(flatten_planets)", "e": 4457, "s": 4147, "text": null }, { "code": null, "e": 4494, "s": 4457, "text": "['Venus', 'Earth', 'Mars', 'Pluto']\n" }, { "code": null, "e": 4577, "s": 4494, "text": "This can also be done using nested list comprehensions which has been shown below:" }, { "code": "# 2-D List of planetsplanets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']] # Nested List comprehension with an if conditionflatten_planets = [planet for sublist in planets for planet in sublist if len(planet) < 6] print(flatten_planets)", "e": 4875, "s": 4577, "text": null }, { "code": null, "e": 4912, "s": 4875, "text": "['Venus', 'Earth', 'Mars', 'Pluto']\n" }, { "code": null, "e": 4925, "s": 4912, "text": "Explanation:" }, { "code": null, "e": 5102, "s": 4925, "text": "This example is quite similar to the previous example but in this example, we justneed an extra if condition to check if the length of a particular planet is less than6 or not." }, { "code": null, "e": 5147, "s": 5102, "text": "This can be divided into 4 parts as follows:" }, { "code": null, "e": 5300, "s": 5147, "text": "flatten_planets = [planet \n for sublist in planets \n for planet in sublist \n if len(planet) < 6] \n" }, { "code": null, "e": 5307, "s": 5300, "text": "Picked" }, { "code": null, "e": 5319, "s": 5307, "text": "python-list" }, { "code": null, "e": 5343, "s": 5319, "text": "Technical Scripter 2018" }, { "code": null, "e": 5350, "s": 5343, "text": "Python" }, { "code": null, "e": 5369, "s": 5350, "text": "Technical Scripter" }, { "code": null, "e": 5381, "s": 5369, "text": "python-list" } ]
Output of Python programs | Set 10 (Exception Handling)
10 Feb, 2020 Pre-requisite: Exception Handling in PythonNote: All the programs run on python version 3 and above. 1) What is the output of the following program? data = 50try: data = data/0except ZeroDivisionError: print('Cannot divide by 0 ', end = '')else: print('Division successful ', end = '') try: data = data/5except: print('Inside except block ', end = '')else: print('GFG', end = '') a) Cannot divide by 0 GFGb) Cannot divide by 0c) Cannot divide by 0 Inside except block GFGd) Cannot divide by 0 Inside except block Ans. (a)Explanation: The else block of code is executed only when there occurs no exception in try block. 2) What is the output of the following program? data = 50try: data = data/10except ZeroDivisionError: print('Cannot divide by 0 ', end = '')finally: print('GeeksforGeeks ', end = '')else: print('Division successful ', end = '') a) Runtime errorb) Cannot divide by 0 GeeksforGeeksc) GeeksforGeeks Division successfuld) GeeksforGeeks Ans. (a)Explanation: else block following a finally block is not allowed in python. Python throws syntax error when such format is used. 3) What is the output of the following program? value = [1, 2, 3, 4]data = 0try: data = value[4]except IndexError: print('GFG', end = '')except: print('GeeksforGeeks ', end = '') a) GeeksforGeeksb) GFGc) GFG GeeksforGeeksd) Compilation error Ans. (b)Explanation: At a time only one exception is caught, even though the throw exception in the try block is likely to belong to multiple exception type. 4) What is the output of the following program? value = [1, 2, 3, 4]data = 0try: data = value[3]except IndexError: print('GFG IndexError ', end = '')except: print('GeeksforGeeks IndexError ', end = '')finally: print('Geeks IndexError ', end = '') data = 10try: data = data/0except ZeroDivisionError: print('GFG ZeroDivisionError ', end = '')finally: print('Geeks ZeroDivisionError ') a) GFG ZeroDivisionError GFG ZeroDivisionErrorb) GFG ZeroDivisionError Geeks ZeroDivisionErrorc) Geeks IndexError GFG ZeroDivisionError Geeks ZeroDivisionErrord) Geeks IndexError GFG ZeroDivisionError Ans. (c)Explanation: finally block of code is always executed whether the exception occurs or not. If exception occurs, the except block is executed first followed by finally block. 5) What is the output of the following program? value = [1, 2, 3, 4, 5]try: value = value[5]/0except (IndexError, ZeroDivisionError): print('GeeksforGeeks ', end = '')else: print('GFG ', end = '')finally: print('Geeks ', end = '') a) Compilation errorb) Runtime errorc) GeeksforGeeks GFG Geeksd) GeeksforGeeks Geeks Ans. (d)Explanation: An else block between finally block between try is defined in python. If there is no exception in try block then else is executed and then the finally block. An except block can be defined to catch multiple exception. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. chaudhary_19 Python-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Feb, 2020" }, { "code": null, "e": 153, "s": 52, "text": "Pre-requisite: Exception Handling in PythonNote: All the programs run on python version 3 and above." }, { "code": null, "e": 201, "s": 153, "text": "1) What is the output of the following program?" }, { "code": "data = 50try: data = data/0except ZeroDivisionError: print('Cannot divide by 0 ', end = '')else: print('Division successful ', end = '') try: data = data/5except: print('Inside except block ', end = '')else: print('GFG', end = '')", "e": 451, "s": 201, "text": null }, { "code": null, "e": 584, "s": 451, "text": "a) Cannot divide by 0 GFGb) Cannot divide by 0c) Cannot divide by 0 Inside except block GFGd) Cannot divide by 0 Inside except block" }, { "code": null, "e": 690, "s": 584, "text": "Ans. (a)Explanation: The else block of code is executed only when there occurs no exception in try block." }, { "code": null, "e": 738, "s": 690, "text": "2) What is the output of the following program?" }, { "code": "data = 50try: data = data/10except ZeroDivisionError: print('Cannot divide by 0 ', end = '')finally: print('GeeksforGeeks ', end = '')else: print('Division successful ', end = '')", "e": 930, "s": 738, "text": null }, { "code": null, "e": 1034, "s": 930, "text": "a) Runtime errorb) Cannot divide by 0 GeeksforGeeksc) GeeksforGeeks Division successfuld) GeeksforGeeks" }, { "code": null, "e": 1171, "s": 1034, "text": "Ans. (a)Explanation: else block following a finally block is not allowed in python. Python throws syntax error when such format is used." }, { "code": null, "e": 1219, "s": 1171, "text": "3) What is the output of the following program?" }, { "code": "value = [1, 2, 3, 4]data = 0try: data = value[4]except IndexError: print('GFG', end = '')except: print('GeeksforGeeks ', end = '')", "e": 1359, "s": 1219, "text": null }, { "code": null, "e": 1422, "s": 1359, "text": "a) GeeksforGeeksb) GFGc) GFG GeeksforGeeksd) Compilation error" }, { "code": null, "e": 1580, "s": 1422, "text": "Ans. (b)Explanation: At a time only one exception is caught, even though the throw exception in the try block is likely to belong to multiple exception type." }, { "code": null, "e": 1628, "s": 1580, "text": "4) What is the output of the following program?" }, { "code": "value = [1, 2, 3, 4]data = 0try: data = value[3]except IndexError: print('GFG IndexError ', end = '')except: print('GeeksforGeeks IndexError ', end = '')finally: print('Geeks IndexError ', end = '') data = 10try: data = data/0except ZeroDivisionError: print('GFG ZeroDivisionError ', end = '')finally: print('Geeks ZeroDivisionError ')", "e": 1991, "s": 1628, "text": null }, { "code": null, "e": 2192, "s": 1991, "text": "a) GFG ZeroDivisionError GFG ZeroDivisionErrorb) GFG ZeroDivisionError Geeks ZeroDivisionErrorc) Geeks IndexError GFG ZeroDivisionError Geeks ZeroDivisionErrord) Geeks IndexError GFG ZeroDivisionError" }, { "code": null, "e": 2374, "s": 2192, "text": "Ans. (c)Explanation: finally block of code is always executed whether the exception occurs or not. If exception occurs, the except block is executed first followed by finally block." }, { "code": null, "e": 2422, "s": 2374, "text": "5) What is the output of the following program?" }, { "code": "value = [1, 2, 3, 4, 5]try: value = value[5]/0except (IndexError, ZeroDivisionError): print('GeeksforGeeks ', end = '')else: print('GFG ', end = '')finally: print('Geeks ', end = '')", "e": 2617, "s": 2422, "text": null }, { "code": null, "e": 2702, "s": 2617, "text": "a) Compilation errorb) Runtime errorc) GeeksforGeeks GFG Geeksd) GeeksforGeeks Geeks" }, { "code": null, "e": 2941, "s": 2702, "text": "Ans. (d)Explanation: An else block between finally block between try is defined in python. If there is no exception in try block then else is executed and then the finally block. An except block can be defined to catch multiple exception." }, { "code": null, "e": 3241, "s": 2941, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3366, "s": 3241, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3379, "s": 3366, "text": "chaudhary_19" }, { "code": null, "e": 3393, "s": 3379, "text": "Python-Output" }, { "code": null, "e": 3408, "s": 3393, "text": "Program Output" } ]
Creating objects in JavaScript (4 Different Ways)
23 Jun, 2020 JavaScript is a flexible object-oriented language when it comes to syntax. In this article, we will see the different ways to instantiate objects in JavaScript.Before we proceed it is important to note that JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have an inheritance of properties and their values. Creating object with a constructor: One of the easiest way to instantiate an object in JavaScript. Constructor is nothing but a function and with help of new keyword, constructor function allows to create multiple objects of same flavor as shown below: //simple functionfunction vehicle(name,maker,engine){ this.name = name; this.maker = maker; this.engine = engine;}//new keyword to create an objectlet car = new vehicle('GT','BMW','1998cc');//property accessorsconsole.log(car.name);console.log(car.maker);console.log(car['engine']); Output:Explanation: A class in OOPs have two major components, certain parameters and few member functions. In this method we declare a function similar to a class, there are three parameters, name, maker and engine ( the this keyword is used to differentiate the name,maker,engine of the class to the name,maker,engine of the arguments that are being supplied.). We then simple create an object obj of the vehicle, initialize it and call it’s method. Using object literals: Literals are smaller and simpler ways to define objects.We simple define the property and values inside curly braces as shown below: //creating js objects with object literallet car = { name : 'GT', maker : 'BMW', engine : '1998cc'};//property accessorconsole.log(car.name); //dot notationconsole.log(car['maker']); //bracket notation Output:In the above code we created a simple object named car with the help of object literal,having properties like name,maker,engine.Then we make use of the property accessor methods(Dot notation,Bracket notation) to console.log the values.Now let’s see how we can add more properties to an already defined object: let car = { name : 'GT', maker : 'BMW', engine : '1998cc'};//adding property to the objectcar.brakesType = 'All Disc';console.log(car); We added new property called brakesType to the above defined car object and when we console.log the entire object we get:Output:Methods can also be part of object while creation or can be added later like properties as shown below: //adding methods to the car objectlet car = { name : 'GT', maker : 'BMW', engine : '1998cc', start : function(){ console.log('Starting the engine...'); }};car.start();// Adding method stop() later to the objectcar.stop = function() { console.log('Applying Brake...'); }car.stop(); Output:Explanation:In the above code start method was added to the car object and later called by the car.start() and also the stop method was added too after the object was already declared. Creating object with Object.create() method: The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.Example: const coder = { isStudying : false, printIntroduction : function(){ console.log(`My name is ${this.name}. Am I studying?: ${this.isStudying}`); }};const me = Object.create(coder);me.name = 'Mukul';me.isStudying = true;me.printIntroduction(); Output: Using es6 classes: ES6 supports class concept like any other Statically typed or object oriented language. So, object can be created out of a class in javascript as well as shown below: //using es6 classesclass Vehicle { constructor(name, maker, engine) { this.name = name; this.maker = maker; this.engine = engine; }} let car1 = new Vehicle('GT', 'BMW', '1998cc'); console.log(car1.name); //GT Output: immukul javascript-basics javascript-object javascript-oop JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to get character array from string in JavaScript? JavaScript | Promises Node.js | fs.writeFileSync() Method How to filter object array based on attributes? How to Use the JavaScript Fetch API to Get Data?
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2020" }, { "code": null, "e": 527, "s": 54, "text": "JavaScript is a flexible object-oriented language when it comes to syntax. In this article, we will see the different ways to instantiate objects in JavaScript.Before we proceed it is important to note that JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have an inheritance of properties and their values." }, { "code": null, "e": 563, "s": 527, "text": "Creating object with a constructor:" }, { "code": null, "e": 780, "s": 563, "text": "One of the easiest way to instantiate an object in JavaScript. Constructor is nothing but a function and with help of new keyword, constructor function allows to create multiple objects of same flavor as shown below:" }, { "code": "//simple functionfunction vehicle(name,maker,engine){ this.name = name; this.maker = maker; this.engine = engine;}//new keyword to create an objectlet car = new vehicle('GT','BMW','1998cc');//property accessorsconsole.log(car.name);console.log(car.maker);console.log(car['engine']);", "e": 1073, "s": 780, "text": null }, { "code": null, "e": 1525, "s": 1073, "text": "Output:Explanation: A class in OOPs have two major components, certain parameters and few member functions. In this method we declare a function similar to a class, there are three parameters, name, maker and engine ( the this keyword is used to differentiate the name,maker,engine of the class to the name,maker,engine of the arguments that are being supplied.). We then simple create an object obj of the vehicle, initialize it and call it’s method." }, { "code": null, "e": 1550, "s": 1527, "text": "Using object literals:" }, { "code": null, "e": 1683, "s": 1550, "text": "Literals are smaller and simpler ways to define objects.We simple define the property and values inside curly braces as shown below:" }, { "code": "//creating js objects with object literallet car = { name : 'GT', maker : 'BMW', engine : '1998cc'};//property accessorconsole.log(car.name); //dot notationconsole.log(car['maker']); //bracket notation", "e": 1894, "s": 1683, "text": null }, { "code": null, "e": 2211, "s": 1894, "text": "Output:In the above code we created a simple object named car with the help of object literal,having properties like name,maker,engine.Then we make use of the property accessor methods(Dot notation,Bracket notation) to console.log the values.Now let’s see how we can add more properties to an already defined object:" }, { "code": "let car = { name : 'GT', maker : 'BMW', engine : '1998cc'};//adding property to the objectcar.brakesType = 'All Disc';console.log(car);", "e": 2356, "s": 2211, "text": null }, { "code": null, "e": 2588, "s": 2356, "text": "We added new property called brakesType to the above defined car object and when we console.log the entire object we get:Output:Methods can also be part of object while creation or can be added later like properties as shown below:" }, { "code": "//adding methods to the car objectlet car = { name : 'GT', maker : 'BMW', engine : '1998cc', start : function(){ console.log('Starting the engine...'); }};car.start();// Adding method stop() later to the objectcar.stop = function() { console.log('Applying Brake...'); }car.stop();", "e": 2895, "s": 2588, "text": null }, { "code": null, "e": 3087, "s": 2895, "text": "Output:Explanation:In the above code start method was added to the car object and later called by the car.start() and also the stop method was added too after the object was already declared." }, { "code": null, "e": 3134, "s": 3089, "text": "Creating object with Object.create() method:" }, { "code": null, "e": 3262, "s": 3134, "text": "The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.Example:" }, { "code": "const coder = { isStudying : false, printIntroduction : function(){ console.log(`My name is ${this.name}. Am I studying?: ${this.isStudying}`); }};const me = Object.create(coder);me.name = 'Mukul';me.isStudying = true;me.printIntroduction();", "e": 3520, "s": 3262, "text": null }, { "code": null, "e": 3528, "s": 3520, "text": "Output:" }, { "code": null, "e": 3547, "s": 3528, "text": "Using es6 classes:" }, { "code": null, "e": 3714, "s": 3547, "text": "ES6 supports class concept like any other Statically typed or object oriented language. So, object can be created out of a class in javascript as well as shown below:" }, { "code": "//using es6 classesclass Vehicle { constructor(name, maker, engine) { this.name = name; this.maker = maker; this.engine = engine; }} let car1 = new Vehicle('GT', 'BMW', '1998cc'); console.log(car1.name); //GT", "e": 3938, "s": 3714, "text": null }, { "code": null, "e": 3946, "s": 3938, "text": "Output:" }, { "code": null, "e": 3954, "s": 3946, "text": "immukul" }, { "code": null, "e": 3972, "s": 3954, "text": "javascript-basics" }, { "code": null, "e": 3990, "s": 3972, "text": "javascript-object" }, { "code": null, "e": 4005, "s": 3990, "text": "javascript-oop" }, { "code": null, "e": 4016, "s": 4005, "text": "JavaScript" }, { "code": null, "e": 4114, "s": 4016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4175, "s": 4114, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4247, "s": 4175, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4287, "s": 4247, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4329, "s": 4287, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4370, "s": 4329, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4424, "s": 4370, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 4446, "s": 4424, "text": "JavaScript | Promises" }, { "code": null, "e": 4482, "s": 4446, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 4530, "s": 4482, "text": "How to filter object array based on attributes?" } ]
Scanner nextLong() method in Java with Examples
12 Oct, 2018 The nextLong(radix) method of java.util.Scanner class scans the next token of the input as a long. If the translation is successful, the scanner advances past the input that matched. If the parameter radix is not passed, then it behaves similarly as nextLong(radix) where the radix is assumed to be the default radix. Syntax: public long nextLong() Parameters: The function accepts a parameter radix which is used to interpret the token as a long value. Return Value: This function returns the long scanned from the input. Exceptions: The function throws three exceptions as described below: InputMismatchException: if the next token does not matches the Integer regular expression, or is out of range NoSuchElementException: throws if input is exhausted IllegalStateException: throws if this scanner is closed Below programs illustrate the above function: Program 1: // Java program to illustrate the// nextLong() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Long, // print found and the Long if (scanner.hasNextLong()) { System.out.println("Found Long value :" + scanner.nextLong()); } // if no Long is found, // print "Not Found:" and the token else { System.out.println("Not found Long value :" + scanner.next()); } } scanner.close(); }} Not found Long value :Gfg Found Long value :9 Not found Long value :+ Found Long value :6 Not found Long value := Not found Long value :12.0 Program 2: // Java program to illustrate the// nextLong() method of Scanner class in Java// with parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Long, // print found and the Long if (scanner.hasNextLong()) { System.out.println("Found Long value :" + scanner.nextLong(12)); } // if no Long is found, // print "Not Found:" and the token else { System.out.println("Not found Long value :" + scanner.next()); } } scanner.close(); }} Not found Long value :Gfg Found Long value :9 Not found Long value :+ Found Long value :6 Not found Long value := Not found Long value :12.0 Program 3: To demonstrate InputMismatchException // Java program to illustrate the// nextLong() method of Scanner class in Java// InputMismatchException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Long, // print found and the Long // since the value 60 is out of range // it throws an exception System.out.println("Next Long value :" + scanner.nextLong()); } scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } }} Exception thrown: java.util.InputMismatchException Program 4: To demonstrate NoSuchElementException // Java program to illustrate the// nextLong() method of Scanner class in Java// NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // Trying to get the next Long value // more times than the scanner // Hence it will throw exception for (int i = 0; i < 5; i++) { // if the next is a Long, // print found and the Long if (scanner.hasNextLong()) { System.out.println("Found Long value :" + scanner.nextLong()); } // if no Long is found, // print "Not Found:" and the token else { System.out.println("Not found Long value :" + scanner.next()); } } scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } }} Not found Long value :Gfg Exception thrown: java.util.NoSuchElementException Program 5: To demonstrate IllegalStateException // Java program to illustrate the// nextLong() method of Scanner class in Java// IllegalStateException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); System.out.println("Scanner Closed"); System.out.println("Trying to get " + "next Long value"); while (scanner.hasNext()) { // if the next is a Long, // print found and the Long if (scanner.hasNextLong()) { System.out.println("Found Long value :" + scanner.nextLong()); } // if no Long is found, // print "Not Found:" and the token else { System.out.println("Not found Long value :" + scanner.next()); } } } catch (Exception e) { System.out.println("Exception thrown: " + e); } }} Scanner Closed Trying to get next Long value Exception thrown: java.lang.IllegalStateException: Scanner closed Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLong(int) Java - util package Java-Functions Java-Library Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2018" }, { "code": null, "e": 346, "s": 28, "text": "The nextLong(radix) method of java.util.Scanner class scans the next token of the input as a long. If the translation is successful, the scanner advances past the input that matched. If the parameter radix is not passed, then it behaves similarly as nextLong(radix) where the radix is assumed to be the default radix." }, { "code": null, "e": 354, "s": 346, "text": "Syntax:" }, { "code": null, "e": 377, "s": 354, "text": "public long nextLong()" }, { "code": null, "e": 482, "s": 377, "text": "Parameters: The function accepts a parameter radix which is used to interpret the token as a long value." }, { "code": null, "e": 551, "s": 482, "text": "Return Value: This function returns the long scanned from the input." }, { "code": null, "e": 620, "s": 551, "text": "Exceptions: The function throws three exceptions as described below:" }, { "code": null, "e": 730, "s": 620, "text": "InputMismatchException: if the next token does not matches the Integer regular expression, or is out of range" }, { "code": null, "e": 783, "s": 730, "text": "NoSuchElementException: throws if input is exhausted" }, { "code": null, "e": 839, "s": 783, "text": "IllegalStateException: throws if this scanner is closed" }, { "code": null, "e": 885, "s": 839, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 896, "s": 885, "text": "Program 1:" }, { "code": "// Java program to illustrate the// nextLong() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Long, // print found and the Long if (scanner.hasNextLong()) { System.out.println(\"Found Long value :\" + scanner.nextLong()); } // if no Long is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Long value :\" + scanner.next()); } } scanner.close(); }}", "e": 1811, "s": 896, "text": null }, { "code": null, "e": 1953, "s": 1811, "text": "Not found Long value :Gfg\nFound Long value :9\nNot found Long value :+\nFound Long value :6\nNot found Long value :=\nNot found Long value :12.0\n" }, { "code": null, "e": 1964, "s": 1953, "text": "Program 2:" }, { "code": "// Java program to illustrate the// nextLong() method of Scanner class in Java// with parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Long, // print found and the Long if (scanner.hasNextLong()) { System.out.println(\"Found Long value :\" + scanner.nextLong(12)); } // if no Long is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Long value :\" + scanner.next()); } } scanner.close(); }}", "e": 2878, "s": 1964, "text": null }, { "code": null, "e": 3020, "s": 2878, "text": "Not found Long value :Gfg\nFound Long value :9\nNot found Long value :+\nFound Long value :6\nNot found Long value :=\nNot found Long value :12.0\n" }, { "code": null, "e": 3069, "s": 3020, "text": "Program 3: To demonstrate InputMismatchException" }, { "code": "// Java program to illustrate the// nextLong() method of Scanner class in Java// InputMismatchException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Long, // print found and the Long // since the value 60 is out of range // it throws an exception System.out.println(\"Next Long value :\" + scanner.nextLong()); } scanner.close(); } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 3959, "s": 3069, "text": null }, { "code": null, "e": 4011, "s": 3959, "text": "Exception thrown: java.util.InputMismatchException\n" }, { "code": null, "e": 4060, "s": 4011, "text": "Program 4: To demonstrate NoSuchElementException" }, { "code": "// Java program to illustrate the// nextLong() method of Scanner class in Java// NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // Trying to get the next Long value // more times than the scanner // Hence it will throw exception for (int i = 0; i < 5; i++) { // if the next is a Long, // print found and the Long if (scanner.hasNextLong()) { System.out.println(\"Found Long value :\" + scanner.nextLong()); } // if no Long is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Long value :\" + scanner.next()); } } scanner.close(); } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 5298, "s": 4060, "text": null }, { "code": null, "e": 5376, "s": 5298, "text": "Not found Long value :Gfg\nException thrown: java.util.NoSuchElementException\n" }, { "code": null, "e": 5424, "s": 5376, "text": "Program 5: To demonstrate IllegalStateException" }, { "code": "// Java program to illustrate the// nextLong() method of Scanner class in Java// IllegalStateException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); System.out.println(\"Scanner Closed\"); System.out.println(\"Trying to get \" + \"next Long value\"); while (scanner.hasNext()) { // if the next is a Long, // print found and the Long if (scanner.hasNextLong()) { System.out.println(\"Found Long value :\" + scanner.nextLong()); } // if no Long is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Long value :\" + scanner.next()); } } } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 6722, "s": 5424, "text": null }, { "code": null, "e": 6834, "s": 6722, "text": "Scanner Closed\nTrying to get next Long value\nException thrown: java.lang.IllegalStateException: Scanner closed\n" }, { "code": null, "e": 6924, "s": 6834, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLong(int)" }, { "code": null, "e": 6944, "s": 6924, "text": "Java - util package" }, { "code": null, "e": 6959, "s": 6944, "text": "Java-Functions" }, { "code": null, "e": 6972, "s": 6959, "text": "Java-Library" }, { "code": null, "e": 6977, "s": 6972, "text": "Java" }, { "code": null, "e": 6982, "s": 6977, "text": "Java" } ]
Plot a 3D Contour in MATLAB
21 Apr, 2021 Contour plots are used to show 3D surfaces by plotting z- slides on a 2D surface. A contour plot is also called a line plot. In contour, we have 3 variables x, y, z. The x, y variables are used to give the values for z, ( z=f(x, y)). The x and y variables are usually in a grid called meshgrid. There are various contour plots in MATLAB like contour, contourf, contour3, contourc, countourslice, clabel, and fcontour. In this article, we will see how to plot 3D contour in MATLAB. To plot 3D contour we will use countour3() to plot different types of 3D modules. Syntax: contour3(X,Y,Z): Specifies the x and y coordinates for the values in Z. contour3(Z): Creates a 3-D contour plot containing the isolines of matrix Z, where Z contains height values on the x-y plane. contour3(___,levels): Specify levels as a scalar value n to display the contour lines at n automatically chosen levels (heights). contour3(___,LineSpec): Specifies the style and color of the contour line. Step-wise Approach: Enter the inputs for x and y in meshgrid function. Matlab % plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5); Pass the value for z using x and y in an equation. Matlab % give any equation for z variablez = x.^2 + y.^2 ; % disp is used to display the % value for zdisp(z); Use contour3 to plot 3d contour and to label the axis use label() method. Matlab % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to % display the height for the contourlinescontour3(z,25); % to label x ,y ,z axis and title.xlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour'); Below is the complete program: Matlab % code for 3D plot% plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5); % give any equation for z variablez = x.^2 + y.^2 ;disp(z); % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used % to display the height for the contour% linescontour3(z,25); % to label x ,y ,z axis and title.xlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour'); Output: Example 1: Here is another example similar to the previous one. Matlab % code for 3D plot,% plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5); % give any equation for z variablez = x.^2 - y.^2 ;disp(z); % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to% display the height for the contourlinescontour3(z,25); % to label x ,y , z axis and titlexlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour'); Output: Example 2: MATLAB program to generate a 3D Contour: Matlab % code for 3D plot,% plot the points for x and y[x,y]=meshgrid(-7 : 0.1 : 7); % give any equation for z variablez = sin(x)+ cos(y) ;disp(z); % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to % display the height for the contour% linescontour3(z,25); % to label x ,y and z axisxlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour'); Output: MATLAB-graphs Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Apr, 2021" }, { "code": null, "e": 349, "s": 54, "text": "Contour plots are used to show 3D surfaces by plotting z- slides on a 2D surface. A contour plot is also called a line plot. In contour, we have 3 variables x, y, z. The x, y variables are used to give the values for z, ( z=f(x, y)). The x and y variables are usually in a grid called meshgrid." }, { "code": null, "e": 618, "s": 349, "text": "There are various contour plots in MATLAB like contour, contourf, contour3, contourc, countourslice, clabel, and fcontour. In this article, we will see how to plot 3D contour in MATLAB. To plot 3D contour we will use countour3() to plot different types of 3D modules. " }, { "code": null, "e": 626, "s": 618, "text": "Syntax:" }, { "code": null, "e": 698, "s": 626, "text": "contour3(X,Y,Z): Specifies the x and y coordinates for the values in Z." }, { "code": null, "e": 824, "s": 698, "text": "contour3(Z): Creates a 3-D contour plot containing the isolines of matrix Z, where Z contains height values on the x-y plane." }, { "code": null, "e": 954, "s": 824, "text": "contour3(___,levels): Specify levels as a scalar value n to display the contour lines at n automatically chosen levels (heights)." }, { "code": null, "e": 1029, "s": 954, "text": "contour3(___,LineSpec): Specifies the style and color of the contour line." }, { "code": null, "e": 1049, "s": 1029, "text": "Step-wise Approach:" }, { "code": null, "e": 1100, "s": 1049, "text": "Enter the inputs for x and y in meshgrid function." }, { "code": null, "e": 1107, "s": 1100, "text": "Matlab" }, { "code": "% plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5);", "e": 1165, "s": 1107, "text": null }, { "code": null, "e": 1216, "s": 1165, "text": "Pass the value for z using x and y in an equation." }, { "code": null, "e": 1223, "s": 1216, "text": "Matlab" }, { "code": "% give any equation for z variablez = x.^2 + y.^2 ; % disp is used to display the % value for zdisp(z);", "e": 1328, "s": 1223, "text": null }, { "code": null, "e": 1402, "s": 1328, "text": "Use contour3 to plot 3d contour and to label the axis use label() method." }, { "code": null, "e": 1409, "s": 1402, "text": "Matlab" }, { "code": "% to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to % display the height for the contourlinescontour3(z,25); % to label x ,y ,z axis and title.xlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour');", "e": 1653, "s": 1409, "text": null }, { "code": null, "e": 1684, "s": 1653, "text": "Below is the complete program:" }, { "code": null, "e": 1691, "s": 1684, "text": "Matlab" }, { "code": "% code for 3D plot% plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5); % give any equation for z variablez = x.^2 + y.^2 ;disp(z); % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used % to display the height for the contour% linescontour3(z,25); % to label x ,y ,z axis and title.xlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour');", "e": 2075, "s": 1691, "text": null }, { "code": null, "e": 2083, "s": 2075, "text": "Output:" }, { "code": null, "e": 2094, "s": 2083, "text": "Example 1:" }, { "code": null, "e": 2147, "s": 2094, "text": "Here is another example similar to the previous one." }, { "code": null, "e": 2154, "s": 2147, "text": "Matlab" }, { "code": "% code for 3D plot,% plot the points for x and y[x,y]=meshgrid(-5 : 0.1 :5); % give any equation for z variablez = x.^2 - y.^2 ;disp(z); % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to% display the height for the contourlinescontour3(z,25); % to label x ,y , z axis and titlexlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour');", "e": 2536, "s": 2154, "text": null }, { "code": null, "e": 2544, "s": 2536, "text": "Output:" }, { "code": null, "e": 2555, "s": 2544, "text": "Example 2:" }, { "code": null, "e": 2596, "s": 2555, "text": "MATLAB program to generate a 3D Contour:" }, { "code": null, "e": 2603, "s": 2596, "text": "Matlab" }, { "code": "% code for 3D plot,% plot the points for x and y[x,y]=meshgrid(-7 : 0.1 : 7); % give any equation for z variablez = sin(x)+ cos(y) ;disp(z); % to plot the 3D surface use contour3()% contour3(z ,levels), levels is used to % display the height for the contour% linescontour3(z,25); % to label x ,y and z axisxlabel('x-axis');ylabel('y-axis');zlabel('z-axis');title('3D contour');", "e": 2984, "s": 2603, "text": null }, { "code": null, "e": 2992, "s": 2984, "text": "Output:" }, { "code": null, "e": 3006, "s": 2992, "text": "MATLAB-graphs" }, { "code": null, "e": 3013, "s": 3006, "text": "Picked" }, { "code": null, "e": 3020, "s": 3013, "text": "MATLAB" } ]
Turn on or off bulb using JavaScript
19 Feb, 2019 Write a JavaScript code that turns ON and OFF the Light Bulb.Syntax: img src = URl or img src = image_name.jpg Here the src property sets or returns the value of the src attribute of an image. The required src attribute specifies the URL of an image.There are two states of the bulb is used which are specified below-Initial state of bulb (OFF STATE): After clicking on bulb (ON STATE): JavaScript code to illustrate this topic: <html> <body> <!-- onclick event is generated and it calls turnOnOff function --> <!-- OFFbulb.jpg is the turn off bulb image --><img id="Image" onclick="turnOnOff()" src="https://media.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg"> <p>Click on the bulb to turn it ON and OFF</p> <script> // implementation of turnOnOff function --> function turnOnOff() // taking image in image variable var image = document.getElementById('Image'); //Match the image name //whether it is ONbulb or OFFbulb //change image to OFFbulb.jpg if //it match with ONbulb otherwise //change it to ONbulb.jpg --> if (image.src.match("ONbulb")) image.src = "https://media.geeksforgeeks.org/ wp-content/uploads/OFFbulb.jpg"; else image.src = "https://media.geeksforgeeks.org/ wp-content/uploads/ONbulb.jpg"; } </script></body> </html> Output:Before clicking on the bulb-After clicking on the bulb- javascript-basics JavaScript-Misc JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Feb, 2019" }, { "code": null, "e": 121, "s": 52, "text": "Write a JavaScript code that turns ON and OFF the Light Bulb.Syntax:" }, { "code": null, "e": 169, "s": 121, "text": "img src = URl\n or\nimg src = image_name.jpg\n" }, { "code": null, "e": 410, "s": 169, "text": "Here the src property sets or returns the value of the src attribute of an image. The required src attribute specifies the URL of an image.There are two states of the bulb is used which are specified below-Initial state of bulb (OFF STATE):" }, { "code": null, "e": 445, "s": 410, "text": "After clicking on bulb (ON STATE):" }, { "code": null, "e": 487, "s": 445, "text": "JavaScript code to illustrate this topic:" }, { "code": "<html> <body> <!-- onclick event is generated and it calls turnOnOff function --> <!-- OFFbulb.jpg is the turn off bulb image --><img id=\"Image\" onclick=\"turnOnOff()\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg\"> <p>Click on the bulb to turn it ON and OFF</p> <script> // implementation of turnOnOff function --> function turnOnOff() // taking image in image variable var image = document.getElementById('Image'); //Match the image name //whether it is ONbulb or OFFbulb //change image to OFFbulb.jpg if //it match with ONbulb otherwise //change it to ONbulb.jpg --> if (image.src.match(\"ONbulb\")) image.src = \"https://media.geeksforgeeks.org/ wp-content/uploads/OFFbulb.jpg\"; else image.src = \"https://media.geeksforgeeks.org/ wp-content/uploads/ONbulb.jpg\"; } </script></body> </html>", "e": 1433, "s": 487, "text": null }, { "code": null, "e": 1496, "s": 1433, "text": "Output:Before clicking on the bulb-After clicking on the bulb-" }, { "code": null, "e": 1514, "s": 1496, "text": "javascript-basics" }, { "code": null, "e": 1530, "s": 1514, "text": "JavaScript-Misc" }, { "code": null, "e": 1541, "s": 1530, "text": "JavaScript" } ]
Hashtable containsKey() Method in Java
28 Jun, 2018 The java.util.Hashtable.containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table. Syntax: Hash_table.containsKey(key_element) Parameters: The method takes just one parameter key_element which refers to the key whose presence is supposed to be checked inside a Hashtable. Return Value: The method returns boolean true if the key is present in the Hashtable otherwise it returns false. Below programs are used to illustrate the working of java.util.Hashtable.containsKey() Method:Program 1: // Java code to illustrate the containsKey() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Putting values into the table hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Displaying the Hashtable System.out.println("Initial Table is: " + hash_table); // Checking for the key_element '20' System.out.println("Is the key '20' present? " + hash_table.containsKey(20)); // Checking for the key_element '5' System.out.println("Is the key '5' present? " + hash_table.containsKey(5)); }} Initial Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes} Is the key '20' present? true Is the key '5' present? false Program 2: // Java code to illustrate the containsKey() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table= new Hashtable<String, Integer>(); // Putting values into the table hash_table.put("Geeks", 10); hash_table.put("4", 15); hash_table.put("Geeks", 20); hash_table.put("Welcomes", 25); hash_table.put("You", 30); // Displaying the Hashtable System.out.println("Initial Table is: " + hash_table); // Checking for the key_element 'Welcomes' System.out.println("Is the key 'Welcomes' present? " + hash_table.containsKey("Welcomes")); // Checking for the key_element 'World' System.out.println("Is the key 'World' present? " + hash_table.containsKey("World")); }} Initial Table is: {You=30, Welcomes=25, 4=15, Geeks=20} Is the key 'Welcomes' present? true Is the key 'World' present? false Note: The same operation can be performed with any type of variation and combination of different data types. Java - util package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2018" }, { "code": null, "e": 249, "s": 28, "text": "The java.util.Hashtable.containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table." }, { "code": null, "e": 257, "s": 249, "text": "Syntax:" }, { "code": null, "e": 293, "s": 257, "text": "Hash_table.containsKey(key_element)" }, { "code": null, "e": 438, "s": 293, "text": "Parameters: The method takes just one parameter key_element which refers to the key whose presence is supposed to be checked inside a Hashtable." }, { "code": null, "e": 551, "s": 438, "text": "Return Value: The method returns boolean true if the key is present in the Hashtable otherwise it returns false." }, { "code": null, "e": 656, "s": 551, "text": "Below programs are used to illustrate the working of java.util.Hashtable.containsKey() Method:Program 1:" }, { "code": "// Java code to illustrate the containsKey() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Putting values into the table hash_table.put(10, \"Geeks\"); hash_table.put(15, \"4\"); hash_table.put(20, \"Geeks\"); hash_table.put(25, \"Welcomes\"); hash_table.put(30, \"You\"); // Displaying the Hashtable System.out.println(\"Initial Table is: \" + hash_table); // Checking for the key_element '20' System.out.println(\"Is the key '20' present? \" + hash_table.containsKey(20)); // Checking for the key_element '5' System.out.println(\"Is the key '5' present? \" + hash_table.containsKey(5)); }}", "e": 1534, "s": 656, "text": null }, { "code": null, "e": 1661, "s": 1534, "text": "Initial Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nIs the key '20' present? true\nIs the key '5' present? false\n" }, { "code": null, "e": 1672, "s": 1661, "text": "Program 2:" }, { "code": "// Java code to illustrate the containsKey() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table= new Hashtable<String, Integer>(); // Putting values into the table hash_table.put(\"Geeks\", 10); hash_table.put(\"4\", 15); hash_table.put(\"Geeks\", 20); hash_table.put(\"Welcomes\", 25); hash_table.put(\"You\", 30); // Displaying the Hashtable System.out.println(\"Initial Table is: \" + hash_table); // Checking for the key_element 'Welcomes' System.out.println(\"Is the key 'Welcomes' present? \" + hash_table.containsKey(\"Welcomes\")); // Checking for the key_element 'World' System.out.println(\"Is the key 'World' present? \" + hash_table.containsKey(\"World\")); }}", "e": 2583, "s": 1672, "text": null }, { "code": null, "e": 2710, "s": 2583, "text": "Initial Table is: {You=30, Welcomes=25, 4=15, Geeks=20}\nIs the key 'Welcomes' present? true\nIs the key 'World' present? false\n" }, { "code": null, "e": 2820, "s": 2710, "text": "Note: The same operation can be performed with any type of variation and combination of different data types." }, { "code": null, "e": 2840, "s": 2820, "text": "Java - util package" }, { "code": null, "e": 2845, "s": 2840, "text": "Java" }, { "code": null, "e": 2850, "s": 2845, "text": "Java" } ]
Removing Array Element and Re-Indexing in PHP
25 Jan, 2022 In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.Syntax:void unset ( mixed $var [, mixed $... ] )array_values(): This function returns all the values from the array and indexes the array numerically.Syntax:array array_values ( array $array ) unset(): This function unsets a given variable.Syntax:void unset ( mixed $var [, mixed $... ] ) void unset ( mixed $var [, mixed $... ] ) array_values(): This function returns all the values from the array and indexes the array numerically.Syntax:array array_values ( array $array ) array array_values ( array $array ) Example 1: <?php $arr1 = array( 'geeks', // [0] 'for', // [1] 'geeks' // [2] ); // remove item at index 1 which is 'for'unset($arr1[1]); // Print modified arrayvar_dump($arr1); // Re-index the array elements$arr2 = array_values($arr1); // Print re-indexed arrayvar_dump($arr2);?> array(2) { [0]=> string(5) "geeks" [2]=> string(5) "geeks" } array(2) { [0]=> string(5) "geeks" [2]=> string(5) "geeks" } We can also use array_splice() function which removes a portion of the array and replaces it with something else.Example 2: <?php $arr1 = array( 'geeks', // [0] 'for', // [1] 'geeks' // [2]); // remove item at index 1 which is 'for'array_splice($arr1, 1, 1); // Print modified arrayvar_dump($arr1);?> array(2) { [0]=> string(5) "geeks" [1]=> string(5) "geeks" } PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. manakupadhyay PHP-array Picked Technical Scripter 2018 PHP Technical Scripter PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Jan, 2022" }, { "code": null, "e": 253, "s": 52, "text": "In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically." }, { "code": null, "e": 268, "s": 253, "text": "Function Used:" }, { "code": null, "e": 508, "s": 268, "text": "unset(): This function unsets a given variable.Syntax:void unset ( mixed $var [, mixed $... ] )array_values(): This function returns all the values from the array and indexes the array numerically.Syntax:array array_values ( array $array )" }, { "code": null, "e": 604, "s": 508, "text": "unset(): This function unsets a given variable.Syntax:void unset ( mixed $var [, mixed $... ] )" }, { "code": null, "e": 646, "s": 604, "text": "void unset ( mixed $var [, mixed $... ] )" }, { "code": null, "e": 791, "s": 646, "text": "array_values(): This function returns all the values from the array and indexes the array numerically.Syntax:array array_values ( array $array )" }, { "code": null, "e": 827, "s": 791, "text": "array array_values ( array $array )" }, { "code": null, "e": 838, "s": 827, "text": "Example 1:" }, { "code": "<?php $arr1 = array( 'geeks', // [0] 'for', // [1] 'geeks' // [2] ); // remove item at index 1 which is 'for'unset($arr1[1]); // Print modified arrayvar_dump($arr1); // Re-index the array elements$arr2 = array_values($arr1); // Print re-indexed arrayvar_dump($arr2);?>", "e": 1124, "s": 838, "text": null }, { "code": null, "e": 1263, "s": 1124, "text": "array(2) {\n [0]=>\n string(5) \"geeks\"\n [2]=>\n string(5) \"geeks\"\n}\narray(2) {\n [0]=>\n string(5) \"geeks\"\n [2]=>\n string(5) \"geeks\"\n}\n" }, { "code": null, "e": 1387, "s": 1263, "text": "We can also use array_splice() function which removes a portion of the array and replaces it with something else.Example 2:" }, { "code": "<?php $arr1 = array( 'geeks', // [0] 'for', // [1] 'geeks' // [2]); // remove item at index 1 which is 'for'array_splice($arr1, 1, 1); // Print modified arrayvar_dump($arr1);?>", "e": 1576, "s": 1387, "text": null }, { "code": null, "e": 1646, "s": 1576, "text": "array(2) {\n [0]=>\n string(5) \"geeks\"\n [1]=>\n string(5) \"geeks\"\n}\n" }, { "code": null, "e": 1815, "s": 1646, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 1829, "s": 1815, "text": "manakupadhyay" }, { "code": null, "e": 1839, "s": 1829, "text": "PHP-array" }, { "code": null, "e": 1846, "s": 1839, "text": "Picked" }, { "code": null, "e": 1870, "s": 1846, "text": "Technical Scripter 2018" }, { "code": null, "e": 1874, "s": 1870, "text": "PHP" }, { "code": null, "e": 1893, "s": 1874, "text": "Technical Scripter" }, { "code": null, "e": 1897, "s": 1893, "text": "PHP" } ]
Character getType() Method in Java with examples
20 Jun, 2018 The Character.getType(char ch) is an inbuilt method in java that returns a value indicating a character’s general category. This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the getType(int) method.Syntax:public static int getType(char ch)Parameters: The method accepts one parameter ch of character datatype which refers to the character to be tested.Return value: This method returns a value of type integer representing the character’s general category.Below programs illustrates the use of Character.getType(char ch) method:Program 1:import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'K', c2 = '%'; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = "Category of " + c1 + " is " + int1; String str2 = "Category of " + c2 + " is " + int2; System.out.println( str1 ); System.out.println( str2 ); }}Output:Category of K is 1 Category of % is 24 Program 2:import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'T', c2 = '^'; // Assign getType values of c1, c2 to inyt primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = "Category of " + c1 + " is " + int1; String str2 = "Category of " + c2 + " is " + int2; System.out.println(str1); System.out.println(str2); }}Output:Category of T is 1 Category of ^ is 27 The java.lang.Character getType(int codePoint) is similar to previous method in all the manner, this method can handle supplementary characters.Syntax:public static int getType(int codePoint) Parameter: The method accepts a single parameter codePoint of integer datatype and refers to the character (Unicode code point) to be tested.Return Value: This method returns a value of type int representing the character’s general category.Below programs demonstrates the above mentioned method:Program 1:// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0037, c2 = 0x016f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( "Category of c1 is " + int1); System.out.println( "Category of c1 is " + int2); }}Output:Category of c1 is 9 Category of c1 is 2 Program 2:// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0135, c2 = 0x015f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( "Category of c1 is " + int1); System.out.println( "Category of c1 is " + int2); }}Output:Category of c1 is 2 Category of c1 is 2 Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getType(char)My Personal Notes arrow_drop_upSave The Character.getType(char ch) is an inbuilt method in java that returns a value indicating a character’s general category. This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the getType(int) method.Syntax:public static int getType(char ch)Parameters: The method accepts one parameter ch of character datatype which refers to the character to be tested.Return value: This method returns a value of type integer representing the character’s general category.Below programs illustrates the use of Character.getType(char ch) method:Program 1:import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'K', c2 = '%'; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = "Category of " + c1 + " is " + int1; String str2 = "Category of " + c2 + " is " + int2; System.out.println( str1 ); System.out.println( str2 ); }}Output:Category of K is 1 Category of % is 24 Program 2:import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'T', c2 = '^'; // Assign getType values of c1, c2 to inyt primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = "Category of " + c1 + " is " + int1; String str2 = "Category of " + c2 + " is " + int2; System.out.println(str1); System.out.println(str2); }}Output:Category of T is 1 Category of ^ is 27 Syntax: public static int getType(char ch) Parameters: The method accepts one parameter ch of character datatype which refers to the character to be tested. Return value: This method returns a value of type integer representing the character’s general category. Below programs illustrates the use of Character.getType(char ch) method:Program 1: import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'K', c2 = '%'; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = "Category of " + c1 + " is " + int1; String str2 = "Category of " + c2 + " is " + int2; System.out.println( str1 ); System.out.println( str2 ); }} Category of K is 1 Category of % is 24 Program 2: import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'T', c2 = '^'; // Assign getType values of c1, c2 to inyt primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = "Category of " + c1 + " is " + int1; String str2 = "Category of " + c2 + " is " + int2; System.out.println(str1); System.out.println(str2); }} Category of T is 1 Category of ^ is 27 The java.lang.Character getType(int codePoint) is similar to previous method in all the manner, this method can handle supplementary characters.Syntax:public static int getType(int codePoint) Parameter: The method accepts a single parameter codePoint of integer datatype and refers to the character (Unicode code point) to be tested.Return Value: This method returns a value of type int representing the character’s general category.Below programs demonstrates the above mentioned method:Program 1:// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0037, c2 = 0x016f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( "Category of c1 is " + int1); System.out.println( "Category of c1 is " + int2); }}Output:Category of c1 is 9 Category of c1 is 2 Program 2:// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0135, c2 = 0x015f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( "Category of c1 is " + int1); System.out.println( "Category of c1 is " + int2); }}Output:Category of c1 is 2 Category of c1 is 2 Syntax: public static int getType(int codePoint) Parameter: The method accepts a single parameter codePoint of integer datatype and refers to the character (Unicode code point) to be tested. Return Value: This method returns a value of type int representing the character’s general category. Below programs demonstrates the above mentioned method:Program 1: // Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0037, c2 = 0x016f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( "Category of c1 is " + int1); System.out.println( "Category of c1 is " + int2); }} Category of c1 is 9 Category of c1 is 2 Program 2: // Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0135, c2 = 0x015f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( "Category of c1 is " + int1); System.out.println( "Category of c1 is " + int2); }} Category of c1 is 2 Category of c1 is 2 Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getType(char) Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2018" }, { "code": null, "e": 3513, "s": 28, "text": "The Character.getType(char ch) is an inbuilt method in java that returns a value indicating a character’s general category. This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the getType(int) method.Syntax:public static int getType(char ch)Parameters: The method accepts one parameter ch of character datatype which refers to the character to be tested.Return value: This method returns a value of type integer representing the character’s general category.Below programs illustrates the use of Character.getType(char ch) method:Program 1:import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'K', c2 = '%'; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = \"Category of \" + c1 + \" is \" + int1; String str2 = \"Category of \" + c2 + \" is \" + int2; System.out.println( str1 ); System.out.println( str2 ); }}Output:Category of K is 1\nCategory of % is 24\nProgram 2:import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'T', c2 = '^'; // Assign getType values of c1, c2 to inyt primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = \"Category of \" + c1 + \" is \" + int1; String str2 = \"Category of \" + c2 + \" is \" + int2; System.out.println(str1); System.out.println(str2); }}Output:Category of T is 1\nCategory of ^ is 27\nThe java.lang.Character getType(int codePoint) is similar to previous method in all the manner, this method can handle supplementary characters.Syntax:public static int getType(int codePoint)\nParameter: The method accepts a single parameter codePoint of integer datatype and refers to the character (Unicode code point) to be tested.Return Value: This method returns a value of type int representing the character’s general category.Below programs demonstrates the above mentioned method:Program 1:// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0037, c2 = 0x016f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( \"Category of c1 is \" + int1); System.out.println( \"Category of c1 is \" + int2); }}Output:Category of c1 is 9\nCategory of c1 is 2\nProgram 2:// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0135, c2 = 0x015f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( \"Category of c1 is \" + int1); System.out.println( \"Category of c1 is \" + int2); }}Output:Category of c1 is 2\nCategory of c1 is 2\nReference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getType(char)My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 5270, "s": 3513, "text": "The Character.getType(char ch) is an inbuilt method in java that returns a value indicating a character’s general category. This method cannot handle supplementary characters. To support all Unicode characters, including supplementary characters, use the getType(int) method.Syntax:public static int getType(char ch)Parameters: The method accepts one parameter ch of character datatype which refers to the character to be tested.Return value: This method returns a value of type integer representing the character’s general category.Below programs illustrates the use of Character.getType(char ch) method:Program 1:import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'K', c2 = '%'; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = \"Category of \" + c1 + \" is \" + int1; String str2 = \"Category of \" + c2 + \" is \" + int2; System.out.println( str1 ); System.out.println( str2 ); }}Output:Category of K is 1\nCategory of % is 24\nProgram 2:import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'T', c2 = '^'; // Assign getType values of c1, c2 to inyt primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = \"Category of \" + c1 + \" is \" + int1; String str2 = \"Category of \" + c2 + \" is \" + int2; System.out.println(str1); System.out.println(str2); }}Output:Category of T is 1\nCategory of ^ is 27\n" }, { "code": null, "e": 5278, "s": 5270, "text": "Syntax:" }, { "code": null, "e": 5313, "s": 5278, "text": "public static int getType(char ch)" }, { "code": null, "e": 5427, "s": 5313, "text": "Parameters: The method accepts one parameter ch of character datatype which refers to the character to be tested." }, { "code": null, "e": 5532, "s": 5427, "text": "Return value: This method returns a value of type integer representing the character’s general category." }, { "code": null, "e": 5615, "s": 5532, "text": "Below programs illustrates the use of Character.getType(char ch) method:Program 1:" }, { "code": "import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'K', c2 = '%'; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = \"Category of \" + c1 + \" is \" + int1; String str2 = \"Category of \" + c2 + \" is \" + int2; System.out.println( str1 ); System.out.println( str2 ); }}", "e": 6138, "s": 5615, "text": null }, { "code": null, "e": 6178, "s": 6138, "text": "Category of K is 1\nCategory of % is 24\n" }, { "code": null, "e": 6189, "s": 6178, "text": "Program 2:" }, { "code": "import java.lang.*; public class gfg { public static void main(String[] args) { // Create 2 character primitives ch1, ch2 and assigning values char c1 = 'T', c2 = '^'; // Assign getType values of c1, c2 to inyt primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); String str1 = \"Category of \" + c1 + \" is \" + int1; String str2 = \"Category of \" + c2 + \" is \" + int2; System.out.println(str1); System.out.println(str2); }}", "e": 6707, "s": 6189, "text": null }, { "code": null, "e": 6747, "s": 6707, "text": "Category of T is 1\nCategory of ^ is 27\n" }, { "code": null, "e": 8350, "s": 6747, "text": "The java.lang.Character getType(int codePoint) is similar to previous method in all the manner, this method can handle supplementary characters.Syntax:public static int getType(int codePoint)\nParameter: The method accepts a single parameter codePoint of integer datatype and refers to the character (Unicode code point) to be tested.Return Value: This method returns a value of type int representing the character’s general category.Below programs demonstrates the above mentioned method:Program 1:// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0037, c2 = 0x016f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( \"Category of c1 is \" + int1); System.out.println( \"Category of c1 is \" + int2); }}Output:Category of c1 is 9\nCategory of c1 is 2\nProgram 2:// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0135, c2 = 0x015f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( \"Category of c1 is \" + int1); System.out.println( \"Category of c1 is \" + int2); }}Output:Category of c1 is 2\nCategory of c1 is 2\n" }, { "code": null, "e": 8358, "s": 8350, "text": "Syntax:" }, { "code": null, "e": 8400, "s": 8358, "text": "public static int getType(int codePoint)\n" }, { "code": null, "e": 8542, "s": 8400, "text": "Parameter: The method accepts a single parameter codePoint of integer datatype and refers to the character (Unicode code point) to be tested." }, { "code": null, "e": 8643, "s": 8542, "text": "Return Value: This method returns a value of type int representing the character’s general category." }, { "code": null, "e": 8709, "s": 8643, "text": "Below programs demonstrates the above mentioned method:Program 1:" }, { "code": "// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0037, c2 = 0x016f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( \"Category of c1 is \" + int1); System.out.println( \"Category of c1 is \" + int2); }}", "e": 9210, "s": 8709, "text": null }, { "code": null, "e": 9251, "s": 9210, "text": "Category of c1 is 9\nCategory of c1 is 2\n" }, { "code": null, "e": 9262, "s": 9251, "text": "Program 2:" }, { "code": "// Java program to demonstrate// the above methodimport java.lang.*; public class gfg { public static void main(String[] args) { // int primitives c1, c2 int c1 = 0x0135, c2 = 0x015f; // Assign getType values of c1, c2 to int primitives int1, int2 int int1 = Character.getType(c1); int int2 = Character.getType(c2); // Print int1, int2 values System.out.println( \"Category of c1 is \" + int1); System.out.println( \"Category of c1 is \" + int2); }}", "e": 9763, "s": 9262, "text": null }, { "code": null, "e": 9804, "s": 9763, "text": "Category of c1 is 2\nCategory of c1 is 2\n" }, { "code": null, "e": 9896, "s": 9804, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getType(char)" }, { "code": null, "e": 9911, "s": 9896, "text": "Java-Functions" }, { "code": null, "e": 9929, "s": 9911, "text": "Java-lang package" }, { "code": null, "e": 9934, "s": 9929, "text": "Java" }, { "code": null, "e": 9939, "s": 9934, "text": "Java" } ]
Update Date Field in SQL Server
10 Oct, 2021 The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. With this article, we will learn how to Update the Date Field in SQL Server. In this article, we will be making use of the Microsoft SQL Server as our database. So, we will create a database first: Step 1: Create Database Query: CREATE DATABASE GFG Step 2: Use Database Query: USE GFG Step 3: Create a table Create a table (TimeTable) in the database to store the data. Query: CREATE TABLE TimeTable( SubjectDate datetime NOT NULL , SubjectName char (10) ) Step 4: Insert the data into the database Query: /* Data Inserted for a full week dates*/ INSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('01/10/2021','DSA') INSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('02/10/2021','CD') INSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('03/10/2021','DBMS') INSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('04/10/2021','OS') Step 5: Now change the data of DateTime In the below query, the SET statement is used to set new values to the particular column, and the WHERE clause is used to select the rows for which the columns are needed to be updated. If we have not used the WHERE clause then the columns in all the rows will be updated. So the WHERE clause is used to choose the particular rows. Query: UPDATE TimeTable SET SubjectDate = '05/10/2021' WHERE SubjectName = 'DSA' Output: As we can see subject date has been changed. Picked SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Oct, 2021" }, { "code": null, "e": 417, "s": 54, "text": "The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. With this article, we will learn how to Update the Date Field in SQL Server. In this article, we will be making use of the Microsoft SQL Server as our database." }, { "code": null, "e": 454, "s": 417, "text": "So, we will create a database first:" }, { "code": null, "e": 478, "s": 454, "text": "Step 1: Create Database" }, { "code": null, "e": 485, "s": 478, "text": "Query:" }, { "code": null, "e": 505, "s": 485, "text": "CREATE DATABASE GFG" }, { "code": null, "e": 526, "s": 505, "text": "Step 2: Use Database" }, { "code": null, "e": 533, "s": 526, "text": "Query:" }, { "code": null, "e": 541, "s": 533, "text": "USE GFG" }, { "code": null, "e": 564, "s": 541, "text": "Step 3: Create a table" }, { "code": null, "e": 626, "s": 564, "text": "Create a table (TimeTable) in the database to store the data." }, { "code": null, "e": 633, "s": 626, "text": "Query:" }, { "code": null, "e": 715, "s": 633, "text": "CREATE TABLE TimeTable(\n SubjectDate datetime NOT NULL ,\n SubjectName char (10)\n)" }, { "code": null, "e": 758, "s": 715, "text": "Step 4: Insert the data into the database " }, { "code": null, "e": 765, "s": 758, "text": "Query:" }, { "code": null, "e": 1118, "s": 765, "text": "/* Data Inserted for a full week dates*/\n\nINSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('01/10/2021','DSA')\nINSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('02/10/2021','CD')\nINSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('03/10/2021','DBMS')\nINSERT INTO TimeTable (SubjectDate , SubjectName) VALUES ('04/10/2021','OS')" }, { "code": null, "e": 1158, "s": 1118, "text": "Step 5: Now change the data of DateTime" }, { "code": null, "e": 1490, "s": 1158, "text": "In the below query, the SET statement is used to set new values to the particular column, and the WHERE clause is used to select the rows for which the columns are needed to be updated. If we have not used the WHERE clause then the columns in all the rows will be updated. So the WHERE clause is used to choose the particular rows." }, { "code": null, "e": 1497, "s": 1490, "text": "Query:" }, { "code": null, "e": 1580, "s": 1497, "text": "UPDATE TimeTable \nSET SubjectDate = '05/10/2021' \nWHERE SubjectName = 'DSA' " }, { "code": null, "e": 1588, "s": 1580, "text": "Output:" }, { "code": null, "e": 1633, "s": 1588, "text": "As we can see subject date has been changed." }, { "code": null, "e": 1640, "s": 1633, "text": "Picked" }, { "code": null, "e": 1651, "s": 1640, "text": "SQL-Server" }, { "code": null, "e": 1655, "s": 1651, "text": "SQL" }, { "code": null, "e": 1659, "s": 1655, "text": "SQL" } ]
How to delete an Element From an Array in PHP ?
29 Jul, 2021 There are multiple ways to delete an element from an array in PHP. This article discusses some of the most common methods used in PHP to delete an element from an array. Functions used: unset(): This function takes an element as a parameter and unset it. It wouldn’t change the keys of other elements. array_splice(): This function takes three parameters an array, offset (where to start), and length (number of elements to be removed). It will automatically re-index an indexed array but not an associated array after deleting the elements. array_diff(): This function takes an array and list of array values as input and deletes the giving values from an array. Like unset() method, it will not change the keys of other elements. Steps used: Declare an associated array. Delete element from array. Print the result. Declare an indexed array. Delete an element from the indexed array. Print the result. Example 1: This example uses unset() function to delete the element. The unset() function takes the array as a reference and does not return anything. PHP <?php // Declaring associated array $ass_arr = ["a"=>"Geeks", "b"=>"For", "c"=>"Geeks"]; // Deleting element associated with key "b" unset($ass_arr["b"]); // Printing array after deleting the element print_r($ass_arr); // Declaring indexed array $ind_arr = ["Geeks","For","Geeks"]; // Deleting element and index 1 unset($ind_arr[1]); // Printing array after deleting the element print_r($ind_arr);?> Array ( [a] => Geeks => Geeks ) Array ( [0] => Geeks [2] => Geeks ) From the output we can see that unset() has not changed the index for other elements in indexed array. Example 2: This example uses array_splice() function to delete element from array. PHP <?php // Declaring associated array $ass_arr = ["a"=>"Geeks", "b"=>"For", "c"=>"Geeks"]; // Deleting element associated with key "b" array_splice($ass_arr,1,1); // Printing array after deleting the element print_r($ass_arr); // Declaring indexed array $ind_arr = ["Geeks","For","Geeks"]; // Deleting element and index 1 array_splice($ind_arr,1,1); // Printing array after deleting the element print_r($ind_arr);?> Array ( [a] => Geeks => Geeks ) Array ( [0] => Geeks [1] => Geeks ) Example 3: This example uses array_diff() function to delete the elements. Please note that the array values are passed as second parameter not the index. This function takes array parameter by value not reference and returns an array as output. PHP <?php // Declaring associated array $ass_arr = ["a"=>"Geeks", "b"=>"For", "c"=>"Geeks"]; // Deleting element associated with key "b" $ass_arr = array_diff($ass_arr,["For"]); // Printing array after deleting the element print_r($ass_arr); // Declaring indexed array $ind_arr = ["Geeks","For","Geeks"]; // Deleting element and index 1 $ind_arr = array_diff($ind_arr,["For"]); // Printing array after deleting the element print_r($ind_arr);?> Array ( [a] => Geeks => Geeks ) Array ( [0] => Geeks [2] => Geeks ) kapoorsagar226 singghakshay PHP-array PHP-function PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2021" }, { "code": null, "e": 198, "s": 28, "text": "There are multiple ways to delete an element from an array in PHP. This article discusses some of the most common methods used in PHP to delete an element from an array." }, { "code": null, "e": 214, "s": 198, "text": "Functions used:" }, { "code": null, "e": 330, "s": 214, "text": "unset(): This function takes an element as a parameter and unset it. It wouldn’t change the keys of other elements." }, { "code": null, "e": 570, "s": 330, "text": "array_splice(): This function takes three parameters an array, offset (where to start), and length (number of elements to be removed). It will automatically re-index an indexed array but not an associated array after deleting the elements." }, { "code": null, "e": 760, "s": 570, "text": "array_diff(): This function takes an array and list of array values as input and deletes the giving values from an array. Like unset() method, it will not change the keys of other elements." }, { "code": null, "e": 772, "s": 760, "text": "Steps used:" }, { "code": null, "e": 801, "s": 772, "text": "Declare an associated array." }, { "code": null, "e": 828, "s": 801, "text": "Delete element from array." }, { "code": null, "e": 846, "s": 828, "text": "Print the result." }, { "code": null, "e": 872, "s": 846, "text": "Declare an indexed array." }, { "code": null, "e": 914, "s": 872, "text": "Delete an element from the indexed array." }, { "code": null, "e": 932, "s": 914, "text": "Print the result." }, { "code": null, "e": 1083, "s": 932, "text": "Example 1: This example uses unset() function to delete the element. The unset() function takes the array as a reference and does not return anything." }, { "code": null, "e": 1087, "s": 1083, "text": "PHP" }, { "code": "<?php // Declaring associated array $ass_arr = [\"a\"=>\"Geeks\", \"b\"=>\"For\", \"c\"=>\"Geeks\"]; // Deleting element associated with key \"b\" unset($ass_arr[\"b\"]); // Printing array after deleting the element print_r($ass_arr); // Declaring indexed array $ind_arr = [\"Geeks\",\"For\",\"Geeks\"]; // Deleting element and index 1 unset($ind_arr[1]); // Printing array after deleting the element print_r($ind_arr);?>", "e": 1505, "s": 1087, "text": null }, { "code": null, "e": 1590, "s": 1505, "text": "Array\n(\n [a] => Geeks\n => Geeks\n)\nArray\n(\n [0] => Geeks\n [2] => Geeks\n)" }, { "code": null, "e": 1693, "s": 1590, "text": "From the output we can see that unset() has not changed the index for other elements in indexed array." }, { "code": null, "e": 1776, "s": 1693, "text": "Example 2: This example uses array_splice() function to delete element from array." }, { "code": null, "e": 1780, "s": 1776, "text": "PHP" }, { "code": "<?php // Declaring associated array $ass_arr = [\"a\"=>\"Geeks\", \"b\"=>\"For\", \"c\"=>\"Geeks\"]; // Deleting element associated with key \"b\" array_splice($ass_arr,1,1); // Printing array after deleting the element print_r($ass_arr); // Declaring indexed array $ind_arr = [\"Geeks\",\"For\",\"Geeks\"]; // Deleting element and index 1 array_splice($ind_arr,1,1); // Printing array after deleting the element print_r($ind_arr);?>", "e": 2212, "s": 1780, "text": null }, { "code": null, "e": 2297, "s": 2212, "text": "Array\n(\n [a] => Geeks\n => Geeks\n)\nArray\n(\n [0] => Geeks\n [1] => Geeks\n)" }, { "code": null, "e": 2543, "s": 2297, "text": "Example 3: This example uses array_diff() function to delete the elements. Please note that the array values are passed as second parameter not the index. This function takes array parameter by value not reference and returns an array as output." }, { "code": null, "e": 2547, "s": 2543, "text": "PHP" }, { "code": "<?php // Declaring associated array $ass_arr = [\"a\"=>\"Geeks\", \"b\"=>\"For\", \"c\"=>\"Geeks\"]; // Deleting element associated with key \"b\" $ass_arr = array_diff($ass_arr,[\"For\"]); // Printing array after deleting the element print_r($ass_arr); // Declaring indexed array $ind_arr = [\"Geeks\",\"For\",\"Geeks\"]; // Deleting element and index 1 $ind_arr = array_diff($ind_arr,[\"For\"]); // Printing array after deleting the element print_r($ind_arr);?>", "e": 3005, "s": 2547, "text": null }, { "code": null, "e": 3093, "s": 3008, "text": "Array\n(\n [a] => Geeks\n => Geeks\n)\nArray\n(\n [0] => Geeks\n [2] => Geeks\n)" }, { "code": null, "e": 3110, "s": 3095, "text": "kapoorsagar226" }, { "code": null, "e": 3123, "s": 3110, "text": "singghakshay" }, { "code": null, "e": 3133, "s": 3123, "text": "PHP-array" }, { "code": null, "e": 3146, "s": 3133, "text": "PHP-function" }, { "code": null, "e": 3160, "s": 3146, "text": "PHP-Questions" }, { "code": null, "e": 3167, "s": 3160, "text": "Picked" }, { "code": null, "e": 3171, "s": 3167, "text": "PHP" }, { "code": null, "e": 3188, "s": 3171, "text": "Web Technologies" }, { "code": null, "e": 3192, "s": 3188, "text": "PHP" } ]
Remove BST Keys in a given Range
18 Jun, 2021 Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are inside the given range. The modified tree should also be BST. For example, consider the following BST and range [50, 70]. 50 / \ 30 70 / \ / \ 20 40 60 80 The given BST should be transformed to this: 80 / 30 / \ 20 40 There are two possible cases for every node. 1) Node’s key is inside the given range. 2) Node’s key is out of range. We don’t need to do anything for case 2. In case 1, we need to remove the node and change the root of sub-tree rooted with this node. The idea is to fix the tree in Postorder fashion. When we visit a node, we make sure that its left and right sub-trees are already fixed. When we find a node inside the range we call normal BST delete function to delete that node. Following is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h> using namespace std; class BSTnode {public: int data; BSTnode *left, *right; BSTnode(int data) { this->data = data; this->left = this->right = NULL; }}; // A Utility function to find leftMost nodeBSTnode* leftMost(BSTnode* root){ if (!root) return NULL; while (root->left) root = root->left; return root;} // A Utility function to delete the give nodeBSTnode* deleteNode(BSTnode* root){ // node with only one chile or no child if (!root->left) { BSTnode* child = root->right; root = NULL; return child; } else if (!root->right) { BSTnode* child = root->left; root = NULL; return child; } // node with two children: get inorder successor // in the right subtree BSTnode* next = leftMost(root->right); // copy the inorder successor's content to this node root->data = next->data; // delete the inorder successor root->right = deleteNode(root->right); return root;} // function to find node in given range and delete// it in preorder mannerBSTnode* removeRange(BSTnode* node, int low, int high){ // Base case if (!node) return NULL; // First fix the left and right subtrees of node node->left = removeRange(node->left, low, high); node->right = removeRange(node->right, low, high); // Now fix the node. // if given node is in Range then delete it if (node->data >= low && node->data <= high) return deleteNode(node); // Root is out of range return node;} // Utility function to traverse the binary tree// after conversionvoid inorder(BSTnode* root){ if (root) { inorder(root->left); cout << root->data << ' '; inorder(root->right); }} // Driver Program to test above functionsint main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ BSTnode* root = new BSTnode(50); root->left = new BSTnode(30); root->right = new BSTnode(70); root->left->right = new BSTnode(40); root->right->right = new BSTnode(80); root->right->left = new BSTnode(60); root->left->left = new BSTnode(20); cout << "Inorder Before deletion: "; inorder(root); root = removeRange(root, 50, 70); cout << "\nInorder After deletion: "; inorder(root); cout << endl; return 0;} // Java implementation of the above approachimport java.util.*;class Solution { static class BSTnode { int data; BSTnode left, right; BSTnode(int data) { this.data = data; this.left = this.right = null; } } // A Utility function to find leftMost node static BSTnode leftMost(BSTnode root) { if (root == null) return null; while (root.left != null) root = root.left; return root; } // A Utility function to delete the give node static BSTnode deleteNode(BSTnode root) { // node with only one chile or no child if (root.left == null) { BSTnode child = root.right; root = null; return child; } else if (root.right == null) { BSTnode child = root.left; root = null; return child; } // node with two children: get inorder successor // in the right subtree BSTnode next = leftMost(root.right); // copy the inorder successor's content to this node root.data = next.data; // delete the inorder successor root.right = deleteNode(root.right); return root; } // function to find node in given range and delete // it in preorder manner static BSTnode removeRange(BSTnode node, int low, int high) { // Base case if (node == null) return null; // First fix the left and right subtrees of node node.left = removeRange(node.left, low, high); node.right = removeRange(node.right, low, high); // Now fix the node. // if given node is in Range then delete it if (node.data >= low && node.data <= high) return deleteNode(node); // Root is out of range return node; } // Utility function to traverse the binary tree // after conversion static void inorder(BSTnode root) { if (root != null) { inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } } // Driver Program to test above functions public static void main(String args[]) { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ BSTnode root = new BSTnode(50); root.left = new BSTnode(30); root.right = new BSTnode(70); root.left.right = new BSTnode(40); root.right.right = new BSTnode(80); root.right.left = new BSTnode(60); root.left.left = new BSTnode(20); System.out.print("Inorder Before deletion: "); inorder(root); root = removeRange(root, 50, 70); System.out.print("\nInorder After deletion: "); inorder(root); }}// This code is contributed by Arnab Kundu # Python3 implementation of the above approachclass BSTnode: def __init__(self, data): self.data = data self.left = None self.right = None # A Utility function to find leftMost nodedef leftMost(root): if (root == None): return None while (root.left): root = root.left return root # A Utility function to delete the give nodedef deleteNode(root): # Node with only one chile or no child if (root.left == None): child = root.right root = None return child elif (root.right == None): child = root.left root = None return child # Node with two children: get # inorder successor in the # right subtree next = leftMost(root.right) # Copy the inorder successor's # content to this node root.data = next.data # Delete the inorder successor root.right = deleteNode(root.right) return root # Function to find node in given range# and delete it in preorder mannerdef removeRange(node, low, high): # Base case if (node == None): return None # First fix the left and right subtrees of node node.left = removeRange(node.left, low, high) node.right = removeRange(node.right, low, high) # Now fix the node. If given node # is in Range then delete it if (node.data >= low and node.data <= high): return deleteNode(node) # Root is out of range return node # Utility function to traverse the# binary tree after conversiondef inorder(root): if (root): inorder(root.left) print(root.data, end = " ") inorder(root.right) # Driver codeif __name__ == '__main__': ''' Let us create following BST 50 / \ 30 70 / / / \ 20 40 60 80 ''' root = BSTnode(50) root.left = BSTnode(30) root.right = BSTnode(70) root.left.right = BSTnode(40) root.right.right = BSTnode(80) root.right.left = BSTnode(60) root.left.left = BSTnode(20) print("Inorder Before deletion:", end = "") inorder(root) root = removeRange(root, 50, 70) print("\nInorder After deletion:", end = "") inorder(root) # This code is contributed by bgangwar59 // C# implementation of the above approachusing System; class GFG { public class BSTnode { public int data; public BSTnode left, right; public BSTnode(int data) { this.data = data; this.left = this.right = null; } } // A Utility function to find leftMost node static BSTnode leftMost(BSTnode root) { if (root == null) return null; while (root.left != null) root = root.left; return root; } // A Utility function to delete the give node static BSTnode deleteNode(BSTnode root) { // node with only one chile or no child if (root.left == null) { BSTnode child = root.right; root = null; return child; } else if (root.right == null) { BSTnode child = root.left; root = null; return child; } // node with two children: get inorder successor // in the right subtree BSTnode next = leftMost(root.right); // copy the inorder successor's content to this node root.data = next.data; // delete the inorder successor root.right = deleteNode(root.right); return root; } // function to find node in given range and delete // it in preorder manner static BSTnode removeRange(BSTnode node, int low, int high) { // Base case if (node == null) return null; // First fix the left and right subtrees of node node.left = removeRange(node.left, low, high); node.right = removeRange(node.right, low, high); // Now fix the node. // if given node is in Range then delete it if (node.data >= low && node.data <= high) return deleteNode(node); // Root is out of range return node; } // Utility function to traverse the binary tree // after conversion static void inorder(BSTnode root) { if (root != null) { inorder(root.left); Console.Write(root.data + " "); inorder(root.right); } } // Driver code public static void Main(String[] args) { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ BSTnode root = new BSTnode(50); root.left = new BSTnode(30); root.right = new BSTnode(70); root.left.right = new BSTnode(40); root.right.right = new BSTnode(80); root.right.left = new BSTnode(60); root.left.left = new BSTnode(20); Console.Write("Inorder Before deletion: "); inorder(root); root = removeRange(root, 50, 70); Console.Write("\nInorder After deletion: "); inorder(root); }} // This code contributed by Rajput-Ji <script> // Javascript implementation of the// above approachclass BSTnode{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // A Utility function to find leftMost nodefunction leftMost(root){ if (root == null) return null; while (root.left != null) root = root.left; return root;} // A Utility function to delete the give nodefunction deleteNode(root){ // Node with only one chile or no child if (root.left == null) { let child = root.right; root = null; return child; } else if (root.right == null) { let child = root.left; root = null; return child; } // Node with two children: get inorder // successor in the right subtree let next = leftMost(root.right); // Copy the inorder successor's // content to this node root.data = next.data; // Delete the inorder successor root.right = deleteNode(root.right); return root;} // Function to find node in given range// and delete it in preorder mannerfunction removeRange(node, low, high){ // Base case if (node == null) return null; // First fix the left and right subtrees of node node.left = removeRange(node.left, low, high); node.right = removeRange(node.right, low, high); // Now fix the node. // if given node is in Range then delete it if (node.data >= low && node.data <= high) return deleteNode(node); // Root is out of range return node;} // Utility function to traverse the binary// tree after conversionfunction inorder(root){ if (root != null) { inorder(root.left); document.write(root.data + " "); inorder(root.right); }} // Driver code /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */let root = new BSTnode(50);root.left = new BSTnode(30);root.right = new BSTnode(70);root.left.right = new BSTnode(40);root.right.right = new BSTnode(80);root.right.left = new BSTnode(60);root.left.left = new BSTnode(20); document.write("Inorder Before deletion: ");inorder(root); root = removeRange(root, 50, 70); document.write("</br>" + "Inorder After deletion: ");inorder(root); // This code is contributed by divyeshrabadiya07 </script> Inorder Before deletion: 20 30 40 50 60 70 80 Inorder After deletion: 20 30 40 80 andrew1234 Rajput-Ji bgangwar59 divyeshrabadiya07 Technical Scripter 2018 tree-traversal Binary Search Tree Technical Scripter Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jun, 2021" }, { "code": null, "e": 261, "s": 54, "text": "Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are inside the given range. The modified tree should also be BST. For example, consider the following BST and range [50, 70]. " }, { "code": null, "e": 472, "s": 261, "text": " 50\n / \\\n 30 70\n / \\ / \\\n 20 40 60 80 \n\nThe given BST should be transformed to this:\n 80\n /\n 30\n / \\\n 20 40" }, { "code": null, "e": 589, "s": 472, "text": "There are two possible cases for every node. 1) Node’s key is inside the given range. 2) Node’s key is out of range." }, { "code": null, "e": 954, "s": 589, "text": "We don’t need to do anything for case 2. In case 1, we need to remove the node and change the root of sub-tree rooted with this node. The idea is to fix the tree in Postorder fashion. When we visit a node, we make sure that its left and right sub-trees are already fixed. When we find a node inside the range we call normal BST delete function to delete that node." }, { "code": null, "e": 1010, "s": 954, "text": "Following is the implementation of the above approach. " }, { "code": null, "e": 1014, "s": 1010, "text": "C++" }, { "code": null, "e": 1019, "s": 1014, "text": "Java" }, { "code": null, "e": 1027, "s": 1019, "text": "Python3" }, { "code": null, "e": 1030, "s": 1027, "text": "C#" }, { "code": null, "e": 1041, "s": 1030, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h> using namespace std; class BSTnode {public: int data; BSTnode *left, *right; BSTnode(int data) { this->data = data; this->left = this->right = NULL; }}; // A Utility function to find leftMost nodeBSTnode* leftMost(BSTnode* root){ if (!root) return NULL; while (root->left) root = root->left; return root;} // A Utility function to delete the give nodeBSTnode* deleteNode(BSTnode* root){ // node with only one chile or no child if (!root->left) { BSTnode* child = root->right; root = NULL; return child; } else if (!root->right) { BSTnode* child = root->left; root = NULL; return child; } // node with two children: get inorder successor // in the right subtree BSTnode* next = leftMost(root->right); // copy the inorder successor's content to this node root->data = next->data; // delete the inorder successor root->right = deleteNode(root->right); return root;} // function to find node in given range and delete// it in preorder mannerBSTnode* removeRange(BSTnode* node, int low, int high){ // Base case if (!node) return NULL; // First fix the left and right subtrees of node node->left = removeRange(node->left, low, high); node->right = removeRange(node->right, low, high); // Now fix the node. // if given node is in Range then delete it if (node->data >= low && node->data <= high) return deleteNode(node); // Root is out of range return node;} // Utility function to traverse the binary tree// after conversionvoid inorder(BSTnode* root){ if (root) { inorder(root->left); cout << root->data << ' '; inorder(root->right); }} // Driver Program to test above functionsint main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ BSTnode* root = new BSTnode(50); root->left = new BSTnode(30); root->right = new BSTnode(70); root->left->right = new BSTnode(40); root->right->right = new BSTnode(80); root->right->left = new BSTnode(60); root->left->left = new BSTnode(20); cout << \"Inorder Before deletion: \"; inorder(root); root = removeRange(root, 50, 70); cout << \"\\nInorder After deletion: \"; inorder(root); cout << endl; return 0;}", "e": 3488, "s": 1041, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*;class Solution { static class BSTnode { int data; BSTnode left, right; BSTnode(int data) { this.data = data; this.left = this.right = null; } } // A Utility function to find leftMost node static BSTnode leftMost(BSTnode root) { if (root == null) return null; while (root.left != null) root = root.left; return root; } // A Utility function to delete the give node static BSTnode deleteNode(BSTnode root) { // node with only one chile or no child if (root.left == null) { BSTnode child = root.right; root = null; return child; } else if (root.right == null) { BSTnode child = root.left; root = null; return child; } // node with two children: get inorder successor // in the right subtree BSTnode next = leftMost(root.right); // copy the inorder successor's content to this node root.data = next.data; // delete the inorder successor root.right = deleteNode(root.right); return root; } // function to find node in given range and delete // it in preorder manner static BSTnode removeRange(BSTnode node, int low, int high) { // Base case if (node == null) return null; // First fix the left and right subtrees of node node.left = removeRange(node.left, low, high); node.right = removeRange(node.right, low, high); // Now fix the node. // if given node is in Range then delete it if (node.data >= low && node.data <= high) return deleteNode(node); // Root is out of range return node; } // Utility function to traverse the binary tree // after conversion static void inorder(BSTnode root) { if (root != null) { inorder(root.left); System.out.print(root.data + \" \"); inorder(root.right); } } // Driver Program to test above functions public static void main(String args[]) { /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ BSTnode root = new BSTnode(50); root.left = new BSTnode(30); root.right = new BSTnode(70); root.left.right = new BSTnode(40); root.right.right = new BSTnode(80); root.right.left = new BSTnode(60); root.left.left = new BSTnode(20); System.out.print(\"Inorder Before deletion: \"); inorder(root); root = removeRange(root, 50, 70); System.out.print(\"\\nInorder After deletion: \"); inorder(root); }}// This code is contributed by Arnab Kundu", "e": 6361, "s": 3488, "text": null }, { "code": "# Python3 implementation of the above approachclass BSTnode: def __init__(self, data): self.data = data self.left = None self.right = None # A Utility function to find leftMost nodedef leftMost(root): if (root == None): return None while (root.left): root = root.left return root # A Utility function to delete the give nodedef deleteNode(root): # Node with only one chile or no child if (root.left == None): child = root.right root = None return child elif (root.right == None): child = root.left root = None return child # Node with two children: get # inorder successor in the # right subtree next = leftMost(root.right) # Copy the inorder successor's # content to this node root.data = next.data # Delete the inorder successor root.right = deleteNode(root.right) return root # Function to find node in given range# and delete it in preorder mannerdef removeRange(node, low, high): # Base case if (node == None): return None # First fix the left and right subtrees of node node.left = removeRange(node.left, low, high) node.right = removeRange(node.right, low, high) # Now fix the node. If given node # is in Range then delete it if (node.data >= low and node.data <= high): return deleteNode(node) # Root is out of range return node # Utility function to traverse the# binary tree after conversiondef inorder(root): if (root): inorder(root.left) print(root.data, end = \" \") inorder(root.right) # Driver codeif __name__ == '__main__': ''' Let us create following BST 50 / \\ 30 70 / / / \\ 20 40 60 80 ''' root = BSTnode(50) root.left = BSTnode(30) root.right = BSTnode(70) root.left.right = BSTnode(40) root.right.right = BSTnode(80) root.right.left = BSTnode(60) root.left.left = BSTnode(20) print(\"Inorder Before deletion:\", end = \"\") inorder(root) root = removeRange(root, 50, 70) print(\"\\nInorder After deletion:\", end = \"\") inorder(root) # This code is contributed by bgangwar59", "e": 8628, "s": 6361, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG { public class BSTnode { public int data; public BSTnode left, right; public BSTnode(int data) { this.data = data; this.left = this.right = null; } } // A Utility function to find leftMost node static BSTnode leftMost(BSTnode root) { if (root == null) return null; while (root.left != null) root = root.left; return root; } // A Utility function to delete the give node static BSTnode deleteNode(BSTnode root) { // node with only one chile or no child if (root.left == null) { BSTnode child = root.right; root = null; return child; } else if (root.right == null) { BSTnode child = root.left; root = null; return child; } // node with two children: get inorder successor // in the right subtree BSTnode next = leftMost(root.right); // copy the inorder successor's content to this node root.data = next.data; // delete the inorder successor root.right = deleteNode(root.right); return root; } // function to find node in given range and delete // it in preorder manner static BSTnode removeRange(BSTnode node, int low, int high) { // Base case if (node == null) return null; // First fix the left and right subtrees of node node.left = removeRange(node.left, low, high); node.right = removeRange(node.right, low, high); // Now fix the node. // if given node is in Range then delete it if (node.data >= low && node.data <= high) return deleteNode(node); // Root is out of range return node; } // Utility function to traverse the binary tree // after conversion static void inorder(BSTnode root) { if (root != null) { inorder(root.left); Console.Write(root.data + \" \"); inorder(root.right); } } // Driver code public static void Main(String[] args) { /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ BSTnode root = new BSTnode(50); root.left = new BSTnode(30); root.right = new BSTnode(70); root.left.right = new BSTnode(40); root.right.right = new BSTnode(80); root.right.left = new BSTnode(60); root.left.left = new BSTnode(20); Console.Write(\"Inorder Before deletion: \"); inorder(root); root = removeRange(root, 50, 70); Console.Write(\"\\nInorder After deletion: \"); inorder(root); }} // This code contributed by Rajput-Ji", "e": 11453, "s": 8628, "text": null }, { "code": "<script> // Javascript implementation of the// above approachclass BSTnode{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // A Utility function to find leftMost nodefunction leftMost(root){ if (root == null) return null; while (root.left != null) root = root.left; return root;} // A Utility function to delete the give nodefunction deleteNode(root){ // Node with only one chile or no child if (root.left == null) { let child = root.right; root = null; return child; } else if (root.right == null) { let child = root.left; root = null; return child; } // Node with two children: get inorder // successor in the right subtree let next = leftMost(root.right); // Copy the inorder successor's // content to this node root.data = next.data; // Delete the inorder successor root.right = deleteNode(root.right); return root;} // Function to find node in given range// and delete it in preorder mannerfunction removeRange(node, low, high){ // Base case if (node == null) return null; // First fix the left and right subtrees of node node.left = removeRange(node.left, low, high); node.right = removeRange(node.right, low, high); // Now fix the node. // if given node is in Range then delete it if (node.data >= low && node.data <= high) return deleteNode(node); // Root is out of range return node;} // Utility function to traverse the binary// tree after conversionfunction inorder(root){ if (root != null) { inorder(root.left); document.write(root.data + \" \"); inorder(root.right); }} // Driver code /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */let root = new BSTnode(50);root.left = new BSTnode(30);root.right = new BSTnode(70);root.left.right = new BSTnode(40);root.right.right = new BSTnode(80);root.right.left = new BSTnode(60);root.left.left = new BSTnode(20); document.write(\"Inorder Before deletion: \");inorder(root); root = removeRange(root, 50, 70); document.write(\"</br>\" + \"Inorder After deletion: \");inorder(root); // This code is contributed by divyeshrabadiya07 </script>", "e": 13770, "s": 11453, "text": null }, { "code": null, "e": 13853, "s": 13770, "text": "Inorder Before deletion: 20 30 40 50 60 70 80 \nInorder After deletion: 20 30 40 80" }, { "code": null, "e": 13866, "s": 13855, "text": "andrew1234" }, { "code": null, "e": 13876, "s": 13866, "text": "Rajput-Ji" }, { "code": null, "e": 13887, "s": 13876, "text": "bgangwar59" }, { "code": null, "e": 13905, "s": 13887, "text": "divyeshrabadiya07" }, { "code": null, "e": 13929, "s": 13905, "text": "Technical Scripter 2018" }, { "code": null, "e": 13944, "s": 13929, "text": "tree-traversal" }, { "code": null, "e": 13963, "s": 13944, "text": "Binary Search Tree" }, { "code": null, "e": 13982, "s": 13963, "text": "Technical Scripter" }, { "code": null, "e": 14001, "s": 13982, "text": "Binary Search Tree" } ]
C++ Program to Implement Max Heap
A Binary Heap is a complete binary tree which is either Min Heap or Max Heap. In a Max Binary Heap, the key at root must be maximum among all keys present in Binary Heap. This property must be recursively true for all nodes in Binary Tree. Min Binary Heap is similar to MinHeap. For max_heap: Begin Declare function max_heap () Declare j, t of the integer datatype. Initialize t = a[m]. j = 2 * m; while (j <= n) do if (j < n && a[j+1] > a[j]) then j = j + 1 if (t > a[j]) then break else if (t <= a[j]) then a[j / 2] = a[j] j = 2 * j a[j/2] = t return End. For build_maxheap: Begin Declare function build_maxheap(int *a,int n). Declare k of the integer datatype. for(k = n/2; k >= 1; k--) Call function max_heap(a,k,n) End. #include <iostream> using namespace std; void max_heap(int *a, int m, int n) { int j, t; t = a[m]; j = 2 * m; while (j <= n) { if (j < n && a[j+1] > a[j]) j = j + 1; if (t > a[j]) break; else if (t <= a[j]) { a[j / 2] = a[j]; j = 2 * j; } } a[j/2] = t; return; } void build_maxheap(int *a,int n) { int k; for(k = n/2; k >= 1; k--) { max_heap(a,k,n); } } int main() { int n, i; cout<<"enter no of elements of array\n"; cin>>n; int a[30]; for (i = 1; i <= n; i++) { cout<<"enter elements"<<" "<<(i)<<endl; cin>>a[i]; } build_maxheap(a,n); cout<<"Max Heap\n"; for (i = 1; i <= n; i++) { cout<<a[i]<<endl; } } enter no of elements of array 5 enter elements 1 7 enter elements 2 6 enter elements 3 2 enter elements 4 1 enter elements 5 4 Max Heap 7 6 2 1 4
[ { "code": null, "e": 1341, "s": 1062, "text": "A Binary Heap is a complete binary tree which is either Min Heap or Max Heap. In a Max Binary Heap, the key at root must be maximum among all keys present in Binary Heap. This property must be recursively true for all nodes in Binary Tree. Min Binary Heap is similar to MinHeap." }, { "code": null, "e": 1355, "s": 1341, "text": "For max_heap:" }, { "code": null, "e": 1734, "s": 1355, "text": "Begin\n Declare function max_heap ()\n Declare j, t of the integer datatype.\n Initialize t = a[m].\n j = 2 * m;\n while (j <= n) do\n if (j < n && a[j+1] > a[j]) then\n j = j + 1\n if (t > a[j]) then\n break\n else if (t <= a[j]) then\n a[j / 2] = a[j]\n j = 2 * j\n a[j/2] = t\n return\nEnd." }, { "code": null, "e": 1753, "s": 1734, "text": "For build_maxheap:" }, { "code": null, "e": 1925, "s": 1753, "text": "Begin\n Declare function build_maxheap(int *a,int n).\n Declare k of the integer datatype.\n for(k = n/2; k >= 1; k--)\n Call function max_heap(a,k,n)\nEnd." }, { "code": null, "e": 2675, "s": 1925, "text": "#include <iostream>\nusing namespace std;\nvoid max_heap(int *a, int m, int n) {\n int j, t;\n t = a[m];\n j = 2 * m;\n while (j <= n) {\n if (j < n && a[j+1] > a[j])\n j = j + 1;\n if (t > a[j])\n break;\n else if (t <= a[j]) {\n a[j / 2] = a[j];\n j = 2 * j;\n }\n }\n a[j/2] = t;\n return;\n}\nvoid build_maxheap(int *a,int n) {\n int k;\n for(k = n/2; k >= 1; k--) {\n max_heap(a,k,n);\n }\n}\nint main() {\n int n, i;\n cout<<\"enter no of elements of array\\n\";\n cin>>n;\n int a[30];\n for (i = 1; i <= n; i++) {\n cout<<\"enter elements\"<<\" \"<<(i)<<endl;\n cin>>a[i];\n }\n build_maxheap(a,n);\n cout<<\"Max Heap\\n\";\n for (i = 1; i <= n; i++) {\n cout<<a[i]<<endl;\n }\n}" }, { "code": null, "e": 2821, "s": 2675, "text": "enter no of elements of array\n5\nenter elements 1\n7\nenter elements 2\n6\nenter elements 3\n2\nenter elements 4\n1\nenter elements 5\n4\nMax Heap\n7\n6\n2\n1\n4" } ]
GATE | GATE-CS-2014-(Set-2) | Question 20 - GeeksforGeeks
28 Jun, 2021 Consider the function func shown below: int func(int num){ int count = 0; while (num) { count++; num >>= 1; } return (count);} The value returned by func(435)is __________. (A) 8(B) 9(C) 10(D) 11Answer: (B)Explanation: The function mainly returns position of Most significant bit in binary representation of n. The MSD in binary representation of 435 is 9th bit. Another explanation:>> in right shift. In other words, it means divide by 2.If keep on dividing by 2, we get: 435, 217, 108, 54, 27, 13, 6, 3, 1.Therefore, the count is 9.Quiz of this Question GATE-CS-2014-(Set-2) GATE-GATE-CS-2014-(Set-2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25805, "s": 25777, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25845, "s": 25805, "text": "Consider the function func shown below:" }, { "code": "int func(int num){ int count = 0; while (num) { count++; num >>= 1; } return (count);}", "e": 25961, "s": 25845, "text": null }, { "code": null, "e": 26007, "s": 25961, "text": "The value returned by func(435)is __________." }, { "code": null, "e": 26197, "s": 26007, "text": "(A) 8(B) 9(C) 10(D) 11Answer: (B)Explanation: The function mainly returns position of Most significant bit in binary representation of n. The MSD in binary representation of 435 is 9th bit." }, { "code": null, "e": 26390, "s": 26197, "text": "Another explanation:>> in right shift. In other words, it means divide by 2.If keep on dividing by 2, we get: 435, 217, 108, 54, 27, 13, 6, 3, 1.Therefore, the count is 9.Quiz of this Question" }, { "code": null, "e": 26411, "s": 26390, "text": "GATE-CS-2014-(Set-2)" }, { "code": null, "e": 26437, "s": 26411, "text": "GATE-GATE-CS-2014-(Set-2)" }, { "code": null, "e": 26442, "s": 26437, "text": "GATE" }, { "code": null, "e": 26540, "s": 26442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26574, "s": 26540, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26608, "s": 26574, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26642, "s": 26608, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26675, "s": 26642, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26711, "s": 26675, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26745, "s": 26711, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26781, "s": 26745, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26815, "s": 26781, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26849, "s": 26815, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Sum of all prime numbers in an Array - GeeksforGeeks
21 May, 2021 Given an array arr[] of N positive integers. The task is to write a program to find the sum of all prime elements in the given array.Examples: Input: arr[] = {1, 3, 4, 5, 7} Output: 15 There are three primes, 3, 5 and 7 whose sum =15.Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 17 Naive Approach: A simple solution is to traverse the array and keep checking for every element if it is prime or not and add the prime element at the same time.Efficient Approach: Generate all primes up to the maximum element of the array using the sieve of Eratosthenes and store them in a hash. Now traverse the array and find the sum of those elements which are prime using the sieve.Below is the implementation of the efficient approach: C++ Java Python C# Javascript // CPP program to find sum of// primes in given array.#include <bits/stdc++.h>using namespace std; // Function to find count of primeint primeSum(int arr[], int n){ // Find maximum value in the array int max_val = *max_element(arr, arr + n); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all primes in arr[] int sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; return sum;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << primeSum(arr, n); return 0;} // Java program to find sum of// primes in given array.import java.util.*; class GFG{ // Function to find count of primestatic int primeSum(int arr[], int n){ // Find maximum value in the array int max_val = Arrays.stream(arr).max().getAsInt(); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. Vector<Boolean> prime = new Vector<>(max_val + 1); for(int i = 0; i < max_val + 1; i++) prime.add(i,Boolean.TRUE); // Remaining part of SIEVE prime.add(0,Boolean.FALSE); prime.add(1,Boolean.FALSE); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime.get(p) == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.add(i,Boolean.FALSE); } } // Sum all primes in arr[] int sum = 0; for (int i = 0; i < n; i++) if (prime.get(arr[i])) sum += arr[i]; return sum;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.length; System.out.print(primeSum(arr, n));}} /* This code contributed by PrinciRaj1992 */ # Python3 program to find sum of# primes in given array. # Function to find count of primedef primeSum( arr, n): # Find maximum value in the array max_val = max(arr) # USE SIEVE TO FIND ALL PRIME NUMBERS LESS # THAN OR EQUAL TO max_val # Create a boolean array "prime[0..n]". A # value in prime[i] will finally be False # if i is Not a prime, else true. prime=[True for i in range(max_val + 1)] # Remaining part of SIEVE prime[0] = False prime[1] = False for p in range(2, max_val + 1): if(p * p > max_val): break # If prime[p] is not changed, then # it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, max_val+1, p): prime[i] = False # Sum all primes in arr[] sum = 0 for i in range(n): if (prime[arr[i]]): sum += arr[i] return sum # Driver codearr =[1, 2, 3, 4, 5, 6, 7] n = len(arr) print(primeSum(arr, n)) # This code is contributed by mohit kumar 29 // C# program to find sum of// primes in given array.using System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to find count of primestatic int primeSum(int []arr, int n){ // Find maximum value in the array int max_val = arr.Max(); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. List<bool> prime = new List<bool>(max_val + 1); for(int i = 0; i < max_val + 1; i++) prime.Insert(i,true); // Remaining part of SIEVE prime.Insert(0, false); prime.Insert(1, false); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.Insert(i,false); } } // Sum all primes in arr[] int sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; return sum;} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.Length; Console.WriteLine(primeSum(arr, n));}} // This code contributed by Rajput-Ji <script>// Javascript program to find sum of// primes in given array. // Function to find count of primefunction primeSum(arr, n) { // Find maximum value in the array let max_val = arr.sort((a, b) => b - a)[0]; // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = new Array(max_val + 1).fill(true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (let p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all primes in arr[] let sum = 0; for (let i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; return sum;} // Driver code let arr = [1, 2, 3, 4, 5, 6, 7];let n = arr.length; document.write(primeSum(arr, n)); // This code is contributed by _saurabh_jaiswal.</script> 17 Time complexity : O(n*loglogn) VishalBachchas princiraj1992 Rajput-Ji mohit kumar 29 nidhi_biet _saurabh_jaiswal Prime Number sieve Technical Scripter 2018 Arrays Technical Scripter Arrays Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Array of Strings in C++ (5 Different Ways to Create)
[ { "code": null, "e": 26174, "s": 26146, "text": "\n21 May, 2021" }, { "code": null, "e": 26319, "s": 26174, "text": "Given an array arr[] of N positive integers. The task is to write a program to find the sum of all prime elements in the given array.Examples: " }, { "code": null, "e": 26460, "s": 26319, "text": "Input: arr[] = {1, 3, 4, 5, 7} Output: 15 There are three primes, 3, 5 and 7 whose sum =15.Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 17 " }, { "code": null, "e": 26906, "s": 26462, "text": "Naive Approach: A simple solution is to traverse the array and keep checking for every element if it is prime or not and add the prime element at the same time.Efficient Approach: Generate all primes up to the maximum element of the array using the sieve of Eratosthenes and store them in a hash. Now traverse the array and find the sum of those elements which are prime using the sieve.Below is the implementation of the efficient approach: " }, { "code": null, "e": 26910, "s": 26906, "text": "C++" }, { "code": null, "e": 26915, "s": 26910, "text": "Java" }, { "code": null, "e": 26922, "s": 26915, "text": "Python" }, { "code": null, "e": 26925, "s": 26922, "text": "C#" }, { "code": null, "e": 26936, "s": 26925, "text": "Javascript" }, { "code": "// CPP program to find sum of// primes in given array.#include <bits/stdc++.h>using namespace std; // Function to find count of primeint primeSum(int arr[], int n){ // Find maximum value in the array int max_val = *max_element(arr, arr + n); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all primes in arr[] int sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; return sum;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << primeSum(arr, n); return 0;}", "e": 28092, "s": 26936, "text": null }, { "code": "// Java program to find sum of// primes in given array.import java.util.*; class GFG{ // Function to find count of primestatic int primeSum(int arr[], int n){ // Find maximum value in the array int max_val = Arrays.stream(arr).max().getAsInt(); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. Vector<Boolean> prime = new Vector<>(max_val + 1); for(int i = 0; i < max_val + 1; i++) prime.add(i,Boolean.TRUE); // Remaining part of SIEVE prime.add(0,Boolean.FALSE); prime.add(1,Boolean.FALSE); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime.get(p) == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.add(i,Boolean.FALSE); } } // Sum all primes in arr[] int sum = 0; for (int i = 0; i < n; i++) if (prime.get(arr[i])) sum += arr[i]; return sum;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.length; System.out.print(primeSum(arr, n));}} /* This code contributed by PrinciRaj1992 */", "e": 29435, "s": 28092, "text": null }, { "code": "# Python3 program to find sum of# primes in given array. # Function to find count of primedef primeSum( arr, n): # Find maximum value in the array max_val = max(arr) # USE SIEVE TO FIND ALL PRIME NUMBERS LESS # THAN OR EQUAL TO max_val # Create a boolean array \"prime[0..n]\". A # value in prime[i] will finally be False # if i is Not a prime, else true. prime=[True for i in range(max_val + 1)] # Remaining part of SIEVE prime[0] = False prime[1] = False for p in range(2, max_val + 1): if(p * p > max_val): break # If prime[p] is not changed, then # it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, max_val+1, p): prime[i] = False # Sum all primes in arr[] sum = 0 for i in range(n): if (prime[arr[i]]): sum += arr[i] return sum # Driver codearr =[1, 2, 3, 4, 5, 6, 7] n = len(arr) print(primeSum(arr, n)) # This code is contributed by mohit kumar 29", "e": 30474, "s": 29435, "text": null }, { "code": "// C# program to find sum of// primes in given array.using System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to find count of primestatic int primeSum(int []arr, int n){ // Find maximum value in the array int max_val = arr.Max(); // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. List<bool> prime = new List<bool>(max_val + 1); for(int i = 0; i < max_val + 1; i++) prime.Insert(i,true); // Remaining part of SIEVE prime.Insert(0, false); prime.Insert(1, false); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime.Insert(i,false); } } // Sum all primes in arr[] int sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; return sum;} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.Length; Console.WriteLine(primeSum(arr, n));}} // This code contributed by Rajput-Ji", "e": 31799, "s": 30474, "text": null }, { "code": "<script>// Javascript program to find sum of// primes in given array. // Function to find count of primefunction primeSum(arr, n) { // Find maximum value in the array let max_val = arr.sort((a, b) => b - a)[0]; // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = new Array(max_val + 1).fill(true); // Remaining part of SIEVE prime[0] = false; prime[1] = false; for (let p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Sum all primes in arr[] let sum = 0; for (let i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; return sum;} // Driver code let arr = [1, 2, 3, 4, 5, 6, 7];let n = arr.length; document.write(primeSum(arr, n)); // This code is contributed by _saurabh_jaiswal.</script>", "e": 32938, "s": 31799, "text": null }, { "code": null, "e": 32941, "s": 32938, "text": "17" }, { "code": null, "e": 32975, "s": 32943, "text": "Time complexity : O(n*loglogn) " }, { "code": null, "e": 32990, "s": 32975, "text": "VishalBachchas" }, { "code": null, "e": 33004, "s": 32990, "text": "princiraj1992" }, { "code": null, "e": 33014, "s": 33004, "text": "Rajput-Ji" }, { "code": null, "e": 33029, "s": 33014, "text": "mohit kumar 29" }, { "code": null, "e": 33040, "s": 33029, "text": "nidhi_biet" }, { "code": null, "e": 33057, "s": 33040, "text": "_saurabh_jaiswal" }, { "code": null, "e": 33070, "s": 33057, "text": "Prime Number" }, { "code": null, "e": 33076, "s": 33070, "text": "sieve" }, { "code": null, "e": 33100, "s": 33076, "text": "Technical Scripter 2018" }, { "code": null, "e": 33107, "s": 33100, "text": "Arrays" }, { "code": null, "e": 33126, "s": 33107, "text": "Technical Scripter" }, { "code": null, "e": 33133, "s": 33126, "text": "Arrays" }, { "code": null, "e": 33146, "s": 33133, "text": "Prime Number" }, { "code": null, "e": 33152, "s": 33146, "text": "sieve" }, { "code": null, "e": 33250, "s": 33152, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33318, "s": 33250, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33362, "s": 33318, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33385, "s": 33362, "text": "Introduction to Arrays" }, { "code": null, "e": 33417, "s": 33385, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33431, "s": 33417, "text": "Linear Search" }, { "code": null, "e": 33452, "s": 33431, "text": "Linked List vs Array" }, { "code": null, "e": 33537, "s": 33452, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33582, "s": 33537, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 33630, "s": 33582, "text": "Search an element in a sorted and rotated array" } ]
Count Odd and Even numbers in a range from L to R - GeeksforGeeks
30 Apr, 2021 Given two numbers L and R, the task is to count the number of odd numbers in the range L to R.Examples: Input: l = 3, r = 7 Output: 3 2 Count of odd numbers is 3 i.e. 3, 5, 7 Count of even numbers is 2 i.e. 4, 6Input: l = 4, r = 8 Output: 2 Approach: Total numbers in the range will be (R – L + 1) i.e. N. If N is even then the count of both odd and even numbers will be N/2.If N is odd, If L or R is odd, then the count of odd number will be N/2 + 1 and even numbers = N – countofOdd.Else, count of odd numbers will be N/2 and even numbers = N – countofOdd. If N is even then the count of both odd and even numbers will be N/2. If N is odd, If L or R is odd, then the count of odd number will be N/2 + 1 and even numbers = N – countofOdd.Else, count of odd numbers will be N/2 and even numbers = N – countofOdd. If L or R is odd, then the count of odd number will be N/2 + 1 and even numbers = N – countofOdd. Else, count of odd numbers will be N/2 and even numbers = N – countofOdd. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h> using namespace std; // Return the number of odd numbers// in the range [L, R]int countOdd(int L, int R){ int N = (R - L) / 2; // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N += 1; return N;} // Driver codeint main(){ int L = 3, R = 7; int odds = countOdd(L, R); int evens = (R - L + 1) - odds; cout << "Count of odd numbers is " << odds << endl; cout << "Count of even numbers is " << evens << endl; return 0;} // This code is contributed by Rituraj Jain // Java implementation of the above approach class GFG { // Return the number of odd numbers // in the range [L, R] static int countOdd(int L, int R) { int N = (R - L) / 2; // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N++; return N; } // Driver code public static void main(String[] args) { int L = 3, R = 7; int odds = countOdd(L, R); int evens = (R - L + 1) - odds; System.out.println("Count of odd numbers is " + odds); System.out.println("Count of even numbers is " + evens); }} # Python 3 implementation of the# above approach # Return the number of odd numbers# in the range [L, R]def countOdd(L, R): N = (R - L) // 2 # if either R or L is odd if (R % 2 != 0 or L % 2 != 0): N += 1 return N # Driver codeif __name__ == "__main__": L = 3 R = 7 odds = countOdd(L, R) evens = (R - L + 1) - odds print("Count of odd numbers is", odds) print("Count of even numbers is", evens) # This code is contributed by ita_c // C# implementation of the above approachusing System; class GFG{ // Return the number of odd numbers // in the range [L, R] static int countOdd(int L, int R) { int N = (R - L) / 2; // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N++; return N; } // Driver code public static void Main() { int L = 3, R = 7; int odds = countOdd(L, R); int evens = (R - L + 1) - odds; Console.WriteLine("Count of odd numbers is " + odds); Console.WriteLine("Count of even numbers is " + evens); }} // This code is contributed by Ryuga <?php// PHP implementation of the above approach // Return the number of odd numbers// in the range [L, R]function countOdd($L, $R){ $N = ($R - $L) / 2; // if either R or L is odd if ($R % 2 != 0 || $L % 2 != 0) $N++; return $N;} // Driver code$L = 3; $R = 7; $odds = countOdd($L, $R);$evens = ($R - $L + 1) - $odds;echo "Count of odd numbers is " . $odds . "\n";echo "Count of even numbers is " . $evens; // This code is contributed// by Akanksha Rai?> <script> // Javascript implementation// of the above approach // Return the number of odd numbers// in the range [L, R]function countOdd( L, R){ let N = Math.floor((R - L) / 2); // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N += 1; return N;} // Driver Code let L = 3, R = 7; let odds = countOdd(L, R); let evens = (R - L + 1) - odds; document.write( "Count of odd numbers is " + odds + "</br>" ); document.write( "Count of even numbers is " + evens + "</br>" ); </script> Count of odd numbers is 3 Count of even numbers is 2 ankthon ukasp Akanksha_Rai rituraj_jain jana_sayantan number-theory Mathematical School Programming number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Print all possible combinations of r elements in a given array of size n Program for factorial of a number Operators in C / C++ Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26437, "s": 26409, "text": "\n30 Apr, 2021" }, { "code": null, "e": 26543, "s": 26437, "text": "Given two numbers L and R, the task is to count the number of odd numbers in the range L to R.Examples: " }, { "code": null, "e": 26682, "s": 26543, "text": "Input: l = 3, r = 7 Output: 3 2 Count of odd numbers is 3 i.e. 3, 5, 7 Count of even numbers is 2 i.e. 4, 6Input: l = 4, r = 8 Output: 2 " }, { "code": null, "e": 26751, "s": 26684, "text": "Approach: Total numbers in the range will be (R – L + 1) i.e. N. " }, { "code": null, "e": 27004, "s": 26751, "text": "If N is even then the count of both odd and even numbers will be N/2.If N is odd, If L or R is odd, then the count of odd number will be N/2 + 1 and even numbers = N – countofOdd.Else, count of odd numbers will be N/2 and even numbers = N – countofOdd." }, { "code": null, "e": 27074, "s": 27004, "text": "If N is even then the count of both odd and even numbers will be N/2." }, { "code": null, "e": 27258, "s": 27074, "text": "If N is odd, If L or R is odd, then the count of odd number will be N/2 + 1 and even numbers = N – countofOdd.Else, count of odd numbers will be N/2 and even numbers = N – countofOdd." }, { "code": null, "e": 27356, "s": 27258, "text": "If L or R is odd, then the count of odd number will be N/2 + 1 and even numbers = N – countofOdd." }, { "code": null, "e": 27430, "s": 27356, "text": "Else, count of odd numbers will be N/2 and even numbers = N – countofOdd." }, { "code": null, "e": 27482, "s": 27430, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27486, "s": 27482, "text": "C++" }, { "code": null, "e": 27491, "s": 27486, "text": "Java" }, { "code": null, "e": 27500, "s": 27491, "text": "Python 3" }, { "code": null, "e": 27503, "s": 27500, "text": "C#" }, { "code": null, "e": 27507, "s": 27503, "text": "PHP" }, { "code": null, "e": 27518, "s": 27507, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h> using namespace std; // Return the number of odd numbers// in the range [L, R]int countOdd(int L, int R){ int N = (R - L) / 2; // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N += 1; return N;} // Driver codeint main(){ int L = 3, R = 7; int odds = countOdd(L, R); int evens = (R - L + 1) - odds; cout << \"Count of odd numbers is \" << odds << endl; cout << \"Count of even numbers is \" << evens << endl; return 0;} // This code is contributed by Rituraj Jain", "e": 28098, "s": 27518, "text": null }, { "code": "// Java implementation of the above approach class GFG { // Return the number of odd numbers // in the range [L, R] static int countOdd(int L, int R) { int N = (R - L) / 2; // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N++; return N; } // Driver code public static void main(String[] args) { int L = 3, R = 7; int odds = countOdd(L, R); int evens = (R - L + 1) - odds; System.out.println(\"Count of odd numbers is \" + odds); System.out.println(\"Count of even numbers is \" + evens); }}", "e": 28699, "s": 28098, "text": null }, { "code": "# Python 3 implementation of the# above approach # Return the number of odd numbers# in the range [L, R]def countOdd(L, R): N = (R - L) // 2 # if either R or L is odd if (R % 2 != 0 or L % 2 != 0): N += 1 return N # Driver codeif __name__ == \"__main__\": L = 3 R = 7 odds = countOdd(L, R) evens = (R - L + 1) - odds print(\"Count of odd numbers is\", odds) print(\"Count of even numbers is\", evens) # This code is contributed by ita_c", "e": 29176, "s": 28699, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Return the number of odd numbers // in the range [L, R] static int countOdd(int L, int R) { int N = (R - L) / 2; // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N++; return N; } // Driver code public static void Main() { int L = 3, R = 7; int odds = countOdd(L, R); int evens = (R - L + 1) - odds; Console.WriteLine(\"Count of odd numbers is \" + odds); Console.WriteLine(\"Count of even numbers is \" + evens); }} // This code is contributed by Ryuga", "e": 29809, "s": 29176, "text": null }, { "code": "<?php// PHP implementation of the above approach // Return the number of odd numbers// in the range [L, R]function countOdd($L, $R){ $N = ($R - $L) / 2; // if either R or L is odd if ($R % 2 != 0 || $L % 2 != 0) $N++; return $N;} // Driver code$L = 3; $R = 7; $odds = countOdd($L, $R);$evens = ($R - $L + 1) - $odds;echo \"Count of odd numbers is \" . $odds . \"\\n\";echo \"Count of even numbers is \" . $evens; // This code is contributed// by Akanksha Rai?>", "e": 30284, "s": 29809, "text": null }, { "code": "<script> // Javascript implementation// of the above approach // Return the number of odd numbers// in the range [L, R]function countOdd( L, R){ let N = Math.floor((R - L) / 2); // if either R or L is odd if (R % 2 != 0 || L % 2 != 0) N += 1; return N;} // Driver Code let L = 3, R = 7; let odds = countOdd(L, R); let evens = (R - L + 1) - odds; document.write( \"Count of odd numbers is \" + odds + \"</br>\" ); document.write( \"Count of even numbers is \" + evens + \"</br>\" ); </script>", "e": 30842, "s": 30284, "text": null }, { "code": null, "e": 30895, "s": 30842, "text": "Count of odd numbers is 3\nCount of even numbers is 2" }, { "code": null, "e": 30905, "s": 30897, "text": "ankthon" }, { "code": null, "e": 30911, "s": 30905, "text": "ukasp" }, { "code": null, "e": 30924, "s": 30911, "text": "Akanksha_Rai" }, { "code": null, "e": 30937, "s": 30924, "text": "rituraj_jain" }, { "code": null, "e": 30951, "s": 30937, "text": "jana_sayantan" }, { "code": null, "e": 30965, "s": 30951, "text": "number-theory" }, { "code": null, "e": 30978, "s": 30965, "text": "Mathematical" }, { "code": null, "e": 30997, "s": 30978, "text": "School Programming" }, { "code": null, "e": 31011, "s": 30997, "text": "number-theory" }, { "code": null, "e": 31024, "s": 31011, "text": "Mathematical" }, { "code": null, "e": 31122, "s": 31024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31146, "s": 31122, "text": "Merge two sorted arrays" }, { "code": null, "e": 31189, "s": 31146, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31262, "s": 31189, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31296, "s": 31262, "text": "Program for factorial of a number" }, { "code": null, "e": 31317, "s": 31296, "text": "Operators in C / C++" }, { "code": null, "e": 31335, "s": 31317, "text": "Python Dictionary" }, { "code": null, "e": 31351, "s": 31335, "text": "Arrays in C/C++" }, { "code": null, "e": 31370, "s": 31351, "text": "Inheritance in C++" }, { "code": null, "e": 31395, "s": 31370, "text": "Reverse a string in Java" } ]
Check if Array can be split into subarrays such that XOR of length of Longest Decreasing Subsequences of those subarrays is 0 - GeeksforGeeks
17 Dec, 2021 Given an array of integers arr[] of size N, the task is to check whether arr[] can be split into different subarrays such that on taking the XOR of lengths of LDS (Longest decreasing subsequences) of all the subarrays is equal to 0. Print ‘YES‘ if it is possible to split else print ‘NO‘. Examples: Input: arr[] = {1, 0, 3, 4, 5}Output: YESExplanation: {1}, {0}, {3}, {4, 5} length of LDS of subarrays: 1, 1, 1, 1, XOR of lengths = 0. So answer is Yes. Input: arr[] = {5, 4, 3}Output: NO Approach: The XOR operation of even number of 1’s is 0. So if the array length is even then each element can be considered as LDS of size 1 which makes XOR of even 1’s equal to 0 and for odd length arrays to have even LDS’s with 1’s any subarray of size 2 can be considered with LDS i.e. the subarray should be strictly increasing so the LDS will be 1. Follow the steps below to solve the problem: Initialize a variable found as false. If N is even print ‘YES’ and return. Else, Iterate over the range (0, N – 1] using the variable i and perform the following tasks:Check if there is consecutive increasing elements by arr[i]>arr[i-1]If arr[i]>arr[i-1] make found as true and come out of the loop Check if there is consecutive increasing elements by arr[i]>arr[i-1] If arr[i]>arr[i-1] make found as true and come out of the loop If found is true print “YES”, else print “NO” Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find XOR of LDS's// of subarraysvoid xor_of_lds(int arr[], int n){ // If length is even each element // can be considered as lds of length // 1 which makes even 1's and xor is 0 if (n % 2 == 0) { cout << "YES" << endl; return; } else { // For odd length we need to find // even subarray of length 2 which // is strictly increasing so that it // makes a subarray with lds=1 bool found = 0; for (int i = 1; i < n; i++) { // Check if there are 2 // consecutive increasing elements if (arr[i] > arr[i - 1]) { found = 1; break; } } if (found == 1) cout << "YES" << endl; else cout << "NO" << endl; }} // Driver Codeint main(){ // Initializing array of arr int arr[] = { 1, 0, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Call the function xor_of_lds(arr, N); return 0;} // Java code for the above approachimport java.util.*;class GFG{ // Function to find XOR of LDS's// of subarraysstatic void xor_of_lds(int arr[], int n){ // If length is even each element // can be considered as lds of length // 1 which makes even 1's and xor is 0 if (n % 2 == 0) { System.out.print("YES" +"\n"); return; } else { // For odd length we need to find // even subarray of length 2 which // is strictly increasing so that it // makes a subarray with lds=1 boolean found = false; for (int i = 1; i < n; i++) { // Check if there are 2 // consecutive increasing elements if (arr[i] > arr[i - 1]) { found = true; break; } } if (found == true) System.out.print("YES" +"\n"); else System.out.print("NO" +"\n"); }} // Driver Codepublic static void main(String[] args){ // Initializing array of arr int arr[] = { 1, 0, 3, 4, 5 }; int N = arr.length; // Call the function xor_of_lds(arr, N); }} // This code is contributed by shikhasingrajput # Python code for the above approach # Function to find XOR of LDS's# of subarraysdef xor_of_lds (arr, n) : # If length is even each element # can be considered as lds of length # 1 which makes even 1's and xor is 0 if (n % 2 == 0): print("YES") return else: # For odd length we need to find # even subarray of length 2 which # is strictly increasing so that it # makes a subarray with lds=1 found = 0 for i in range(1, n): # Check if there are 2 # consecutive increasing elements if (arr[i] > arr[i - 1]): found = 1 break if (found == 1): print("YES") else: print("NO") # Driver Code# Initializing array of arrarr = [1, 0, 3, 4, 5]N = len(arr) # Call the functionxor_of_lds(arr, N) # This code is contributed by Saurabh Jaiswal // C# code for the above approachusing System; class GFG{ // Function to find XOR of LDS's// of subarraysstatic void xor_of_lds(int []arr, int n){ // If length is even each element // can be considered as lds of length // 1 which makes even 1's and xor is 0 if (n % 2 == 0) { Console.Write("YES" + "\n"); return; } else { // For odd length we need to find // even subarray of length 2 which // is strictly increasing so that it // makes a subarray with lds=1 bool found = false; for (int i = 1; i < n; i++) { // Check if there are 2 // consecutive increasing elements if (arr[i] > arr[i - 1]) { found = true; break; } } if (found == true) Console.Write("YES" +"\n"); else Console.Write("NO" +"\n"); }} // Driver Codepublic static void Main(){ // Initializing array of arr int []arr = { 1, 0, 3, 4, 5 }; int N = arr.Length; // Call the function xor_of_lds(arr, N);}} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to find XOR of LDS's // of subarrays const xor_of_lds = (arr, n) => { // If length is even each element // can be considered as lds of length // 1 which makes even 1's and xor is 0 if (n % 2 == 0) { document.write("YES<br/>"); return; } else { // For odd length we need to find // even subarray of length 2 which // is strictly increasing so that it // makes a subarray with lds=1 let found = 0; for (let i = 1; i < n; i++) { // Check if there are 2 // consecutive increasing elements if (arr[i] > arr[i - 1]) { found = 1; break; } } if (found == 1) document.write("YES<br/>"); else document.write("NO<br/>"); } } // Driver Code // Initializing array of arr let arr = [1, 0, 3, 4, 5]; let N = arr.length; // Call the function xor_of_lds(arr, N); // This code is contributed by rakeshsahni</script> YES Time Complexity: O(N)Auxiliary Space: O(1) rakeshsahni shikhasingrajput samim2000 _saurabh_jaiswal Bitwise-XOR subarray subsequence Arrays Divide and Conquer Greedy Mathematical Arrays Greedy Mathematical Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Trapping Rain Water Merge Sort QuickSort Binary Search Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction
[ { "code": null, "e": 24716, "s": 24688, "text": "\n17 Dec, 2021" }, { "code": null, "e": 25005, "s": 24716, "text": "Given an array of integers arr[] of size N, the task is to check whether arr[] can be split into different subarrays such that on taking the XOR of lengths of LDS (Longest decreasing subsequences) of all the subarrays is equal to 0. Print ‘YES‘ if it is possible to split else print ‘NO‘." }, { "code": null, "e": 25015, "s": 25005, "text": "Examples:" }, { "code": null, "e": 25169, "s": 25015, "text": "Input: arr[] = {1, 0, 3, 4, 5}Output: YESExplanation: {1}, {0}, {3}, {4, 5} length of LDS of subarrays: 1, 1, 1, 1, XOR of lengths = 0. So answer is Yes." }, { "code": null, "e": 25204, "s": 25169, "text": "Input: arr[] = {5, 4, 3}Output: NO" }, { "code": null, "e": 25602, "s": 25204, "text": "Approach: The XOR operation of even number of 1’s is 0. So if the array length is even then each element can be considered as LDS of size 1 which makes XOR of even 1’s equal to 0 and for odd length arrays to have even LDS’s with 1’s any subarray of size 2 can be considered with LDS i.e. the subarray should be strictly increasing so the LDS will be 1. Follow the steps below to solve the problem:" }, { "code": null, "e": 25640, "s": 25602, "text": "Initialize a variable found as false." }, { "code": null, "e": 25677, "s": 25640, "text": "If N is even print ‘YES’ and return." }, { "code": null, "e": 25901, "s": 25677, "text": "Else, Iterate over the range (0, N – 1] using the variable i and perform the following tasks:Check if there is consecutive increasing elements by arr[i]>arr[i-1]If arr[i]>arr[i-1] make found as true and come out of the loop" }, { "code": null, "e": 25970, "s": 25901, "text": "Check if there is consecutive increasing elements by arr[i]>arr[i-1]" }, { "code": null, "e": 26033, "s": 25970, "text": "If arr[i]>arr[i-1] make found as true and come out of the loop" }, { "code": null, "e": 26079, "s": 26033, "text": "If found is true print “YES”, else print “NO”" }, { "code": null, "e": 26130, "s": 26079, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26134, "s": 26130, "text": "C++" }, { "code": null, "e": 26139, "s": 26134, "text": "Java" }, { "code": null, "e": 26147, "s": 26139, "text": "Python3" }, { "code": null, "e": 26150, "s": 26147, "text": "C#" }, { "code": null, "e": 26161, "s": 26150, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find XOR of LDS's// of subarraysvoid xor_of_lds(int arr[], int n){ // If length is even each element // can be considered as lds of length // 1 which makes even 1's and xor is 0 if (n % 2 == 0) { cout << \"YES\" << endl; return; } else { // For odd length we need to find // even subarray of length 2 which // is strictly increasing so that it // makes a subarray with lds=1 bool found = 0; for (int i = 1; i < n; i++) { // Check if there are 2 // consecutive increasing elements if (arr[i] > arr[i - 1]) { found = 1; break; } } if (found == 1) cout << \"YES\" << endl; else cout << \"NO\" << endl; }} // Driver Codeint main(){ // Initializing array of arr int arr[] = { 1, 0, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Call the function xor_of_lds(arr, N); return 0;}", "e": 27246, "s": 26161, "text": null }, { "code": "// Java code for the above approachimport java.util.*;class GFG{ // Function to find XOR of LDS's// of subarraysstatic void xor_of_lds(int arr[], int n){ // If length is even each element // can be considered as lds of length // 1 which makes even 1's and xor is 0 if (n % 2 == 0) { System.out.print(\"YES\" +\"\\n\"); return; } else { // For odd length we need to find // even subarray of length 2 which // is strictly increasing so that it // makes a subarray with lds=1 boolean found = false; for (int i = 1; i < n; i++) { // Check if there are 2 // consecutive increasing elements if (arr[i] > arr[i - 1]) { found = true; break; } } if (found == true) System.out.print(\"YES\" +\"\\n\"); else System.out.print(\"NO\" +\"\\n\"); }} // Driver Codepublic static void main(String[] args){ // Initializing array of arr int arr[] = { 1, 0, 3, 4, 5 }; int N = arr.length; // Call the function xor_of_lds(arr, N); }} // This code is contributed by shikhasingrajput", "e": 28407, "s": 27246, "text": null }, { "code": "# Python code for the above approach # Function to find XOR of LDS's# of subarraysdef xor_of_lds (arr, n) : # If length is even each element # can be considered as lds of length # 1 which makes even 1's and xor is 0 if (n % 2 == 0): print(\"YES\") return else: # For odd length we need to find # even subarray of length 2 which # is strictly increasing so that it # makes a subarray with lds=1 found = 0 for i in range(1, n): # Check if there are 2 # consecutive increasing elements if (arr[i] > arr[i - 1]): found = 1 break if (found == 1): print(\"YES\") else: print(\"NO\") # Driver Code# Initializing array of arrarr = [1, 0, 3, 4, 5]N = len(arr) # Call the functionxor_of_lds(arr, N) # This code is contributed by Saurabh Jaiswal", "e": 29310, "s": 28407, "text": null }, { "code": "// C# code for the above approachusing System; class GFG{ // Function to find XOR of LDS's// of subarraysstatic void xor_of_lds(int []arr, int n){ // If length is even each element // can be considered as lds of length // 1 which makes even 1's and xor is 0 if (n % 2 == 0) { Console.Write(\"YES\" + \"\\n\"); return; } else { // For odd length we need to find // even subarray of length 2 which // is strictly increasing so that it // makes a subarray with lds=1 bool found = false; for (int i = 1; i < n; i++) { // Check if there are 2 // consecutive increasing elements if (arr[i] > arr[i - 1]) { found = true; break; } } if (found == true) Console.Write(\"YES\" +\"\\n\"); else Console.Write(\"NO\" +\"\\n\"); }} // Driver Codepublic static void Main(){ // Initializing array of arr int []arr = { 1, 0, 3, 4, 5 }; int N = arr.Length; // Call the function xor_of_lds(arr, N);}} // This code is contributed by Samim Hossain Mondal.", "e": 30448, "s": 29310, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find XOR of LDS's // of subarrays const xor_of_lds = (arr, n) => { // If length is even each element // can be considered as lds of length // 1 which makes even 1's and xor is 0 if (n % 2 == 0) { document.write(\"YES<br/>\"); return; } else { // For odd length we need to find // even subarray of length 2 which // is strictly increasing so that it // makes a subarray with lds=1 let found = 0; for (let i = 1; i < n; i++) { // Check if there are 2 // consecutive increasing elements if (arr[i] > arr[i - 1]) { found = 1; break; } } if (found == 1) document.write(\"YES<br/>\"); else document.write(\"NO<br/>\"); } } // Driver Code // Initializing array of arr let arr = [1, 0, 3, 4, 5]; let N = arr.length; // Call the function xor_of_lds(arr, N); // This code is contributed by rakeshsahni</script>", "e": 31651, "s": 30448, "text": null }, { "code": null, "e": 31658, "s": 31654, "text": "YES" }, { "code": null, "e": 31703, "s": 31660, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 31717, "s": 31705, "text": "rakeshsahni" }, { "code": null, "e": 31734, "s": 31717, "text": "shikhasingrajput" }, { "code": null, "e": 31744, "s": 31734, "text": "samim2000" }, { "code": null, "e": 31761, "s": 31744, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31773, "s": 31761, "text": "Bitwise-XOR" }, { "code": null, "e": 31782, "s": 31773, "text": "subarray" }, { "code": null, "e": 31794, "s": 31782, "text": "subsequence" }, { "code": null, "e": 31801, "s": 31794, "text": "Arrays" }, { "code": null, "e": 31820, "s": 31801, "text": "Divide and Conquer" }, { "code": null, "e": 31827, "s": 31820, "text": "Greedy" }, { "code": null, "e": 31840, "s": 31827, "text": "Mathematical" }, { "code": null, "e": 31847, "s": 31840, "text": "Arrays" }, { "code": null, "e": 31854, "s": 31847, "text": "Greedy" }, { "code": null, "e": 31867, "s": 31854, "text": "Mathematical" }, { "code": null, "e": 31886, "s": 31867, "text": "Divide and Conquer" }, { "code": null, "e": 31984, "s": 31886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31993, "s": 31984, "text": "Comments" }, { "code": null, "e": 32006, "s": 31993, "text": "Old Comments" }, { "code": null, "e": 32031, "s": 32006, "text": "Window Sliding Technique" }, { "code": null, "e": 32080, "s": 32031, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32118, "s": 32080, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32176, "s": 32118, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 32196, "s": 32176, "text": "Trapping Rain Water" }, { "code": null, "e": 32207, "s": 32196, "text": "Merge Sort" }, { "code": null, "e": 32217, "s": 32207, "text": "QuickSort" }, { "code": null, "e": 32231, "s": 32217, "text": "Binary Search" }, { "code": null, "e": 32258, "s": 32231, "text": "Program for Tower of Hanoi" } ]
How many types of inheritance are there in Python?
Inheritance is concept where one class accesses the methods and properties of another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class. There are two types of inheritance in python − Multiple Inheritance Multilevel Inheritance In multiple inheritance one child class can inherit multiple parent classes. class Father: fathername = "" def father(self): print(self.fathername) class Mother: mothername = "" def mother(self): print(self.mothername) class Daughter(Father, Mother): def parent(self): print("Father :", self.fathername) print("Mother :", self.mothername) s1 = Daughter() s1.fathername = "Srinivas" s1.mothername = "Anjali" s1.parent() Father : Srinivas Mother : Anjali In this type of inheritance, a class can inherit from a child class/derived class. #Daughter class inherited from Father and Mother classes which derived from Family class. class Family: def family(self): print("This is My family:") class Father(Family): fathername = "" def father(self): print(self.fathername) class Mother(Family): mothername = "" def mother(self): print(self.mothername) class Daughter(Father, Mother): def parent(self): print("Father :", self.fathername) print("Mother :", self.mothername) s1 = Daughter() s1.fathername = "Srinivas" s1.mothername = "Anjali" s1.family() s1.parent() This is My family: Father : Srinivas Mother : Anjali
[ { "code": null, "e": 1155, "s": 1062, "text": "Inheritance is concept where one class accesses the methods and properties of another class." }, { "code": null, "e": 1227, "s": 1155, "text": "Parent class is the class being inherited from, also called base class." }, { "code": null, "e": 1313, "s": 1227, "text": "Child class is the class that inherits from another class, also called derived class." }, { "code": null, "e": 1360, "s": 1313, "text": "There are two types of inheritance in python −" }, { "code": null, "e": 1381, "s": 1360, "text": "Multiple Inheritance" }, { "code": null, "e": 1404, "s": 1381, "text": "Multilevel Inheritance" }, { "code": null, "e": 1481, "s": 1404, "text": "In multiple inheritance one child class can inherit multiple parent classes." }, { "code": null, "e": 1865, "s": 1481, "text": "class Father:\n fathername = \"\"\n def father(self):\n print(self.fathername)\n\nclass Mother:\n mothername = \"\"\n def mother(self):\n print(self.mothername)\n\nclass Daughter(Father, Mother):\n def parent(self):\n print(\"Father :\", self.fathername)\n print(\"Mother :\", self.mothername)\n\ns1 = Daughter()\ns1.fathername = \"Srinivas\"\ns1.mothername = \"Anjali\"\ns1.parent()" }, { "code": null, "e": 1899, "s": 1865, "text": "Father : Srinivas\nMother : Anjali" }, { "code": null, "e": 1982, "s": 1899, "text": "In this type of inheritance, a class can inherit from a child class/derived class." }, { "code": null, "e": 2557, "s": 1982, "text": "#Daughter class inherited from Father and Mother classes which derived from Family class.\nclass Family:\n def family(self):\n print(\"This is My family:\")\n\nclass Father(Family):\n fathername = \"\"\n def father(self):\n print(self.fathername)\n\nclass Mother(Family):\n mothername = \"\"\n def mother(self):\n print(self.mothername)\n \nclass Daughter(Father, Mother):\n def parent(self):\n print(\"Father :\", self.fathername)\n print(\"Mother :\", self.mothername)\n\ns1 = Daughter()\ns1.fathername = \"Srinivas\"\ns1.mothername = \"Anjali\"\ns1.family()\ns1.parent()" }, { "code": null, "e": 2610, "s": 2557, "text": "This is My family:\nFather : Srinivas\nMother : Anjali" } ]
Connecting to a MySQL database with Java
Use below URL to connect MySQL database. The syntax is as follows − String MySQLURL="jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false"; String databseUserName="yourUserName"; String databasePassword="yourPassword"; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class ConnectToDatabase { public static void main(String[] args) { String MySQLURL = "jdbc:mysql://localhost:3306/web?useSSL=false"; String databseUserName = "root"; String databasePassword = "123456"; Connection con = null; try { con = DriverManager.getConnection(MySQLURL, databseUserName, databasePassword); if (con != null) { System.out.println("Database connection is successful !!!!"); } } catch (Exception e) { e.printStackTrace(); } } } Database connection is successful !!!! Here is the snapshot of the output −
[ { "code": null, "e": 1130, "s": 1062, "text": "Use below URL to connect MySQL database. The syntax is as follows −" }, { "code": null, "e": 1286, "s": 1130, "text": "String MySQLURL=\"jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false\";\nString databseUserName=\"yourUserName\";\nString databasePassword=\"yourPassword\";" }, { "code": null, "e": 1928, "s": 1286, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class ConnectToDatabase {\n public static void main(String[] args) {\n String MySQLURL = \"jdbc:mysql://localhost:3306/web?useSSL=false\";\n String databseUserName = \"root\";\n String databasePassword = \"123456\";\n Connection con = null;\n try {\n con = DriverManager.getConnection(MySQLURL, databseUserName, databasePassword);\n if (con != null) {\n System.out.println(\"Database connection is successful !!!!\");\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 1967, "s": 1928, "text": "Database connection is successful !!!!" }, { "code": null, "e": 2004, "s": 1967, "text": "Here is the snapshot of the output −" } ]
PHP - imap_open() Function
PHP−IMAP functions helps you to access an email accounts, IMAP stands for Internet Mail Access Protocol using these functions you can also work with NNTP, POP3 protocols and local mailbox access methods. The imap_open() function accepts three string values representing the mailbox name/URL, user name and, password as parameters and opens stream to the specified mailbox. imap_open ($mailbox, $username, $password [$options, $n_retries, $params); mailbox(Mandatory) This is a string value representing the name/URL of the mailbox. It contains the server name, mailbox path. username(Mandatory) This is a string value representing the user name. password(Mandatory) This is a string value representing the password. options (Optional) This is an integer value representing the optional parameter which can be one or more of the following − OP_READONLY OP_READONLY OP_ANONYMOUS OP_ANONYMOUS OP_HALFOPEN OP_HALFOPEN CL_EXPUNGE CL_EXPUNGE OP_DEBUG OP_DEBUG OP_SHORTCACHE OP_SHORTCACHE OP_SILENT OP_SILENT OP_PROTOTYPE OP_PROTOTYPE OP_SECURE OP_SECURE retries (Optional) This is an integer value representing the maximum number of attempts. params (Optional) This is an array value representing the connection parameters. This function returns an IMAP stream object in case of success and a Boolean value FALSE in case of failure. This function was first introduced in PHP Version 4 and works in all the later versions. Following is an php program tries to establish a connection with a particular Gmail account imap_open() − <html> <body> <?php $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX"; $id = "[email protected]"; $pwd = "cohondob_123"; $mailbox = imap_open($url, $id, $pwd); if($mailbox){ print("Connection established...."); } else { print("Connection failed"); } ?> </body> </html> The above program generates the following output − Connection established.... Following is another example of this function in this we have established connection to a particular mail box and retrieved the contents of the message in it. <html> <body> <?php //Establishing connection $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX"; $id = "[email protected]"; $pwd = "cohondob_123"; $imap = imap_open($url, $id, $pwd); print("Connection established...."."<br>"); //Searching emails $emailData = imap_search($imap, ''); if (! empty($emailData)) { foreach ($emailData as $msg) { $msg = imap_fetchbody($imap, $msg, "1"); print(quoted_printable_decode($msg)."<br>"); } } //Closing the connection imap_close($imap); ?> </body> </html> The above program generates the following output − Connection established.... This is a test mail #1. --0000000000001bf26805af905277 Content-Type: text/plain; charset="UTF-8" test mail #2 --0000000000001bf26805af905277 Content-Type: text/html; charset="UTF-8" Content-Transfer-Encoding: quoted-printable test mail #2 --0000000000001bf26805af905277-- test mail #3 test mail #4 Following is the example of this function with optional parameters. <html> <body> <?php //Establishing the connection $url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX"; $id = "[email protected]"; $pwd = "cohondob_123"; //Optional parameters $options = OP_READONLY; $retries = 10; $mailbox = imap_open($url, $id, $pwd, $options, $retries); if($mailbox){ print("Connection established...."); } else { print("Connection failed"); } ?> </body> </html> The above program generates the following output − Connection established.... 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2961, "s": 2757, "text": "PHP−IMAP functions helps you to access an email accounts, IMAP stands for Internet Mail Access Protocol using these functions you can also work with NNTP, POP3 protocols and local mailbox access methods." }, { "code": null, "e": 3130, "s": 2961, "text": "The imap_open() function accepts three string values representing the mailbox name/URL, user name and, password as parameters and opens stream to the specified mailbox." }, { "code": null, "e": 3206, "s": 3130, "text": "imap_open ($mailbox, $username, $password [$options, $n_retries, $params);\n" }, { "code": null, "e": 3225, "s": 3206, "text": "mailbox(Mandatory)" }, { "code": null, "e": 3333, "s": 3225, "text": "This is a string value representing the name/URL of the mailbox. It contains the server name, mailbox path." }, { "code": null, "e": 3353, "s": 3333, "text": "username(Mandatory)" }, { "code": null, "e": 3404, "s": 3353, "text": "This is a string value representing the user name." }, { "code": null, "e": 3424, "s": 3404, "text": "password(Mandatory)" }, { "code": null, "e": 3474, "s": 3424, "text": "This is a string value representing the password." }, { "code": null, "e": 3493, "s": 3474, "text": "options (Optional)" }, { "code": null, "e": 3598, "s": 3493, "text": "This is an integer value representing the optional parameter which can be one or more of the following −" }, { "code": null, "e": 3610, "s": 3598, "text": "OP_READONLY" }, { "code": null, "e": 3622, "s": 3610, "text": "OP_READONLY" }, { "code": null, "e": 3635, "s": 3622, "text": "OP_ANONYMOUS" }, { "code": null, "e": 3648, "s": 3635, "text": "OP_ANONYMOUS" }, { "code": null, "e": 3660, "s": 3648, "text": "OP_HALFOPEN" }, { "code": null, "e": 3672, "s": 3660, "text": "OP_HALFOPEN" }, { "code": null, "e": 3683, "s": 3672, "text": "CL_EXPUNGE" }, { "code": null, "e": 3694, "s": 3683, "text": "CL_EXPUNGE" }, { "code": null, "e": 3703, "s": 3694, "text": "OP_DEBUG" }, { "code": null, "e": 3712, "s": 3703, "text": "OP_DEBUG" }, { "code": null, "e": 3726, "s": 3712, "text": "OP_SHORTCACHE" }, { "code": null, "e": 3740, "s": 3726, "text": "OP_SHORTCACHE" }, { "code": null, "e": 3750, "s": 3740, "text": "OP_SILENT" }, { "code": null, "e": 3760, "s": 3750, "text": "OP_SILENT" }, { "code": null, "e": 3773, "s": 3760, "text": "OP_PROTOTYPE" }, { "code": null, "e": 3786, "s": 3773, "text": "OP_PROTOTYPE" }, { "code": null, "e": 3797, "s": 3786, "text": "OP_SECURE " }, { "code": null, "e": 3808, "s": 3797, "text": "OP_SECURE " }, { "code": null, "e": 3827, "s": 3808, "text": "retries (Optional)" }, { "code": null, "e": 3897, "s": 3827, "text": "This is an integer value representing the maximum number of attempts." }, { "code": null, "e": 3915, "s": 3897, "text": "params (Optional)" }, { "code": null, "e": 3978, "s": 3915, "text": "This is an array value representing the connection parameters." }, { "code": null, "e": 4087, "s": 3978, "text": "This function returns an IMAP stream object in case of success and a Boolean value FALSE in case of failure." }, { "code": null, "e": 4176, "s": 4087, "text": "This function was first introduced in PHP Version 4 and works in all the later versions." }, { "code": null, "e": 4282, "s": 4176, "text": "Following is an php program tries to establish a connection with a particular Gmail account imap_open() −" }, { "code": null, "e": 4678, "s": 4282, "text": "<html>\n <body>\n <?php\n $url = \"{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX\";\n $id = \"[email protected]\";\n $pwd = \"cohondob_123\";\n $mailbox = imap_open($url, $id, $pwd);\n if($mailbox){\n print(\"Connection established....\");\n } else {\n print(\"Connection failed\");\n }\n ?>\n </body>\n</html>" }, { "code": null, "e": 4729, "s": 4678, "text": "The above program generates the following output −" }, { "code": null, "e": 4757, "s": 4729, "text": "Connection established....\n" }, { "code": null, "e": 4916, "s": 4757, "text": "Following is another example of this function in this we have established connection to a particular mail box and retrieved the contents of the message in it." }, { "code": null, "e": 5647, "s": 4916, "text": "<html>\n <body>\n <?php\n //Establishing connection\n $url = \"{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX\";\n $id = \"[email protected]\";\n $pwd = \"cohondob_123\";\n $imap = imap_open($url, $id, $pwd);\n print(\"Connection established....\".\"<br>\");\n //Searching emails\n $emailData = imap_search($imap, '');\n \n if (! empty($emailData)) { \n foreach ($emailData as $msg) {\n $msg = imap_fetchbody($imap, $msg, \"1\");\n print(quoted_printable_decode($msg).\"<br>\"); \n } \n } \n //Closing the connection\n imap_close($imap); \n ?>\n </body>\n</html>" }, { "code": null, "e": 5698, "s": 5647, "text": "The above program generates the following output −" }, { "code": null, "e": 6027, "s": 5698, "text": "Connection established....\nThis is a test mail #1.\n--0000000000001bf26805af905277 Content-Type: text/plain; charset=\"UTF-8\" test \nmail #2 --0000000000001bf26805af905277 Content-Type: text/html; charset=\"UTF-8\" \nContent-Transfer-Encoding: quoted-printable\n\ntest mail #2\n--0000000000001bf26805af905277--\ntest mail #3\ntest mail #4\n" }, { "code": null, "e": 6095, "s": 6027, "text": "Following is the example of this function with optional parameters." }, { "code": null, "e": 6652, "s": 6095, "text": "<html>\n <body>\n <?php\n //Establishing the connection\n $url = \"{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX\";\n $id = \"[email protected]\";\n $pwd = \"cohondob_123\";\n \n //Optional parameters\n $options = OP_READONLY;\n $retries = 10;\n\t\t \n $mailbox = imap_open($url, $id, $pwd, $options, $retries);\n if($mailbox){\n print(\"Connection established....\");\n } else {\n print(\"Connection failed\");\n }\n ?>\n </body>\n</html>" }, { "code": null, "e": 6703, "s": 6652, "text": "The above program generates the following output −" }, { "code": null, "e": 6731, "s": 6703, "text": "Connection established....\n" }, { "code": null, "e": 6764, "s": 6731, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 6780, "s": 6764, "text": " Malhar Lathkar" }, { "code": null, "e": 6813, "s": 6780, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 6824, "s": 6813, "text": " Syed Raza" }, { "code": null, "e": 6859, "s": 6824, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6876, "s": 6859, "text": " Frahaan Hussain" }, { "code": null, "e": 6909, "s": 6876, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 6924, "s": 6909, "text": " Nivedita Jain" }, { "code": null, "e": 6959, "s": 6924, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 6971, "s": 6959, "text": " Azaz Patel" }, { "code": null, "e": 7006, "s": 6971, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7034, "s": 7006, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 7041, "s": 7034, "text": " Print" }, { "code": null, "e": 7052, "s": 7041, "text": " Add Notes" } ]
Difference between two vectors in R - GeeksforGeeks
23 May, 2021 In this article, we will see how to find the difference between two vectors in R Programming Language. The difference (A-B) between two vectors in R Programming is equivalent to the elements present in A which are not present in B. The resultant elements are always a subset of A. In case, both sets are non-intersecting, the entire A set is returned. The setdiff() method in R is used to retrieve the elements of vector X, which are not contained in Y. This method can be applied where the two vectors may belong to different data types, as well, where the elements of the first argument vector are returned unmodified. In case, the input vectors are equivalent, that is, they contain the same elements, then the resultant vector will have null entries and is referred by the datatype(0) output. Also, different types of results is obtained upon changing the order of vectors during the function call. Syntax: setdiff( X, Y) Example: R # declaring first integer vectorvec1 <- c(1:5) # declaring second string vectorvec2 <- c(4:8) print ("Original vector1 ")print (vec1) print ("Original vector2 ")print (vec2) # computing the difference # in vectorsdiff <- setdiff(vec1,vec2)print ("Vec1- Vec2")print (diff) Output [1] "Original vector1 " [1] 1 2 3 4 5 [1] "Original vector2 " [1] 4 5 6 7 8 [1] "Vec1- Vec2" [1] 1 2 3 This method works for string vectors as well. Example: R # declaring first integer vectorvec1 <- c("Geeksforgeeks","Interviews","Science") # declaring second string vectorvec2 <- c("Algorithms","Science", "placements","data structures") print ("Original vector1 ")print (vec1) print ("Original vector2 ")print (vec2) # computing the difference in # vectorsdiff <- setdiff(vec2,vec1)print ("Vec2 - Vec1")print (diff) Output [1] “Original vector1 “ [1] “Geeksforgeeks” “Interviews” “Science” [1] “Original vector2 “ [1] “Algorithms” “Science” “placements” “data structures” [1] “Vec2 – Vec1” [1] “Algorithms” “placements” “data structures” Also, this method automatically returns unique elements of the resultant vector. Any duplicate elements are removed. Example: R # declaring first integer vectorvec1 <- c("Geeksforgeeks","Interviews","Science") # declaring second string vectorvec2 <- c(1,2,3,5,5) print ("Original vector1 ")print (vec1) print ("Original vector2 ")print (vec2) # computing the difference in vectorsdiff <- setdiff(vec2,vec1)print ("Vec2 - Vec1")print (diff) Output [1] "Original vector1 " [1] "Geeksforgeeks" "Interviews" "Science" [1] "Original vector2 " [1] 1 2 3 5 5 [1] "Vec2 - Vec1" [1] 1 2 3 5 The %in% operator can be used to check for the presence of an element in the list. This approach first checks which indexes of vector1 are not in vector2 and then the corresponding elements of vector1 are returned. This is followed by the application of the unique() method, which returns only unique elements of the resultant vector. Syntax: vec1[! vec1 %in% vec2] Example: R # declaring first integer vectorvec1 <- c("Geeksforgeeks","Interviews","Science") # declaring second string vectorvec2 <- c("Algorithms","Science", "placements","data structures") print ("Original vector1 ")print (vec1) print ("Original vector2 ")print (vec2) # computing the difference in vectorsdiff <- unique(vec1[! vec1 %in% vec2])print ("Vec1 - Vec2")print (diff) Output [1] “Original vector1 “ [1] “Geeksforgeeks” “Interviews” “Science” [1] “Original vector2 “ [1] “Algorithms” “Science” “placements” “data structures” [1] “Vec1 – Vec2” [1] “Geeksforgeeks” “Interviews” This approach is also compatible with vectors belonging to different data types. In this case, the elements of the vec1 are returned. Example: R # declaring first integer vectorvec1 <- c("Geeksforgeeks","Interviews","Science") # declaring second string vectorvec2 <- c(1,2,3,5,5) print ("Original vector1 ")print (vec1) print ("Original vector2 ")print (vec2) # computing the difference in vectorsdiff <- unique(vec2[! vec2 %in% vec1])print ("Vec2 - Vec1")print (diff) Output [1] "Original vector1 " [1] "Geeksforgeeks" "Interviews" "Science" [1] "Original vector2 " [1] 1 2 3 5 5 [1] "Vec2 - Vec1" [1] 1 2 3 5 The intersect() method in Base R is used to calculate the intersection of elements in the specified argument vectors. It returns a vector array of all the elements present in both the input vectors. The approach involves two steps, first is, intersect() method to return the intersection array. Next, is the application of negation of %in% operator to get elements of the first vector that are not present in the intersection. The returned elements will be contained in the only the first vector. Example: R # declaring first integer vectorvec1 <- c(1:5) # declaring second string vectorvec2 <- c(4:8) print ("Original vector1 ")print (vec1) print ("Original vector2 ")print (vec2) # computing the intersection of two # vectorsintersect <- intersect(vec1,vec2) # getting elements of vec1 not in # intersectiondiff <- vec1[!(vec1 %in% intersect)]print ("Elements of vec1 not in vec2")print(diff) Output [1] "Original vector1 " [1] 1 2 3 4 5 [1] "Original vector2 " [1] 4 5 6 7 8 [1] "Elements of vec1 not in vec2" [1] 1 2 3 Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n23 May, 2021" }, { "code": null, "e": 25346, "s": 25242, "text": "In this article, we will see how to find the difference between two vectors in R Programming Language. " }, { "code": null, "e": 25596, "s": 25346, "text": "The difference (A-B) between two vectors in R Programming is equivalent to the elements present in A which are not present in B. The resultant elements are always a subset of A. In case, both sets are non-intersecting, the entire A set is returned. " }, { "code": null, "e": 26148, "s": 25596, "text": "The setdiff() method in R is used to retrieve the elements of vector X, which are not contained in Y. This method can be applied where the two vectors may belong to different data types, as well, where the elements of the first argument vector are returned unmodified. In case, the input vectors are equivalent, that is, they contain the same elements, then the resultant vector will have null entries and is referred by the datatype(0) output. Also, different types of results is obtained upon changing the order of vectors during the function call. " }, { "code": null, "e": 26156, "s": 26148, "text": "Syntax:" }, { "code": null, "e": 26171, "s": 26156, "text": "setdiff( X, Y)" }, { "code": null, "e": 26180, "s": 26171, "text": "Example:" }, { "code": null, "e": 26182, "s": 26180, "text": "R" }, { "code": "# declaring first integer vectorvec1 <- c(1:5) # declaring second string vectorvec2 <- c(4:8) print (\"Original vector1 \")print (vec1) print (\"Original vector2 \")print (vec2) # computing the difference # in vectorsdiff <- setdiff(vec1,vec2)print (\"Vec1- Vec2\")print (diff)", "e": 26458, "s": 26182, "text": null }, { "code": null, "e": 26465, "s": 26458, "text": "Output" }, { "code": null, "e": 26568, "s": 26465, "text": "[1] \"Original vector1 \"\n[1] 1 2 3 4 5\n[1] \"Original vector2 \"\n[1] 4 5 6 7 8\n[1] \"Vec1- Vec2\"\n[1] 1 2 3" }, { "code": null, "e": 26615, "s": 26568, "text": "This method works for string vectors as well. " }, { "code": null, "e": 26624, "s": 26615, "text": "Example:" }, { "code": null, "e": 26626, "s": 26624, "text": "R" }, { "code": "# declaring first integer vectorvec1 <- c(\"Geeksforgeeks\",\"Interviews\",\"Science\") # declaring second string vectorvec2 <- c(\"Algorithms\",\"Science\", \"placements\",\"data structures\") print (\"Original vector1 \")print (vec1) print (\"Original vector2 \")print (vec2) # computing the difference in # vectorsdiff <- setdiff(vec2,vec1)print (\"Vec2 - Vec1\")print (diff)", "e": 26998, "s": 26626, "text": null }, { "code": null, "e": 27005, "s": 26998, "text": "Output" }, { "code": null, "e": 27029, "s": 27005, "text": "[1] “Original vector1 “" }, { "code": null, "e": 27081, "s": 27029, "text": "[1] “Geeksforgeeks” “Interviews” “Science” " }, { "code": null, "e": 27105, "s": 27081, "text": "[1] “Original vector2 “" }, { "code": null, "e": 27181, "s": 27105, "text": "[1] “Algorithms” “Science” “placements” “data structures”" }, { "code": null, "e": 27199, "s": 27181, "text": "[1] “Vec2 – Vec1”" }, { "code": null, "e": 27257, "s": 27199, "text": "[1] “Algorithms” “placements” “data structures”" }, { "code": null, "e": 27375, "s": 27257, "text": "Also, this method automatically returns unique elements of the resultant vector. Any duplicate elements are removed. " }, { "code": null, "e": 27384, "s": 27375, "text": "Example:" }, { "code": null, "e": 27386, "s": 27384, "text": "R" }, { "code": "# declaring first integer vectorvec1 <- c(\"Geeksforgeeks\",\"Interviews\",\"Science\") # declaring second string vectorvec2 <- c(1,2,3,5,5) print (\"Original vector1 \")print (vec1) print (\"Original vector2 \")print (vec2) # computing the difference in vectorsdiff <- setdiff(vec2,vec1)print (\"Vec2 - Vec1\")print (diff)", "e": 27702, "s": 27386, "text": null }, { "code": null, "e": 27709, "s": 27702, "text": "Output" }, { "code": null, "e": 27853, "s": 27709, "text": "[1] \"Original vector1 \"\n[1] \"Geeksforgeeks\" \"Interviews\" \"Science\" \n[1] \"Original vector2 \"\n[1] 1 2 3 5 5\n[1] \"Vec2 - Vec1\"\n[1] 1 2 3 5" }, { "code": null, "e": 28188, "s": 27853, "text": "The %in% operator can be used to check for the presence of an element in the list. This approach first checks which indexes of vector1 are not in vector2 and then the corresponding elements of vector1 are returned. This is followed by the application of the unique() method, which returns only unique elements of the resultant vector." }, { "code": null, "e": 28196, "s": 28188, "text": "Syntax:" }, { "code": null, "e": 28219, "s": 28196, "text": "vec1[! vec1 %in% vec2]" }, { "code": null, "e": 28228, "s": 28219, "text": "Example:" }, { "code": null, "e": 28230, "s": 28228, "text": "R" }, { "code": "# declaring first integer vectorvec1 <- c(\"Geeksforgeeks\",\"Interviews\",\"Science\") # declaring second string vectorvec2 <- c(\"Algorithms\",\"Science\", \"placements\",\"data structures\") print (\"Original vector1 \")print (vec1) print (\"Original vector2 \")print (vec2) # computing the difference in vectorsdiff <- unique(vec1[! vec1 %in% vec2])print (\"Vec1 - Vec2\")print (diff)", "e": 28612, "s": 28230, "text": null }, { "code": null, "e": 28619, "s": 28612, "text": "Output" }, { "code": null, "e": 28643, "s": 28619, "text": "[1] “Original vector1 “" }, { "code": null, "e": 28695, "s": 28643, "text": "[1] “Geeksforgeeks” “Interviews” “Science” " }, { "code": null, "e": 28719, "s": 28695, "text": "[1] “Original vector2 “" }, { "code": null, "e": 28795, "s": 28719, "text": "[1] “Algorithms” “Science” “placements” “data structures”" }, { "code": null, "e": 28813, "s": 28795, "text": "[1] “Vec1 – Vec2”" }, { "code": null, "e": 28849, "s": 28813, "text": "[1] “Geeksforgeeks” “Interviews” " }, { "code": null, "e": 28984, "s": 28849, "text": "This approach is also compatible with vectors belonging to different data types. In this case, the elements of the vec1 are returned. " }, { "code": null, "e": 28993, "s": 28984, "text": "Example:" }, { "code": null, "e": 28995, "s": 28993, "text": "R" }, { "code": "# declaring first integer vectorvec1 <- c(\"Geeksforgeeks\",\"Interviews\",\"Science\") # declaring second string vectorvec2 <- c(1,2,3,5,5) print (\"Original vector1 \")print (vec1) print (\"Original vector2 \")print (vec2) # computing the difference in vectorsdiff <- unique(vec2[! vec2 %in% vec1])print (\"Vec2 - Vec1\")print (diff)", "e": 29323, "s": 28995, "text": null }, { "code": null, "e": 29330, "s": 29323, "text": "Output" }, { "code": null, "e": 29474, "s": 29330, "text": "[1] \"Original vector1 \"\n[1] \"Geeksforgeeks\" \"Interviews\" \"Science\" \n[1] \"Original vector2 \"\n[1] 1 2 3 5 5\n[1] \"Vec2 - Vec1\"\n[1] 1 2 3 5" }, { "code": null, "e": 29972, "s": 29474, "text": "The intersect() method in Base R is used to calculate the intersection of elements in the specified argument vectors. It returns a vector array of all the elements present in both the input vectors. The approach involves two steps, first is, intersect() method to return the intersection array. Next, is the application of negation of %in% operator to get elements of the first vector that are not present in the intersection. The returned elements will be contained in the only the first vector. " }, { "code": null, "e": 29981, "s": 29972, "text": "Example:" }, { "code": null, "e": 29983, "s": 29981, "text": "R" }, { "code": "# declaring first integer vectorvec1 <- c(1:5) # declaring second string vectorvec2 <- c(4:8) print (\"Original vector1 \")print (vec1) print (\"Original vector2 \")print (vec2) # computing the intersection of two # vectorsintersect <- intersect(vec1,vec2) # getting elements of vec1 not in # intersectiondiff <- vec1[!(vec1 %in% intersect)]print (\"Elements of vec1 not in vec2\")print(diff)", "e": 30375, "s": 29983, "text": null }, { "code": null, "e": 30382, "s": 30375, "text": "Output" }, { "code": null, "e": 30503, "s": 30382, "text": "[1] \"Original vector1 \"\n[1] 1 2 3 4 5\n[1] \"Original vector2 \"\n[1] 4 5 6 7 8\n[1] \"Elements of vec1 not in vec2\"\n[1] 1 2 3" }, { "code": null, "e": 30510, "s": 30503, "text": "Picked" }, { "code": null, "e": 30528, "s": 30510, "text": "R Vector-Programs" }, { "code": null, "e": 30538, "s": 30528, "text": "R-Vectors" }, { "code": null, "e": 30549, "s": 30538, "text": "R Language" }, { "code": null, "e": 30560, "s": 30549, "text": "R Programs" }, { "code": null, "e": 30658, "s": 30560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30710, "s": 30658, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30748, "s": 30710, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30783, "s": 30748, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30841, "s": 30783, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30890, "s": 30841, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30948, "s": 30890, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30997, "s": 30948, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 31047, "s": 30997, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 31090, "s": 31047, "text": "Replace Specific Characters in String in R" } ]
Remove duplicates and map an array in JavaScript
Suppose, we have an array of objects like this − const arr = [ {id:123, value:"value1", name:"Name1"}, {id:124, value:"value2", name:"Name1"}, {id:125, value:"value3", name:"Name2"}, {id:126, value:"value4", name:"Name2"} ]; Note that some of the "name" property in objects within the array are duplicate. We are required to write a JavaScript function that takes in one such array of objects. The function should then construct a new array of strings that contains only unique "name" property value from the array. Therefore, the output for the above input should look like this − const output = ["Name1", "Name2"]; The code for this will be − const arr = [ {id:123, value:"value1", name:"Name1"}, {id:124, value:"value2", name:"Name1"}, {id:125, value:"value3", name:"Name2"}, {id:126, value:"value4", name:"Name2"} ]; const pickNames = (arr = []) =>{ const res = []; for (let i = arr.length; i−−;){ if (res.indexOf(arr[i].name) < 0) { res.push(arr[i].name); }; } return res; }; console.log(pickNames(arr)); And the output in the console will be − [ 'Name2', 'Name1' ]
[ { "code": null, "e": 1111, "s": 1062, "text": "Suppose, we have an array of objects like this −" }, { "code": null, "e": 1299, "s": 1111, "text": "const arr = [\n {id:123, value:\"value1\", name:\"Name1\"},\n {id:124, value:\"value2\", name:\"Name1\"},\n {id:125, value:\"value3\", name:\"Name2\"},\n {id:126, value:\"value4\", name:\"Name2\"}\n];" }, { "code": null, "e": 1380, "s": 1299, "text": "Note that some of the \"name\" property in objects within the array are duplicate." }, { "code": null, "e": 1590, "s": 1380, "text": "We are required to write a JavaScript function that takes in one such array of objects. The function should then construct a new array of strings that contains only unique \"name\" property value from the array." }, { "code": null, "e": 1656, "s": 1590, "text": "Therefore, the output for the above input should look like this −" }, { "code": null, "e": 1691, "s": 1656, "text": "const output = [\"Name1\", \"Name2\"];" }, { "code": null, "e": 1719, "s": 1691, "text": "The code for this will be −" }, { "code": null, "e": 2129, "s": 1719, "text": "const arr = [\n {id:123, value:\"value1\", name:\"Name1\"},\n {id:124, value:\"value2\", name:\"Name1\"},\n {id:125, value:\"value3\", name:\"Name2\"},\n {id:126, value:\"value4\", name:\"Name2\"}\n];\nconst pickNames = (arr = []) =>{\n const res = [];\n for (let i = arr.length; i−−;){\n if (res.indexOf(arr[i].name) < 0) {\n res.push(arr[i].name);\n };\n }\n return res;\n};\nconsole.log(pickNames(arr));" }, { "code": null, "e": 2169, "s": 2129, "text": "And the output in the console will be −" }, { "code": null, "e": 2190, "s": 2169, "text": "[ 'Name2', 'Name1' ]" } ]
Difference between Call by Value and Call by Reference - GeeksforGeeks
14 Aug, 2020 Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters. The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters. Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller. Call by Reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller. // C program to illustrate // call by value #include // Function Prototype void swapx(int x, int y); // Main function int main() { int a = 10, b = 20; // Pass by Values swapx(a, b); printf("a=%d b=%d\n", a, b); return 0; } // Swap functions that swaps // two values void swapx(int x, int y) { int t; t = x; x = y; y = t; printf("x=%d y=%d\n", x, y); } Output: x=20 y=10 a=10 b=20 // C program to illustrate // Call by Reference #include // Function Prototype void swapx(int*, int*); // Main function int main() { int a = 10, b = 20; // Pass reference swapx(&a, &b); printf("a=%d b=%d\n", a, b); return 0; } // Function to swap two variables // by references void swapx(int* x, int* y) { int t; t = *x; *x = *y; *y = t; printf("x=%d y=%d\n", *x, *y); } Output: x=20 y=10 a=20 b=10 Note : In C, we use pointers to achieve call by reference. In C++, we can either use pointers or references to for pass by reference. In Java, primitive types are passed as values and non-primitive types are always references. C-Functions CPP-Functions Picked C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ 'this' pointer in C++ Arrow operator -> in C/C++ with Examples 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": 24232, "s": 24204, "text": "\n14 Aug, 2020" }, { "code": null, "e": 24402, "s": 24232, "text": "Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters." }, { "code": null, "e": 24539, "s": 24402, "text": "The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters." }, { "code": null, "e": 24824, "s": 24539, "text": "Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller." }, { "code": null, "e": 25009, "s": 24824, "text": "Call by Reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller." }, { "code": null, "e": 25442, "s": 25009, "text": "// C program to illustrate\n// call by value\n\n#include \n\n// Function Prototype\nvoid swapx(int x, int y);\n\n// Main function\nint main()\n{\n int a = 10, b = 20;\n\n // Pass by Values\n swapx(a, b);\n\n printf(\"a=%d b=%d\\n\", a, b);\n\n return 0;\n}\n\n// Swap functions that swaps\n// two values\nvoid swapx(int x, int y)\n{\n int t;\n\n t = x;\n x = y;\n y = t;\n\n printf(\"x=%d y=%d\\n\", x, y);\n}\n\n\nOutput:\nx=20 y=10\na=10 b=20\n" }, { "code": null, "e": 25894, "s": 25442, "text": "// C program to illustrate\n// Call by Reference\n\n#include \n\n// Function Prototype\nvoid swapx(int*, int*);\n\n// Main function\nint main()\n{\n int a = 10, b = 20;\n\n // Pass reference\n swapx(&a, &b);\n\n printf(\"a=%d b=%d\\n\", a, b);\n\n return 0;\n}\n\n// Function to swap two variables\n// by references\nvoid swapx(int* x, int* y)\n{\n int t;\n\n t = *x;\n *x = *y;\n *y = t;\n\n printf(\"x=%d y=%d\\n\", *x, *y);\n}\n\nOutput:\nx=20 y=10\na=20 b=10\n" }, { "code": null, "e": 26121, "s": 25894, "text": "Note : In C, we use pointers to achieve call by reference. In C++, we can either use pointers or references to for pass by reference. In Java, primitive types are passed as values and non-primitive types are always references." }, { "code": null, "e": 26133, "s": 26121, "text": "C-Functions" }, { "code": null, "e": 26147, "s": 26133, "text": "CPP-Functions" }, { "code": null, "e": 26154, "s": 26147, "text": "Picked" }, { "code": null, "e": 26165, "s": 26154, "text": "C Language" }, { "code": null, "e": 26169, "s": 26165, "text": "C++" }, { "code": null, "e": 26173, "s": 26169, "text": "CPP" }, { "code": null, "e": 26271, "s": 26173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26309, "s": 26271, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26329, "s": 26309, "text": "Multithreading in C" }, { "code": null, "e": 26355, "s": 26329, "text": "Exception Handling in C++" }, { "code": null, "e": 26377, "s": 26355, "text": "'this' pointer in C++" }, { "code": null, "e": 26418, "s": 26377, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26436, "s": 26418, "text": "Vector in C++ STL" }, { "code": null, "e": 26482, "s": 26436, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 26501, "s": 26482, "text": "Inheritance in C++" }, { "code": null, "e": 26544, "s": 26501, "text": "Map in C++ Standard Template Library (STL)" } ]
NLP Text Similarity, how it works and the math behind it | by Jaskaran S. Puri | Towards Data Science
Have a look at these pairs of sentences, which one of these pairs you think has similar sentences? You might be confident about the first two, but not so much about the last two. In reality, you’re right as the sentences in the first two pairs talk about the same thing (independently) and so are quite similar. However, the sentences in last two pairs talk about very different things and hence will not be seen as similar sentences. Surprisingly, the opposite is true for NLP models. According to the way that text similarity works in NLP, the sentences in last two pairs are very much similar but not the ones in first two! 😮 Before you start judging the ability of NLP, let’s look at how it works and the math behind it. So, let’s see how the machine sees these sentences! Sentence 1: “Global warming is here” Sentences 2: “Ocean temperature is rising” For these two to be similar, even from the machine’s perspective, you’ll need to explore a whole new dimension of semantic analysis, according to which these two sentences are quite similar. Click here and type in the two sentences. Now, coming back to our NLP model, it’s time we crack it! STEP 1: Pick only the unique words from the two sentences, which’d equal 7. Unique Words: global, warming, is, here, ocean, temperature, rising STEP 2: Count the number of occurrences of unique words in each of the sentences Analysis of sentence 1 global, 1warming, 1is, 1here, 1ocean, 0temperature, 0rising, 0 Analysis of sentence 2 global, 0warming, 0is, 1here, 0ocean, 1temperature, 1rising, 1 The easy part is over and before we proceed, you must know that NLP’s text similarity works on the basis of cosine similarity. Cosine similarity is basically the cosine of the angle between two vectors. So, we want to convert the sentences into two vectors, which we’ve already done! Vector of sentence 1: [ 1, 1, 1, 1, 0, 0, 0 ] Vector of sentence 2: [ 0, 0, 1, 0, 1, 1, 1] Let’s visualize the vectors. Do note that, in our case we have a 7D vector and because it’s not possible to visualize a 7D vector, I’ll be showing you two 3D vectors and explain the working. So, here we have two 3D vectors [ 1, 1, 1 ] and [ 0, 0, 1 ]. You can imagine these vectors as 2 sentences with 3 unique words in total. Here, [ 1, 1, 1 ] would mean that all 3 unique words occur once in the first sentence while [ 0, 0, 1 ] would mean that only the 3rd unique word occurs once in the second sentence. We’re interested only in the angle between these two vectors. The closer the two lines are, the smaller will be the angle and hence, similarity increases. So, If any two sentences are perfectly similar you’d see only one line in the 3D space, as the two lines would overlap each other. I hope you understand the idea of what we’re trying to achieve here or what NLP is trying to do. So, let’s get back to our original vectors and calculate the cosine angle between the two. Our vectors: Vector of sentence 1: [ 1, 1, 1, 1, 0, 0, 0 ] Vector of sentence 2: [ 0, 0, 1, 0, 1, 1, 1] Measuring the angle between 2 vectors It’s no rocket science, all you need to know is this formula: In the numerator, we have the dot product of the vectors and in the denominator, we have the product of the lengths of the two vectors. Let’s find out the dot product for our case: The Formula -> (u1 * v1) + (u2 * v2) + ..... + (un * vn)That’d be -> (1*0) + (1*0) +(1*1) +(1*0) +(1*0) +(1*0) +(1*0) = 1Find the length of the two vectors: Let’s find out the dot product for our case: The Formula -> (u1 * v1) + (u2 * v2) + ..... + (un * vn)That’d be -> (1*0) + (1*0) +(1*1) +(1*0) +(1*0) +(1*0) +(1*0) = 1 Find the length of the two vectors: So, now we have to calculate: 1 / 4 which equals 0.25 To conclude, according to NLP text similarity, the two sentences “Global warming is here” and “Ocean temperature is rising” are only 25% similar which is completely opposite to what the semantic analysis would show. Now, let’s quickly perform the same steps for one more pair of sentences: Sentence 1: “This place is great” Sentences 2: “This is great news” Unique Words: this, is, great, place, news Vector of sentence 1: [ 1, 1, 1, 1, 0 ] Vector of sentence 2: [ 1, 1, 1, 0, 1 ] Put these vectors into the cosine formula, and you get the value 0.75, meaning a similarity of 75% Do note that, the greater the value smaller is the angle and more similar are the sentences. So, next time when you think of using NLP Text Similarity in your project, you’d know its true purpose and how it is different from Semantic Analysis.
[ { "code": null, "e": 271, "s": 172, "text": "Have a look at these pairs of sentences, which one of these pairs you think has similar sentences?" }, { "code": null, "e": 607, "s": 271, "text": "You might be confident about the first two, but not so much about the last two. In reality, you’re right as the sentences in the first two pairs talk about the same thing (independently) and so are quite similar. However, the sentences in last two pairs talk about very different things and hence will not be seen as similar sentences." }, { "code": null, "e": 801, "s": 607, "text": "Surprisingly, the opposite is true for NLP models. According to the way that text similarity works in NLP, the sentences in last two pairs are very much similar but not the ones in first two! 😮" }, { "code": null, "e": 949, "s": 801, "text": "Before you start judging the ability of NLP, let’s look at how it works and the math behind it. So, let’s see how the machine sees these sentences!" }, { "code": null, "e": 986, "s": 949, "text": "Sentence 1: “Global warming is here”" }, { "code": null, "e": 1029, "s": 986, "text": "Sentences 2: “Ocean temperature is rising”" }, { "code": null, "e": 1262, "s": 1029, "text": "For these two to be similar, even from the machine’s perspective, you’ll need to explore a whole new dimension of semantic analysis, according to which these two sentences are quite similar. Click here and type in the two sentences." }, { "code": null, "e": 1320, "s": 1262, "text": "Now, coming back to our NLP model, it’s time we crack it!" }, { "code": null, "e": 1396, "s": 1320, "text": "STEP 1: Pick only the unique words from the two sentences, which’d equal 7." }, { "code": null, "e": 1464, "s": 1396, "text": "Unique Words: global, warming, is, here, ocean, temperature, rising" }, { "code": null, "e": 1545, "s": 1464, "text": "STEP 2: Count the number of occurrences of unique words in each of the sentences" }, { "code": null, "e": 1568, "s": 1545, "text": "Analysis of sentence 1" }, { "code": null, "e": 1631, "s": 1568, "text": "global, 1warming, 1is, 1here, 1ocean, 0temperature, 0rising, 0" }, { "code": null, "e": 1654, "s": 1631, "text": "Analysis of sentence 2" }, { "code": null, "e": 1717, "s": 1654, "text": "global, 0warming, 0is, 1here, 0ocean, 1temperature, 1rising, 1" }, { "code": null, "e": 2001, "s": 1717, "text": "The easy part is over and before we proceed, you must know that NLP’s text similarity works on the basis of cosine similarity. Cosine similarity is basically the cosine of the angle between two vectors. So, we want to convert the sentences into two vectors, which we’ve already done!" }, { "code": null, "e": 2047, "s": 2001, "text": "Vector of sentence 1: [ 1, 1, 1, 1, 0, 0, 0 ]" }, { "code": null, "e": 2092, "s": 2047, "text": "Vector of sentence 2: [ 0, 0, 1, 0, 1, 1, 1]" }, { "code": null, "e": 2121, "s": 2092, "text": "Let’s visualize the vectors." }, { "code": null, "e": 2283, "s": 2121, "text": "Do note that, in our case we have a 7D vector and because it’s not possible to visualize a 7D vector, I’ll be showing you two 3D vectors and explain the working." }, { "code": null, "e": 2600, "s": 2283, "text": "So, here we have two 3D vectors [ 1, 1, 1 ] and [ 0, 0, 1 ]. You can imagine these vectors as 2 sentences with 3 unique words in total. Here, [ 1, 1, 1 ] would mean that all 3 unique words occur once in the first sentence while [ 0, 0, 1 ] would mean that only the 3rd unique word occurs once in the second sentence." }, { "code": null, "e": 2886, "s": 2600, "text": "We’re interested only in the angle between these two vectors. The closer the two lines are, the smaller will be the angle and hence, similarity increases. So, If any two sentences are perfectly similar you’d see only one line in the 3D space, as the two lines would overlap each other." }, { "code": null, "e": 3087, "s": 2886, "text": "I hope you understand the idea of what we’re trying to achieve here or what NLP is trying to do. So, let’s get back to our original vectors and calculate the cosine angle between the two. Our vectors:" }, { "code": null, "e": 3133, "s": 3087, "text": "Vector of sentence 1: [ 1, 1, 1, 1, 0, 0, 0 ]" }, { "code": null, "e": 3178, "s": 3133, "text": "Vector of sentence 2: [ 0, 0, 1, 0, 1, 1, 1]" }, { "code": null, "e": 3216, "s": 3178, "text": "Measuring the angle between 2 vectors" }, { "code": null, "e": 3278, "s": 3216, "text": "It’s no rocket science, all you need to know is this formula:" }, { "code": null, "e": 3414, "s": 3278, "text": "In the numerator, we have the dot product of the vectors and in the denominator, we have the product of the lengths of the two vectors." }, { "code": null, "e": 3616, "s": 3414, "text": "Let’s find out the dot product for our case: The Formula -> (u1 * v1) + (u2 * v2) + ..... + (un * vn)That’d be -> (1*0) + (1*0) +(1*1) +(1*0) +(1*0) +(1*0) +(1*0) = 1Find the length of the two vectors:" }, { "code": null, "e": 3783, "s": 3616, "text": "Let’s find out the dot product for our case: The Formula -> (u1 * v1) + (u2 * v2) + ..... + (un * vn)That’d be -> (1*0) + (1*0) +(1*1) +(1*0) +(1*0) +(1*0) +(1*0) = 1" }, { "code": null, "e": 3819, "s": 3783, "text": "Find the length of the two vectors:" }, { "code": null, "e": 3873, "s": 3819, "text": "So, now we have to calculate: 1 / 4 which equals 0.25" }, { "code": null, "e": 4089, "s": 3873, "text": "To conclude, according to NLP text similarity, the two sentences “Global warming is here” and “Ocean temperature is rising” are only 25% similar which is completely opposite to what the semantic analysis would show." }, { "code": null, "e": 4163, "s": 4089, "text": "Now, let’s quickly perform the same steps for one more pair of sentences:" }, { "code": null, "e": 4197, "s": 4163, "text": "Sentence 1: “This place is great”" }, { "code": null, "e": 4231, "s": 4197, "text": "Sentences 2: “This is great news”" }, { "code": null, "e": 4274, "s": 4231, "text": "Unique Words: this, is, great, place, news" }, { "code": null, "e": 4314, "s": 4274, "text": "Vector of sentence 1: [ 1, 1, 1, 1, 0 ]" }, { "code": null, "e": 4354, "s": 4314, "text": "Vector of sentence 2: [ 1, 1, 1, 0, 1 ]" }, { "code": null, "e": 4453, "s": 4354, "text": "Put these vectors into the cosine formula, and you get the value 0.75, meaning a similarity of 75%" }, { "code": null, "e": 4546, "s": 4453, "text": "Do note that, the greater the value smaller is the angle and more similar are the sentences." } ]
Java DIP - Sobel Operator
Sobel operator is very similar to Prewitt operator. It is also a derivative mask and is used for edge detection. Sobel operator is used to detect two kinds of edges in an image: Vertical direction edges and Horizontal direction edges. We are going to use OpenCV function filter2D to apply Sobel operator to images. It can be found under Imgproc package. Its syntax is given below − filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT ); The function arguments are described below − src It is source image. dst It is destination image. depth It is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source. kernel It is the kernel to be scanned through the image. anchor It is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default. delta It is a value to be added to each pixel during the convolution. By default it is 0. BORDER_DEFAULT We let this value by default. Apart from the filter2D method, there are other methods provide by the Imgproc class. They are described briefly − cvtColor(Mat src, Mat dst, int code, int dstCn) It converts an image from one color space to another. dilate(Mat src, Mat dst, Mat kernel) It dilates an image by using a specific structuring element. equalizeHist(Mat src, Mat dst) It equalizes the histogram of a grayscale image. filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta) It convolves an image with the kernel. GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX) It blurs an image using a Gaussian filter. integral(Mat src, Mat sum) It calculates the integral of an image. The following example demonstrates the use of Imgproc class to apply Sobel operator to an image of Grayscale. import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; public class convolution { public static void main( String[] args ) { try { int kernelSize = 9; System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); Mat source = Highgui.imread("grayscale.jpg", Highgui.CV_LOAD_IMAGE_GRAYSCALE); Mat destination = new Mat(source.rows(),source.cols(),source.type()); Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) { { put(0,0,-1); put(0,1,0); put(0,2,1); put(1,0-2); put(1,1,0); put(1,2,2); put(2,0,-1); put(2,1,0); put(2,2,1); } }; Imgproc.filter2D(source, destination, -1, kernel); Highgui.imwrite("output.jpg", destination); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } } When you execute the given code, the following output is seen − This original image is convolved with the Sobel operator of vertical edges, which is given below − This original is convolved with the Sobel operator of horizontal edges, which is given below − 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": 2572, "s": 2337, "text": "Sobel operator is very similar to Prewitt operator. It is also a derivative mask and is used for edge detection. Sobel operator is used to detect two kinds of edges in an image: Vertical direction edges and Horizontal direction edges." }, { "code": null, "e": 2719, "s": 2572, "text": "We are going to use OpenCV function filter2D to apply Sobel operator to images. It can be found under Imgproc package. Its syntax is given below −" }, { "code": null, "e": 2788, "s": 2719, "text": "filter2D(src, dst, depth , kernel, anchor, delta, BORDER_DEFAULT );\n" }, { "code": null, "e": 2833, "s": 2788, "text": "The function arguments are described below −" }, { "code": null, "e": 2837, "s": 2833, "text": "src" }, { "code": null, "e": 2857, "s": 2837, "text": "It is source image." }, { "code": null, "e": 2861, "s": 2857, "text": "dst" }, { "code": null, "e": 2886, "s": 2861, "text": "It is destination image." }, { "code": null, "e": 2892, "s": 2886, "text": "depth" }, { "code": null, "e": 2998, "s": 2892, "text": "It is the depth of dst. A negative value (such as -1) indicates that the depth is the same as the source." }, { "code": null, "e": 3005, "s": 2998, "text": "kernel" }, { "code": null, "e": 3055, "s": 3005, "text": "It is the kernel to be scanned through the image." }, { "code": null, "e": 3062, "s": 3055, "text": "anchor" }, { "code": null, "e": 3180, "s": 3062, "text": "It is the position of the anchor relative to its kernel. The location Point (-1, -1) indicates the center by default." }, { "code": null, "e": 3186, "s": 3180, "text": "delta" }, { "code": null, "e": 3270, "s": 3186, "text": "It is a value to be added to each pixel during the convolution. By default it is 0." }, { "code": null, "e": 3285, "s": 3270, "text": "BORDER_DEFAULT" }, { "code": null, "e": 3315, "s": 3285, "text": "We let this value by default." }, { "code": null, "e": 3430, "s": 3315, "text": "Apart from the filter2D method, there are other methods provide by the Imgproc class. They are described briefly −" }, { "code": null, "e": 3478, "s": 3430, "text": "cvtColor(Mat src, Mat dst, int code, int dstCn)" }, { "code": null, "e": 3532, "s": 3478, "text": "It converts an image from one color space to another." }, { "code": null, "e": 3569, "s": 3532, "text": "dilate(Mat src, Mat dst, Mat kernel)" }, { "code": null, "e": 3630, "s": 3569, "text": "It dilates an image by using a specific structuring element." }, { "code": null, "e": 3661, "s": 3630, "text": "equalizeHist(Mat src, Mat dst)" }, { "code": null, "e": 3710, "s": 3661, "text": "It equalizes the histogram of a grayscale image." }, { "code": null, "e": 3788, "s": 3710, "text": "filter2D(Mat src, Mat dst, int depth, Mat kernel, Point anchor, double delta)" }, { "code": null, "e": 3827, "s": 3788, "text": "It convolves an image with the kernel." }, { "code": null, "e": 3885, "s": 3827, "text": "GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)" }, { "code": null, "e": 3928, "s": 3885, "text": "It blurs an image using a Gaussian filter." }, { "code": null, "e": 3955, "s": 3928, "text": "integral(Mat src, Mat sum)" }, { "code": null, "e": 3995, "s": 3955, "text": "It calculates the integral of an image." }, { "code": null, "e": 4105, "s": 3995, "text": "The following example demonstrates the use of Imgproc class to apply Sobel operator to an image of Grayscale." }, { "code": null, "e": 5227, "s": 4105, "text": "import org.opencv.core.Core;\nimport org.opencv.core.CvType;\nimport org.opencv.core.Mat;\n\nimport org.opencv.highgui.Highgui;\nimport org.opencv.imgproc.Imgproc;\n\npublic class convolution {\n public static void main( String[] args ) {\n \n try {\n int kernelSize = 9;\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n \n Mat source = Highgui.imread(\"grayscale.jpg\", Highgui.CV_LOAD_IMAGE_GRAYSCALE);\n Mat destination = new Mat(source.rows(),source.cols(),source.type());\n \n Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F) {\n {\n put(0,0,-1);\n put(0,1,0);\n put(0,2,1);\n\n put(1,0-2);\n put(1,1,0);\n put(1,2,2);\n\n put(2,0,-1);\n put(2,1,0);\n put(2,2,1);\n }\n };\t \n \n Imgproc.filter2D(source, destination, -1, kernel);\n Highgui.imwrite(\"output.jpg\", destination);\n \n } catch (Exception e) {\n System.out.println(\"Error: \" + e.getMessage());\n }\n }\n}" }, { "code": null, "e": 5291, "s": 5227, "text": "When you execute the given code, the following output is seen −" }, { "code": null, "e": 5390, "s": 5291, "text": "This original image is convolved with the Sobel operator of vertical edges, which is given below −" }, { "code": null, "e": 5485, "s": 5390, "text": "This original is convolved with the Sobel operator of horizontal edges, which is given below −" }, { "code": null, "e": 5518, "s": 5485, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5534, "s": 5518, "text": " Malhar Lathkar" }, { "code": null, "e": 5567, "s": 5534, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5583, "s": 5567, "text": " Malhar Lathkar" }, { "code": null, "e": 5618, "s": 5583, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5632, "s": 5618, "text": " Anadi Sharma" }, { "code": null, "e": 5666, "s": 5632, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5680, "s": 5666, "text": " Tushar Kale" }, { "code": null, "e": 5717, "s": 5680, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5732, "s": 5717, "text": " Monica Mittal" }, { "code": null, "e": 5765, "s": 5732, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5784, "s": 5765, "text": " Arnab Chakraborty" }, { "code": null, "e": 5791, "s": 5784, "text": " Print" }, { "code": null, "e": 5802, "s": 5791, "text": " Add Notes" } ]
PHP | fputcsv( ) Function - GeeksforGeeks
13 Jun, 2018 The fputcsv() function in PHP is an inbuilt function which is used to format a line as CSV(comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure. Syntax: int fputcsv ( $file, $fields, $separator, $enclosure ) Parameters: The fputcsv() function in PHP accepts four parameters as explained below. $file: It is a mandatory parameter which specifies the file. $fields: It is a mandatory parameter which specifies which array to get data from. $separator: It is an optional parameter which specifies the field separator. By default the fputcsv() function uses comma. $enclosure: It is an optional parameter which specifies the field enclosure character. By default the fputcsv() function uses. Return Value: This function returns the length of the written string on success or FALSE on failure. Exceptions: If an enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape_char. Enabling the auto_detect_line_endings run-time configuration option may help resolve the problem of PHP properly recognizing the line endings when reading files either on or created by a Macintosh computer. Below programs illustrate the fputcsv() function:Program 1: <?php// Sample data for formatting in CSV format$employees = array("Raj, Singh, Developer, Mumbai", "Sameer, Pandey, Tester, Bangalore", "Raghav, Chauhan, Manager, Delhi"); // opening the file "data.csv" for writing$myfile = fopen("gfg.csv", "w"); // formatting each row of data in CSV format // and outputting itforeach ($employees as $line){ fputcsv($myfile, explode(',',$line));} // closing the filefclose($myfile); ?> Output: Raj, Singh, Developer, Mumbai Sameer, Pandey, Tester, Bangalore Raghav, Chauhan, Manager, Delhi Program 2: <?php// Sample data for formatting in CSV format$random_data = array(array("abc, efg, jhi, klm"),array("123, 456, 789"),array("11aa, 22bb, 33cc, 44dd")); // opening the file "data.csv" for writing$myfile = fopen("gfg.csv", "w"); // formatting each row of data in CSV format // and outputting itforeach ($random_data as $line){ fputcsv($myfile, $line);} // closing the filefclose($myfile);?> Output: abc, efg, jhi, klm 123, 456, 789 11aa, 22bb, 33cc, 44dd Reference: http://php.net/manual/en/function.fputcsv.php PHP-file-handling PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? Comparing two dates in PHP How to receive JSON POST with PHP ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24644, "s": 24616, "text": "\n13 Jun, 2018" }, { "code": null, "e": 24969, "s": 24644, "text": "The fputcsv() function in PHP is an inbuilt function which is used to format a line as CSV(comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure." }, { "code": null, "e": 24977, "s": 24969, "text": "Syntax:" }, { "code": null, "e": 25033, "s": 24977, "text": "int fputcsv ( $file, $fields, $separator, $enclosure )\n" }, { "code": null, "e": 25119, "s": 25033, "text": "Parameters: The fputcsv() function in PHP accepts four parameters as explained below." }, { "code": null, "e": 25180, "s": 25119, "text": "$file: It is a mandatory parameter which specifies the file." }, { "code": null, "e": 25263, "s": 25180, "text": "$fields: It is a mandatory parameter which specifies which array to get data from." }, { "code": null, "e": 25386, "s": 25263, "text": "$separator: It is an optional parameter which specifies the field separator. By default the fputcsv() function uses comma." }, { "code": null, "e": 25513, "s": 25386, "text": "$enclosure: It is an optional parameter which specifies the field enclosure character. By default the fputcsv() function uses." }, { "code": null, "e": 25614, "s": 25513, "text": "Return Value: This function returns the length of the written string on success or FALSE on failure." }, { "code": null, "e": 25626, "s": 25614, "text": "Exceptions:" }, { "code": null, "e": 25765, "s": 25626, "text": "If an enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape_char." }, { "code": null, "e": 25972, "s": 25765, "text": "Enabling the auto_detect_line_endings run-time configuration option may help resolve the problem of PHP properly recognizing the line endings when reading files either on or created by a Macintosh computer." }, { "code": null, "e": 26032, "s": 25972, "text": "Below programs illustrate the fputcsv() function:Program 1:" }, { "code": "<?php// Sample data for formatting in CSV format$employees = array(\"Raj, Singh, Developer, Mumbai\", \"Sameer, Pandey, Tester, Bangalore\", \"Raghav, Chauhan, Manager, Delhi\"); // opening the file \"data.csv\" for writing$myfile = fopen(\"gfg.csv\", \"w\"); // formatting each row of data in CSV format // and outputting itforeach ($employees as $line){ fputcsv($myfile, explode(',',$line));} // closing the filefclose($myfile); ?>", "e": 26498, "s": 26032, "text": null }, { "code": null, "e": 26506, "s": 26498, "text": "Output:" }, { "code": null, "e": 26603, "s": 26506, "text": "Raj, Singh, Developer, Mumbai\nSameer, Pandey, Tester, Bangalore\nRaghav, Chauhan, Manager, Delhi\n" }, { "code": null, "e": 26614, "s": 26603, "text": "Program 2:" }, { "code": "<?php// Sample data for formatting in CSV format$random_data = array(array(\"abc, efg, jhi, klm\"),array(\"123, 456, 789\"),array(\"11aa, 22bb, 33cc, 44dd\")); // opening the file \"data.csv\" for writing$myfile = fopen(\"gfg.csv\", \"w\"); // formatting each row of data in CSV format // and outputting itforeach ($random_data as $line){ fputcsv($myfile, $line);} // closing the filefclose($myfile);?>", "e": 27011, "s": 26614, "text": null }, { "code": null, "e": 27019, "s": 27011, "text": "Output:" }, { "code": null, "e": 27076, "s": 27019, "text": "abc, efg, jhi, klm\n123, 456, 789\n11aa, 22bb, 33cc, 44dd\n" }, { "code": null, "e": 27133, "s": 27076, "text": "Reference: http://php.net/manual/en/function.fputcsv.php" }, { "code": null, "e": 27151, "s": 27133, "text": "PHP-file-handling" }, { "code": null, "e": 27164, "s": 27151, "text": "PHP-function" }, { "code": null, "e": 27168, "s": 27164, "text": "PHP" }, { "code": null, "e": 27185, "s": 27168, "text": "Web Technologies" }, { "code": null, "e": 27189, "s": 27185, "text": "PHP" }, { "code": null, "e": 27287, "s": 27189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27296, "s": 27287, "text": "Comments" }, { "code": null, "e": 27309, "s": 27296, "text": "Old Comments" }, { "code": null, "e": 27359, "s": 27309, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27399, "s": 27359, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27460, "s": 27399, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27487, "s": 27460, "text": "Comparing two dates in PHP" }, { "code": null, "e": 27523, "s": 27487, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 27565, "s": 27523, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27598, "s": 27565, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27641, "s": 27598, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27703, "s": 27641, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Apache Flink - Machine Learning
Apache Flink's Machine Learning library is called FlinkML. Since usage of machine learning has been increasing exponentially over the last 5 years, Flink community decided to add this machine learning APO also in its ecosystem. The list of contributors and algorithms are increasing in FlinkML. This API is not a part of binary distribution yet. Here is an example of linear regression using FlinkML − // LabeledVector is a feature vector with a label (class or real value) val trainingData: DataSet[LabeledVector] = ... val testingData: DataSet[Vector] = ... // Alternatively, a Splitter is used to break up a DataSet into training and testing data. val dataSet: DataSet[LabeledVector] = ... val trainTestData: DataSet[TrainTestDataSet] = Splitter.trainTestSplit(dataSet) val trainingData: DataSet[LabeledVector] = trainTestData.training val testingData: DataSet[Vector] = trainTestData.testing.map(lv => lv.vector) val mlr = MultipleLinearRegression() .setStepsize(1.0) .setIterations(100) .setConvergenceThreshold(0.001) mlr.fit(trainingData) // The fitted model can now be used to make predictions val predictions: DataSet[LabeledVector] = mlr.predict(testingData) Inside flink-1.7.1/examples/batch/ path, you will find KMeans.jar file. Let us run this sample FlinkML example. This example program is run using the default point and the centroid data set. ./bin/flink run examples/batch/KMeans.jar --output Print 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2415, "s": 2069, "text": "Apache Flink's Machine Learning library is called FlinkML. Since usage of machine learning has been increasing exponentially over the last 5 years, Flink community decided to add this machine learning APO also in its ecosystem. The list of contributors and algorithms are increasing in FlinkML. This API is not a part of binary distribution yet." }, { "code": null, "e": 2471, "s": 2415, "text": "Here is an example of linear regression using FlinkML −" }, { "code": null, "e": 3241, "s": 2471, "text": "// LabeledVector is a feature vector with a label (class or real value)\nval trainingData: DataSet[LabeledVector] = ...\nval testingData: DataSet[Vector] = ...\n\n// Alternatively, a Splitter is used to break up a DataSet into training and testing data.\nval dataSet: DataSet[LabeledVector] = ...\nval trainTestData: DataSet[TrainTestDataSet] = Splitter.trainTestSplit(dataSet)\nval trainingData: DataSet[LabeledVector] = trainTestData.training\nval testingData: DataSet[Vector] = trainTestData.testing.map(lv => lv.vector)\nval mlr = MultipleLinearRegression()\n\n.setStepsize(1.0)\n.setIterations(100)\n.setConvergenceThreshold(0.001)\nmlr.fit(trainingData)\n\n// The fitted model can now be used to make predictions\nval predictions: DataSet[LabeledVector] = mlr.predict(testingData)" }, { "code": null, "e": 3353, "s": 3241, "text": "Inside flink-1.7.1/examples/batch/ path, you will find KMeans.jar file. Let us run this sample FlinkML example." }, { "code": null, "e": 3432, "s": 3353, "text": "This example program is run using the default point and the centroid data set." }, { "code": null, "e": 3490, "s": 3432, "text": "./bin/flink run examples/batch/KMeans.jar --output Print\n" }, { "code": null, "e": 3525, "s": 3490, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3544, "s": 3525, "text": " Arnab Chakraborty" }, { "code": null, "e": 3579, "s": 3544, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3600, "s": 3579, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 3633, "s": 3600, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3646, "s": 3633, "text": " Nilay Mehta" }, { "code": null, "e": 3681, "s": 3646, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3699, "s": 3681, "text": " Bigdata Engineer" }, { "code": null, "e": 3732, "s": 3699, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 3750, "s": 3732, "text": " Bigdata Engineer" }, { "code": null, "e": 3783, "s": 3750, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 3801, "s": 3783, "text": " Bigdata Engineer" }, { "code": null, "e": 3808, "s": 3801, "text": " Print" }, { "code": null, "e": 3819, "s": 3808, "text": " Add Notes" } ]
How to create an unordered list in HTML ? - GeeksforGeeks
09 Dec, 2021 In this article, we will know how to create an unordered list in HTML. An Unordered list <ul> tag in HTML is used to define the unordered list item in an HTML document. It contains the list items <li> element. The <ul> tag requires opening and closing tags. Syntax: <ul> List of items </ul> Attribute: This tag contains two attributes which are listed below: compact: It will render the list smaller. type: It specifies which kind of marker is used in the list. Note: The <ul> attributes are not supported by HTML 5. Example: This example illustrates the use of an unordered list by using the <ul> tag. HTML <!DOCTYPE html><html> <head> <title>Unordered list</title></head> <body> <h2>Welcome To GeeksforGeeks Learning</h2> <h5>List of available courses</h5> <ul> <li>Data Structures & Algorithm</li> <li>Web Technology</li> <li>Aptitude & Logical Reasoning</li> <li>Programming Languages</li> </ul></body> </html> Output: HTML Unordered list There are several list-type attributes that can be used with unordered list items. HTML <li> type Attribute: The <li> type attribute in HTML is used to specify the type of a list items. This attribute also defines the style of the bullet point of the list items. <li type="disc|circle|square"> Attribute Values: disc: It is the default value. It creates a filled circle. circle: It creates an unfilled circle. square: It creates a filled square. Note: The <li> type attribute is not supported by HTML 5. Example: This example describes the HTML Unordered List. HTML <!DOCTYPE html><html> <head> <title>How to define an unordered list</title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML5: How to define an unordered list?</h2> <p>GeeksforGeeks courses List:</p> <ul> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html> Output: HTML Unordered list The HTML unordered list has various list item markers: Disc: It is used to set the list item marker to a bullet i.e default. Example 1: This example illustrates the use of an unordered list with a disc bullet by setting the list-style-type property to disc. HTML <!DOCTYPE html><html> <head> <title>HTML ul tag</title></head> <body> <h1>GeeksforGeeks</h1> <h2>Unordered List with Disc Bullets</h2> <p>GeeksforGeeks courses List:</p> <ul style="list-style-type:disc;"> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html> Output: Unordered list with disc list item marker Circle: It is used to set the list item marker to a circle. Example 2: In this example, we have used an unordered list with a circle bullet by setting the list-style-type property to circle. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>Unordered List with Circle Bullets</h2> <p>GeeksforGeeks courses List:</p> <ul style="list-style-type: circle"> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html> Output: Unordered list with circle list item marker Square: It is used to set the list item marker to a square. Example 3: In this example, we have used an unordered list with a square bullet by setting the list-style-type property to square. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>Unordered List with Square Bullets</h2> <p>GeeksforGeeks courses List:</p> <ul style="list-style-type: square"> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html> Output: Unordered list with square list item marker none: It is used to set the list item marker with no mark. Example 4: This example illustrates the use of an unordered list with a no bullet by setting the list-style-type property to none. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>Unordered List with No Bullets</h2> <p>GeeksforGeeks courses List:</p> <ul style="list-style-type: none"> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html> Output: Unordered list without list item marker Nested Unordered List: It is used to nest the list items i.e., list inside another list. Example: This example describes the use of the unordered list in a nested format. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>Nested Unordered List</h2> <p>GeeksforGeeks courses List:</p> <ul> <li>DSA</li> <ul> <li>Array</li> <li>Linked List</li> <li>stack</li> <li>Queue</li> </ul> <li>Web Technologies</li> <ul> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> </ul> <li>Aptitude</li> <li>Gate</li> <li>Placement</li> </ul></body> </html> Output: Nested Unordered lIst Supported Browsers: Google Chrome 94.0 & above Firefox 92.0 & above Microsoft Edge 93.0 IE 11.0 Safari 14.1 Opera 78.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. bhaskargeeksforgeeks sooda367 HTML-Attributes HTML-Questions HTML-Tags HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? REST API (Introduction) Design a web page using HTML and CSS Form validation using HTML and JavaScript Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24317, "s": 24289, "text": "\n09 Dec, 2021" }, { "code": null, "e": 24576, "s": 24317, "text": "In this article, we will know how to create an unordered list in HTML. An Unordered list <ul> tag in HTML is used to define the unordered list item in an HTML document. It contains the list items <li> element. The <ul> tag requires opening and closing tags. " }, { "code": null, "e": 24585, "s": 24576, "text": "Syntax: " }, { "code": null, "e": 24610, "s": 24585, "text": "<ul> List of items </ul>" }, { "code": null, "e": 24679, "s": 24610, "text": "Attribute: This tag contains two attributes which are listed below: " }, { "code": null, "e": 24721, "s": 24679, "text": "compact: It will render the list smaller." }, { "code": null, "e": 24782, "s": 24721, "text": "type: It specifies which kind of marker is used in the list." }, { "code": null, "e": 24837, "s": 24782, "text": "Note: The <ul> attributes are not supported by HTML 5." }, { "code": null, "e": 24924, "s": 24837, "text": "Example: This example illustrates the use of an unordered list by using the <ul> tag. " }, { "code": null, "e": 24929, "s": 24924, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Unordered list</title></head> <body> <h2>Welcome To GeeksforGeeks Learning</h2> <h5>List of available courses</h5> <ul> <li>Data Structures & Algorithm</li> <li>Web Technology</li> <li>Aptitude & Logical Reasoning</li> <li>Programming Languages</li> </ul></body> </html>", "e": 25282, "s": 24929, "text": null }, { "code": null, "e": 25290, "s": 25282, "text": "Output:" }, { "code": null, "e": 25310, "s": 25290, "text": "HTML Unordered list" }, { "code": null, "e": 25393, "s": 25310, "text": "There are several list-type attributes that can be used with unordered list items." }, { "code": null, "e": 25574, "s": 25393, "text": "HTML <li> type Attribute: The <li> type attribute in HTML is used to specify the type of a list items. This attribute also defines the style of the bullet point of the list items. " }, { "code": null, "e": 25605, "s": 25574, "text": "<li type=\"disc|circle|square\">" }, { "code": null, "e": 25624, "s": 25605, "text": "Attribute Values: " }, { "code": null, "e": 25683, "s": 25624, "text": "disc: It is the default value. It creates a filled circle." }, { "code": null, "e": 25722, "s": 25683, "text": "circle: It creates an unfilled circle." }, { "code": null, "e": 25758, "s": 25722, "text": "square: It creates a filled square." }, { "code": null, "e": 25816, "s": 25758, "text": "Note: The <li> type attribute is not supported by HTML 5." }, { "code": null, "e": 25873, "s": 25816, "text": "Example: This example describes the HTML Unordered List." }, { "code": null, "e": 25878, "s": 25873, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>How to define an unordered list</title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML5: How to define an unordered list?</h2> <p>GeeksforGeeks courses List:</p> <ul> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html>", "e": 26234, "s": 25878, "text": null }, { "code": null, "e": 26242, "s": 26234, "text": "Output:" }, { "code": null, "e": 26262, "s": 26242, "text": "HTML Unordered list" }, { "code": null, "e": 26317, "s": 26262, "text": "The HTML unordered list has various list item markers:" }, { "code": null, "e": 26387, "s": 26317, "text": "Disc: It is used to set the list item marker to a bullet i.e default." }, { "code": null, "e": 26520, "s": 26387, "text": "Example 1: This example illustrates the use of an unordered list with a disc bullet by setting the list-style-type property to disc." }, { "code": null, "e": 26525, "s": 26520, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML ul tag</title></head> <body> <h1>GeeksforGeeks</h1> <h2>Unordered List with Disc Bullets</h2> <p>GeeksforGeeks courses List:</p> <ul style=\"list-style-type:disc;\"> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html>", "e": 26884, "s": 26525, "text": null }, { "code": null, "e": 26892, "s": 26884, "text": "Output:" }, { "code": null, "e": 26934, "s": 26892, "text": "Unordered list with disc list item marker" }, { "code": null, "e": 26994, "s": 26934, "text": "Circle: It is used to set the list item marker to a circle." }, { "code": null, "e": 27125, "s": 26994, "text": "Example 2: In this example, we have used an unordered list with a circle bullet by setting the list-style-type property to circle." }, { "code": null, "e": 27130, "s": 27125, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>Unordered List with Circle Bullets</h2> <p>GeeksforGeeks courses List:</p> <ul style=\"list-style-type: circle\"> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html>", "e": 27448, "s": 27130, "text": null }, { "code": null, "e": 27456, "s": 27448, "text": "Output:" }, { "code": null, "e": 27500, "s": 27456, "text": "Unordered list with circle list item marker" }, { "code": null, "e": 27560, "s": 27500, "text": "Square: It is used to set the list item marker to a square." }, { "code": null, "e": 27691, "s": 27560, "text": "Example 3: In this example, we have used an unordered list with a square bullet by setting the list-style-type property to square." }, { "code": null, "e": 27696, "s": 27691, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>Unordered List with Square Bullets</h2> <p>GeeksforGeeks courses List:</p> <ul style=\"list-style-type: square\"> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html>", "e": 28014, "s": 27696, "text": null }, { "code": null, "e": 28022, "s": 28014, "text": "Output:" }, { "code": null, "e": 28066, "s": 28022, "text": "Unordered list with square list item marker" }, { "code": null, "e": 28125, "s": 28066, "text": "none: It is used to set the list item marker with no mark." }, { "code": null, "e": 28256, "s": 28125, "text": "Example 4: This example illustrates the use of an unordered list with a no bullet by setting the list-style-type property to none." }, { "code": null, "e": 28261, "s": 28256, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>Unordered List with No Bullets</h2> <p>GeeksforGeeks courses List:</p> <ul style=\"list-style-type: none\"> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html>", "e": 28573, "s": 28261, "text": null }, { "code": null, "e": 28582, "s": 28573, "text": " Output:" }, { "code": null, "e": 28622, "s": 28582, "text": "Unordered list without list item marker" }, { "code": null, "e": 28711, "s": 28622, "text": "Nested Unordered List: It is used to nest the list items i.e., list inside another list." }, { "code": null, "e": 28793, "s": 28711, "text": "Example: This example describes the use of the unordered list in a nested format." }, { "code": null, "e": 28798, "s": 28793, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>Nested Unordered List</h2> <p>GeeksforGeeks courses List:</p> <ul> <li>DSA</li> <ul> <li>Array</li> <li>Linked List</li> <li>stack</li> <li>Queue</li> </ul> <li>Web Technologies</li> <ul> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> </ul> <li>Aptitude</li> <li>Gate</li> <li>Placement</li> </ul></body> </html>", "e": 29326, "s": 28798, "text": null }, { "code": null, "e": 29334, "s": 29326, "text": "Output:" }, { "code": null, "e": 29356, "s": 29334, "text": "Nested Unordered lIst" }, { "code": null, "e": 29376, "s": 29356, "text": "Supported Browsers:" }, { "code": null, "e": 29403, "s": 29376, "text": "Google Chrome 94.0 & above" }, { "code": null, "e": 29424, "s": 29403, "text": "Firefox 92.0 & above" }, { "code": null, "e": 29444, "s": 29424, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 29452, "s": 29444, "text": "IE 11.0" }, { "code": null, "e": 29464, "s": 29452, "text": "Safari 14.1" }, { "code": null, "e": 29475, "s": 29464, "text": "Opera 78.0" }, { "code": null, "e": 29612, "s": 29475, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29633, "s": 29612, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 29642, "s": 29633, "text": "sooda367" }, { "code": null, "e": 29658, "s": 29642, "text": "HTML-Attributes" }, { "code": null, "e": 29673, "s": 29658, "text": "HTML-Questions" }, { "code": null, "e": 29683, "s": 29673, "text": "HTML-Tags" }, { "code": null, "e": 29688, "s": 29683, "text": "HTML" }, { "code": null, "e": 29705, "s": 29688, "text": "Web Technologies" }, { "code": null, "e": 29732, "s": 29705, "text": "Web technologies Questions" }, { "code": null, "e": 29737, "s": 29732, "text": "HTML" }, { "code": null, "e": 29835, "s": 29737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29844, "s": 29835, "text": "Comments" }, { "code": null, "e": 29857, "s": 29844, "text": "Old Comments" }, { "code": null, "e": 29894, "s": 29857, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 29944, "s": 29894, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29968, "s": 29944, "text": "REST API (Introduction)" }, { "code": null, "e": 30005, "s": 29968, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30047, "s": 30005, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 30103, "s": 30047, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 30136, "s": 30103, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30179, "s": 30136, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30240, "s": 30179, "text": "Difference between var, let and const keywords in JavaScript" } ]
Check if given string can be made Palindrome by removing only single type of character - GeeksforGeeks
23 Nov, 2021 Given a string S, the task is to whether a string can be made palindrome after removing the occurrences of the same character, any number of times Examples: Input: S = “abczdzacb” Output: Yes Explanation: Remove first and second occurrence of character ‘a’, string S becomes “bczdzcb”, which is a palindrome . Input: S = “madem”Output: No Approach: The task can be solved by iterating over each unique character in the given string, and removing its occurrences wherever there is a mismatch, if a valid palindrome is found, after removing occurrences of the same character any number of times, return “Yes” else return “No“.Follow the below steps to solve the problem: Start iterating over each unique character of the string, whose occurrences are to be deleted Use the two-pointer technique, to check for a mismatch, Place l at the start of the string and r at the end of the string If S[l] == S[r], increment l, and decrement r. If S[l]!= S[r], check if S[l[ == char, do l++, else if S[r] == char, do r– If none of the conditions hold, means the given can’t be converted into a palindrome Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a palindrome is// possible or notstring isPossible(string S){ // Stores the length of string int n = (int)S.length(); // Stores the unique characters in // the string set<char> st; for (int i = 0; i < n; i++) { st.insert(S[i]); } // Check if valid palindrome is // possible or not bool check = false; // Iterating over unique characters // of the string for (auto ele : st) { // Pointers to check the condition int low = 0, high = n - 1; bool flag = true; // Iterating over the string for (int i = 0; i < n; i++) { if (S[low] == S[high]) { // Updating low and high low++; high--; } else { if (S[low] == ele) { // Updating low low++; } else if (S[high] == ele) { // Updating high high--; } else { // It is impossible // to make palindrome // by removing // occurrences of char flag = false; break; } } } // If palindrome is formed // break the loop if (flag == true) { check = true; break; } } if (check) return "Yes"; else return "No";} // Driver Codeint main(){ string S = "abczdzacb"; cout << isPossible(S); return 0;} // Java code for the above approachimport java.util.*; class GFG{ // Function to check if a palindrome is// possible or notstatic String isPossible(String S){ // Stores the length of string int n = S.length(); // Stores the unique characters in // the string Set<Character> st = new HashSet<Character>(); for (int i = 0; i < n; i++) { st.add(S.charAt(i)); } // Check if valid palindrome is // possible or not boolean check = false; // Iterating over unique characters // of the string for (Character ele : st) { // Pointers to check the condition int low = 0, high = n - 1; boolean flag = true; // Iterating over the string for (int i = 0; i < n; i++) { if (S.charAt(low) == S.charAt(high)) { // Updating low and high low++; high--; } else { if (S.charAt(low) == ele) { // Updating low low++; } else if (S.charAt(high)== ele) { // Updating high high--; } else { // It is impossible // to make palindrome // by removing // occurrences of char flag = false; break; } } } // If palindrome is formed // break the loop if (flag == true) { check = true; break; } } if (check) return "Yes"; else return "No";} // Driver Code public static void main (String[] args) { String S = "abczdzacb"; System.out.println(isPossible(S)); }} // This code is contributed by Potta Lokesh # python program for the above approach # Function to check if a palindrome is# possible or notdef isPossible(S): # Stores the length of string n = len(S) # Stores the unique characters in # the string st = set() for i in range(0, n): st.add(S[i]) # Check if valid palindrome is # possible or not check = False # Iterating over unique characters # of the string for ele in st: # Pointers to check the condition low = 0 high = n - 1 flag = True # Iterating over the string for i in range(0, n): if (S[low] == S[high]): # Updating low and high low += 1 high -= 1 else: if (S[low] == ele): # Updating low low += 1 elif (S[high] == ele): # Updating high high -= 1 else: # It is impossible # to make palindrome # by removing # occurrences of char flag = False break # If palindrome is formed # break the loop if (flag == True): check = True break if (check): return "Yes" else: return "No" # Driver Codeif __name__ == "__main__": S = "abczdzacb" print(isPossible(S)) # This code is contributed by rakeshsahni // C# code for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to check if a palindrome is// possible or notstatic String isPossible(String S){ // Stores the length of string int n = S.Length; // Stores the unique characters in // the string HashSet<char> st = new HashSet<char>(); for (int i = 0; i < n; i++) { st.Add(S[i]); } // Check if valid palindrome is // possible or not bool check = false; // Iterating over unique characters // of the string foreach (char ele in st) { // Pointers to check the condition int low = 0, high = n - 1; bool flag = true; // Iterating over the string for (int i = 0; i < n; i++) { if (S[low] == S[high]) { // Updating low and high low++; high--; } else { if (S[low] == ele) { // Updating low low++; } else if (S[high]== ele) { // Updating high high--; } else { // It is impossible // to make palindrome // by removing // occurrences of char flag = false; break; } } } // If palindrome is formed // break the loop if (flag == true) { check = true; break; } } if (check) return "Yes"; else return "No";} // Driver Code public static void Main(String[] args) { String S = "abczdzacb"; Console.WriteLine(isPossible(S)); }} // This code is contributed by shikhasingrajput <script>// Javascript program for the above approach // Function to check if a palindrome is// possible or notfunction isPossible(S){ // Stores the length of string let n = S.length; // Stores the unique characters in // the string let st = new Set(); for (let i = 0; i < n; i++) { st.add(S[i]); } // Check if valid palindrome is // possible or not let check = false; // Iterating over unique characters // of the string for (ele of st) { // Pointers to check the condition let low = 0, high = n - 1; let flag = true; // Iterating over the string for (let i = 0; i < n; i++) { if (S[low] == S[high]) { // Updating low and high low++; high--; } else { if (S[low] == ele) { // Updating low low++; } else if (S[high] == ele) { // Updating high high--; } else { // It is impossible // to make palindrome // by removing // occurrences of char flag = false; break; } } } // If palindrome is formed // break the loop if (flag == true) { check = true; break; } } if (check) return "Yes"; else return "No";} // Driver Codelet S = "abczdzacb";document.write(isPossible(S)); // This code is contributed by saurabh_jaiswal.</script> Yes Time Complexity: O(n*26)Auxiliary Space: O(n) rakeshsahni _saurabh_jaiswal lokeshpotta20 shikhasingrajput palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 String Coding Problems for Interviews Vigenère Cipher How to Append a Character to a String in C Program to add two binary strings Convert character array to string in C++ Naive algorithm for Pattern Searching Hill Cipher Return maximum occurring character in an input string Print all subsequences of a string A Program to check if strings are rotations of each other or not
[ { "code": null, "e": 24461, "s": 24433, "text": "\n23 Nov, 2021" }, { "code": null, "e": 24608, "s": 24461, "text": "Given a string S, the task is to whether a string can be made palindrome after removing the occurrences of the same character, any number of times" }, { "code": null, "e": 24618, "s": 24608, "text": "Examples:" }, { "code": null, "e": 24802, "s": 24618, "text": " Input: S = “abczdzacb” Output: Yes Explanation: Remove first and second occurrence of character ‘a’, string S becomes “bczdzcb”, which is a palindrome . Input: S = “madem”Output: No" }, { "code": null, "e": 25132, "s": 24802, "text": "Approach: The task can be solved by iterating over each unique character in the given string, and removing its occurrences wherever there is a mismatch, if a valid palindrome is found, after removing occurrences of the same character any number of times, return “Yes” else return “No“.Follow the below steps to solve the problem:" }, { "code": null, "e": 25226, "s": 25132, "text": "Start iterating over each unique character of the string, whose occurrences are to be deleted" }, { "code": null, "e": 25348, "s": 25226, "text": "Use the two-pointer technique, to check for a mismatch, Place l at the start of the string and r at the end of the string" }, { "code": null, "e": 25395, "s": 25348, "text": "If S[l] == S[r], increment l, and decrement r." }, { "code": null, "e": 25470, "s": 25395, "text": "If S[l]!= S[r], check if S[l[ == char, do l++, else if S[r] == char, do r–" }, { "code": null, "e": 25555, "s": 25470, "text": "If none of the conditions hold, means the given can’t be converted into a palindrome" }, { "code": null, "e": 25607, "s": 25555, "text": " Below is the implementation of the above approach:" }, { "code": null, "e": 25611, "s": 25607, "text": "C++" }, { "code": null, "e": 25616, "s": 25611, "text": "Java" }, { "code": null, "e": 25624, "s": 25616, "text": "Python3" }, { "code": null, "e": 25627, "s": 25624, "text": "C#" }, { "code": null, "e": 25638, "s": 25627, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a palindrome is// possible or notstring isPossible(string S){ // Stores the length of string int n = (int)S.length(); // Stores the unique characters in // the string set<char> st; for (int i = 0; i < n; i++) { st.insert(S[i]); } // Check if valid palindrome is // possible or not bool check = false; // Iterating over unique characters // of the string for (auto ele : st) { // Pointers to check the condition int low = 0, high = n - 1; bool flag = true; // Iterating over the string for (int i = 0; i < n; i++) { if (S[low] == S[high]) { // Updating low and high low++; high--; } else { if (S[low] == ele) { // Updating low low++; } else if (S[high] == ele) { // Updating high high--; } else { // It is impossible // to make palindrome // by removing // occurrences of char flag = false; break; } } } // If palindrome is formed // break the loop if (flag == true) { check = true; break; } } if (check) return \"Yes\"; else return \"No\";} // Driver Codeint main(){ string S = \"abczdzacb\"; cout << isPossible(S); return 0;}", "e": 27318, "s": 25638, "text": null }, { "code": "// Java code for the above approachimport java.util.*; class GFG{ // Function to check if a palindrome is// possible or notstatic String isPossible(String S){ // Stores the length of string int n = S.length(); // Stores the unique characters in // the string Set<Character> st = new HashSet<Character>(); for (int i = 0; i < n; i++) { st.add(S.charAt(i)); } // Check if valid palindrome is // possible or not boolean check = false; // Iterating over unique characters // of the string for (Character ele : st) { // Pointers to check the condition int low = 0, high = n - 1; boolean flag = true; // Iterating over the string for (int i = 0; i < n; i++) { if (S.charAt(low) == S.charAt(high)) { // Updating low and high low++; high--; } else { if (S.charAt(low) == ele) { // Updating low low++; } else if (S.charAt(high)== ele) { // Updating high high--; } else { // It is impossible // to make palindrome // by removing // occurrences of char flag = false; break; } } } // If palindrome is formed // break the loop if (flag == true) { check = true; break; } } if (check) return \"Yes\"; else return \"No\";} // Driver Code public static void main (String[] args) { String S = \"abczdzacb\"; System.out.println(isPossible(S)); }} // This code is contributed by Potta Lokesh", "e": 29165, "s": 27318, "text": null }, { "code": "# python program for the above approach # Function to check if a palindrome is# possible or notdef isPossible(S): # Stores the length of string n = len(S) # Stores the unique characters in # the string st = set() for i in range(0, n): st.add(S[i]) # Check if valid palindrome is # possible or not check = False # Iterating over unique characters # of the string for ele in st: # Pointers to check the condition low = 0 high = n - 1 flag = True # Iterating over the string for i in range(0, n): if (S[low] == S[high]): # Updating low and high low += 1 high -= 1 else: if (S[low] == ele): # Updating low low += 1 elif (S[high] == ele): # Updating high high -= 1 else: # It is impossible # to make palindrome # by removing # occurrences of char flag = False break # If palindrome is formed # break the loop if (flag == True): check = True break if (check): return \"Yes\" else: return \"No\" # Driver Codeif __name__ == \"__main__\": S = \"abczdzacb\" print(isPossible(S)) # This code is contributed by rakeshsahni", "e": 30663, "s": 29165, "text": null }, { "code": "// C# code for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to check if a palindrome is// possible or notstatic String isPossible(String S){ // Stores the length of string int n = S.Length; // Stores the unique characters in // the string HashSet<char> st = new HashSet<char>(); for (int i = 0; i < n; i++) { st.Add(S[i]); } // Check if valid palindrome is // possible or not bool check = false; // Iterating over unique characters // of the string foreach (char ele in st) { // Pointers to check the condition int low = 0, high = n - 1; bool flag = true; // Iterating over the string for (int i = 0; i < n; i++) { if (S[low] == S[high]) { // Updating low and high low++; high--; } else { if (S[low] == ele) { // Updating low low++; } else if (S[high]== ele) { // Updating high high--; } else { // It is impossible // to make palindrome // by removing // occurrences of char flag = false; break; } } } // If palindrome is formed // break the loop if (flag == true) { check = true; break; } } if (check) return \"Yes\"; else return \"No\";} // Driver Code public static void Main(String[] args) { String S = \"abczdzacb\"; Console.WriteLine(isPossible(S)); }} // This code is contributed by shikhasingrajput", "e": 32497, "s": 30663, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to check if a palindrome is// possible or notfunction isPossible(S){ // Stores the length of string let n = S.length; // Stores the unique characters in // the string let st = new Set(); for (let i = 0; i < n; i++) { st.add(S[i]); } // Check if valid palindrome is // possible or not let check = false; // Iterating over unique characters // of the string for (ele of st) { // Pointers to check the condition let low = 0, high = n - 1; let flag = true; // Iterating over the string for (let i = 0; i < n; i++) { if (S[low] == S[high]) { // Updating low and high low++; high--; } else { if (S[low] == ele) { // Updating low low++; } else if (S[high] == ele) { // Updating high high--; } else { // It is impossible // to make palindrome // by removing // occurrences of char flag = false; break; } } } // If palindrome is formed // break the loop if (flag == true) { check = true; break; } } if (check) return \"Yes\"; else return \"No\";} // Driver Codelet S = \"abczdzacb\";document.write(isPossible(S)); // This code is contributed by saurabh_jaiswal.</script>", "e": 33870, "s": 32497, "text": null }, { "code": null, "e": 33877, "s": 33873, "text": "Yes" }, { "code": null, "e": 33929, "s": 33881, "text": "Time Complexity: O(n*26)Auxiliary Space: O(n) " }, { "code": null, "e": 33943, "s": 33931, "text": "rakeshsahni" }, { "code": null, "e": 33960, "s": 33943, "text": "_saurabh_jaiswal" }, { "code": null, "e": 33974, "s": 33960, "text": "lokeshpotta20" }, { "code": null, "e": 33991, "s": 33974, "text": "shikhasingrajput" }, { "code": null, "e": 34002, "s": 33991, "text": "palindrome" }, { "code": null, "e": 34010, "s": 34002, "text": "Strings" }, { "code": null, "e": 34018, "s": 34010, "text": "Strings" }, { "code": null, "e": 34029, "s": 34018, "text": "palindrome" }, { "code": null, "e": 34127, "s": 34029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34136, "s": 34127, "text": "Comments" }, { "code": null, "e": 34149, "s": 34136, "text": "Old Comments" }, { "code": null, "e": 34194, "s": 34149, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 34211, "s": 34194, "text": "Vigenère Cipher" }, { "code": null, "e": 34254, "s": 34211, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 34288, "s": 34254, "text": "Program to add two binary strings" }, { "code": null, "e": 34329, "s": 34288, "text": "Convert character array to string in C++" }, { "code": null, "e": 34367, "s": 34329, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 34379, "s": 34367, "text": "Hill Cipher" }, { "code": null, "e": 34433, "s": 34379, "text": "Return maximum occurring character in an input string" }, { "code": null, "e": 34468, "s": 34433, "text": "Print all subsequences of a string" } ]
Check if dataframe contains infinity in Python - Pandas - GeeksforGeeks
26 Dec, 2020 Prerequisites: Pandas There are various cases where a data frame can contain infinity as value. This article discusses how we can keep track of infinities in our data frame. Import module Create a data frame, for this article, it is done using a dictionary. For including infinity in the data, import NumPy module, and use np.inf for positive infinity and -np.inf for negative infinity. Use appropriate methods from the ones mentioned below as per your requirement. Method 1: Use DataFrame.isinf() function to check whether the dataframe contains infinity or not. It returns boolean value. If it contains any infinity, it will return True. Else, it will return False. Syntax: isinf(array [, out]) Using this method itself, we can derive a lot more information regarding the presence of infinity in our dataframe: Checking for infinity as values Counting the number of infinity values Retrieve column name with infinity as value(s) Retrieve row index/indices with infinity as value(s) Example: Python3 # Import required libraries import pandas as pdimport numpy as np # Create dataframe using dictionarydata = {'Student ID': [10, 11, 12, 13, 14], 'Age': [23, 22, 24, 22, 25], 'Weight': [66, 72, np.inf, 68, -np.inf]} df = pd.DataFrame(data) display(df) # checking for infinityprint()print("checking for infinity") ds = df.isin([np.inf, -np.inf])print(ds) # printing the count of infinity valuesprint()print("printing the count of infinity values") count = np.isinf(df).values.sum()print("It contains " + str(count) + " infinite values") # counting infinity in a particular column namec = np.isinf(df['Weight']).values.sum()print("It contains " + str(c) + " infinite values") # printing column name where infinity is presentprint()print("printing column name where infinity is present")col_name = df.columns.to_series()[np.isinf(df).any()]print(col_name) # printing row index with infinityprint()print("printing row index with infinity ") r = df.index[np.isinf(df).any(1)]print(r) Output: Method 2: Use np.isfinite(dataframe_name) to check the presence of infinite value(s). It returns boolean value. It will return False for infinite values and it will return True for finite values. Syntax: isfinite(array [, out]) Example: Python3 # Import required libraries import pandas as pdimport numpy as np # Create dataframe using dictionarydata = {'Student ID': [10, 11, 12, 13, 14], 'Age': [ 23, 22, 24, 22, 25], 'Weight': [66, 72, np.inf, 68, -np.inf]} df = pd.DataFrame(data) d = np.isfinite(df) display(d) Output: Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23938, "s": 23910, "text": "\n26 Dec, 2020" }, { "code": null, "e": 23960, "s": 23938, "text": "Prerequisites: Pandas" }, { "code": null, "e": 24113, "s": 23960, "text": "There are various cases where a data frame can contain infinity as value. This article discusses how we can keep track of infinities in our data frame. " }, { "code": null, "e": 24127, "s": 24113, "text": "Import module" }, { "code": null, "e": 24326, "s": 24127, "text": "Create a data frame, for this article, it is done using a dictionary. For including infinity in the data, import NumPy module, and use np.inf for positive infinity and -np.inf for negative infinity." }, { "code": null, "e": 24405, "s": 24326, "text": "Use appropriate methods from the ones mentioned below as per your requirement." }, { "code": null, "e": 24608, "s": 24405, "text": "Method 1: Use DataFrame.isinf() function to check whether the dataframe contains infinity or not. It returns boolean value. If it contains any infinity, it will return True. Else, it will return False. " }, { "code": null, "e": 24616, "s": 24608, "text": "Syntax:" }, { "code": null, "e": 24637, "s": 24616, "text": "isinf(array [, out])" }, { "code": null, "e": 24753, "s": 24637, "text": "Using this method itself, we can derive a lot more information regarding the presence of infinity in our dataframe:" }, { "code": null, "e": 24785, "s": 24753, "text": "Checking for infinity as values" }, { "code": null, "e": 24824, "s": 24785, "text": "Counting the number of infinity values" }, { "code": null, "e": 24871, "s": 24824, "text": "Retrieve column name with infinity as value(s)" }, { "code": null, "e": 24924, "s": 24871, "text": "Retrieve row index/indices with infinity as value(s)" }, { "code": null, "e": 24933, "s": 24924, "text": "Example:" }, { "code": null, "e": 24941, "s": 24933, "text": "Python3" }, { "code": "# Import required libraries import pandas as pdimport numpy as np # Create dataframe using dictionarydata = {'Student ID': [10, 11, 12, 13, 14], 'Age': [23, 22, 24, 22, 25], 'Weight': [66, 72, np.inf, 68, -np.inf]} df = pd.DataFrame(data) display(df) # checking for infinityprint()print(\"checking for infinity\") ds = df.isin([np.inf, -np.inf])print(ds) # printing the count of infinity valuesprint()print(\"printing the count of infinity values\") count = np.isinf(df).values.sum()print(\"It contains \" + str(count) + \" infinite values\") # counting infinity in a particular column namec = np.isinf(df['Weight']).values.sum()print(\"It contains \" + str(c) + \" infinite values\") # printing column name where infinity is presentprint()print(\"printing column name where infinity is present\")col_name = df.columns.to_series()[np.isinf(df).any()]print(col_name) # printing row index with infinityprint()print(\"printing row index with infinity \") r = df.index[np.isinf(df).any(1)]print(r)", "e": 25946, "s": 24941, "text": null }, { "code": null, "e": 25954, "s": 25946, "text": "Output:" }, { "code": null, "e": 26150, "s": 25954, "text": "Method 2: Use np.isfinite(dataframe_name) to check the presence of infinite value(s). It returns boolean value. It will return False for infinite values and it will return True for finite values." }, { "code": null, "e": 26158, "s": 26150, "text": "Syntax:" }, { "code": null, "e": 26182, "s": 26158, "text": "isfinite(array [, out])" }, { "code": null, "e": 26192, "s": 26182, "text": "Example: " }, { "code": null, "e": 26200, "s": 26192, "text": "Python3" }, { "code": "# Import required libraries import pandas as pdimport numpy as np # Create dataframe using dictionarydata = {'Student ID': [10, 11, 12, 13, 14], 'Age': [ 23, 22, 24, 22, 25], 'Weight': [66, 72, np.inf, 68, -np.inf]} df = pd.DataFrame(data) d = np.isfinite(df) display(d)", "e": 26479, "s": 26200, "text": null }, { "code": null, "e": 26487, "s": 26479, "text": "Output:" }, { "code": null, "e": 26494, "s": 26487, "text": "Picked" }, { "code": null, "e": 26518, "s": 26494, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26541, "s": 26518, "text": "Python Pandas-exercise" }, { "code": null, "e": 26555, "s": 26541, "text": "Python-pandas" }, { "code": null, "e": 26562, "s": 26555, "text": "Python" }, { "code": null, "e": 26660, "s": 26562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26669, "s": 26660, "text": "Comments" }, { "code": null, "e": 26682, "s": 26669, "text": "Old Comments" }, { "code": null, "e": 26700, "s": 26682, "text": "Python Dictionary" }, { "code": null, "e": 26735, "s": 26700, "text": "Read a file line by line in Python" }, { "code": null, "e": 26757, "s": 26735, "text": "Enumerate() in Python" }, { "code": null, "e": 26789, "s": 26757, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26819, "s": 26789, "text": "Iterate over a list in Python" }, { "code": null, "e": 26861, "s": 26819, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26904, "s": 26861, "text": "Python program to convert a list to string" }, { "code": null, "e": 26930, "s": 26904, "text": "Python String | replace()" }, { "code": null, "e": 26974, "s": 26930, "text": "Reading and Writing to text files in Python" } ]
Basic Algorithms — Heapsort. Sorting an array with “Heap” data... | by Keita Miyaki | Towards Data Science
In previous posts, we looked at different sorting algorithms such as Merge Sort and Quicksort, and this time another sorting algorithm, Heapsort, is discussed. Heapsort, as shown in its name, uses “Heap” data structure. Heap is a data structure, and heaps are arrays of binary trees. Each node of the binary tree corresponds to one element of the array. As one node has zero, one, or two children nodes, for i-th element of the array, 2i-th and (2i+1)-th elements are its left and right children respectively. The following figure depicts an example heap in which the numbers in nodes equal to the orders in a 12-element array. The root is the first element in the array, and its left and right children are the second and third elements respectively. The sixth element has only one left child, and the seventh has none. There are two kinds of heaps: min-heap and max-heap. In min-heap parents nodes are smaller than children nodes (the root node is smallest), while in max-heap it is opposite (the root node is largest). We will use max-heap property for Heapsort in this article. The strategy is as follows; i) turn an array into a max-heap; ii) pick the root, which is the maximum number; iii) keep the remaining array as a max heap; iv) recurse ii) and iii). Here is the code for the step iii) which is also used in the step i). This “Max-Heapify” function takes two inputs: an array and an integer. The function compare the node at a given order (input integer) with its two children. If the node is smaller than either of the children, it is swapped with the largest of two children nodes. def max_heapify(array, i): l = (i+1) * 2 - 1 r = (i+1) * 2 length = len(array) if l < length and array[l] > array[i]: largest = l else: largest = i if r < length and array[r] > array[largest]: largest = r if largest != i: largest_value = array[largest] array[largest] = array[i] array[i] = largest_value max_heapify(array, largest) return array While Max-Heapify does not exhaust the entire heap, by operating the function to all the node except for leaves (the end nodes of the heap) we can turn any array to a max-heap. def build_max_heap(array): length = len(array) for i in range(length//2, -1, -1): max_heapify(array, i) return array Now we are ready to implement Heapsort. def heap_sort(array): length = len(array) array = build_max_heap(array) for i in range(length-1, 0, -1): largest = array[0] array[0] = array[i] array[i] = largest max_heapify(array[:i], 0) return array The following figure explains how Heapsort processes a 12-element array; i) firstly we turn the array into a max-heap; ii) take the root, 12, and replace it with the last element, 3; iii) process Max-Heapify onthe remaining 11-element array at the root, and the nodes affected are shown in dark blue; iii) recurse ii) and iii). In the end we will obtain an array sorted by ascending order. Heapsort operates in-place, storing only constant amount of data outside of the input array. We can analyze the cost of Heapsort by examining sub-functions of Max-Heapify and Build-Max-Heap. The cost of Max-Heapify is O(lgn). Comparing a node and its two children nodes costs Θ(1), and in the worst case, we recurse ⌊log2n⌋ times to the bottom. Alternatively, the cost of Max-Heapify can be expressed with the height h of the heap O(h). The cost of Build-Max-Heap is O(n). As an n-element heap has a depth of ⌊lgn⌋ and at any height, there are ⌈n/2h+ 1⌉ nodes except the leaves, we can derive the cost as a total of Max-Heapify costs O(h) as shown on the left. The total cost of Heapsort is O(nlgn), as it calls Build-Max-Heap (O(n)) and Max-Heapify (O(lgn)) over (n-1) times. The following chart describes different sorting algorithms. As expected, Heapsort follows other O(nlgn)-cost algorithms, while it is not as inexpensive as Quicksort with a higher constant hidden in O notation. Although Heapsort does not beat Quicksort as a sorting algorithm, Heap as the data structure offers many different usages, and one of the most notable would be in priority queues. With this Heapsort as an introduction to Heaps, we will see how Heaps are applied to an efficient priority queue algorithm later.
[ { "code": null, "e": 392, "s": 172, "text": "In previous posts, we looked at different sorting algorithms such as Merge Sort and Quicksort, and this time another sorting algorithm, Heapsort, is discussed. Heapsort, as shown in its name, uses “Heap” data structure." }, { "code": null, "e": 682, "s": 392, "text": "Heap is a data structure, and heaps are arrays of binary trees. Each node of the binary tree corresponds to one element of the array. As one node has zero, one, or two children nodes, for i-th element of the array, 2i-th and (2i+1)-th elements are its left and right children respectively." }, { "code": null, "e": 993, "s": 682, "text": "The following figure depicts an example heap in which the numbers in nodes equal to the orders in a 12-element array. The root is the first element in the array, and its left and right children are the second and third elements respectively. The sixth element has only one left child, and the seventh has none." }, { "code": null, "e": 1254, "s": 993, "text": "There are two kinds of heaps: min-heap and max-heap. In min-heap parents nodes are smaller than children nodes (the root node is smallest), while in max-heap it is opposite (the root node is largest). We will use max-heap property for Heapsort in this article." }, { "code": null, "e": 1435, "s": 1254, "text": "The strategy is as follows; i) turn an array into a max-heap; ii) pick the root, which is the maximum number; iii) keep the remaining array as a max heap; iv) recurse ii) and iii)." }, { "code": null, "e": 1768, "s": 1435, "text": "Here is the code for the step iii) which is also used in the step i). This “Max-Heapify” function takes two inputs: an array and an integer. The function compare the node at a given order (input integer) with its two children. If the node is smaller than either of the children, it is swapped with the largest of two children nodes." }, { "code": null, "e": 2207, "s": 1768, "text": "def max_heapify(array, i): l = (i+1) * 2 - 1 r = (i+1) * 2 length = len(array) if l < length and array[l] > array[i]: largest = l else: largest = i if r < length and array[r] > array[largest]: largest = r if largest != i: largest_value = array[largest] array[largest] = array[i] array[i] = largest_value max_heapify(array, largest) return array" }, { "code": null, "e": 2384, "s": 2207, "text": "While Max-Heapify does not exhaust the entire heap, by operating the function to all the node except for leaves (the end nodes of the heap) we can turn any array to a max-heap." }, { "code": null, "e": 2517, "s": 2384, "text": "def build_max_heap(array): length = len(array) for i in range(length//2, -1, -1): max_heapify(array, i) return array" }, { "code": null, "e": 2557, "s": 2517, "text": "Now we are ready to implement Heapsort." }, { "code": null, "e": 2807, "s": 2557, "text": "def heap_sort(array): length = len(array) array = build_max_heap(array) for i in range(length-1, 0, -1): largest = array[0] array[0] = array[i] array[i] = largest max_heapify(array[:i], 0) return array" }, { "code": null, "e": 3290, "s": 2807, "text": "The following figure explains how Heapsort processes a 12-element array; i) firstly we turn the array into a max-heap; ii) take the root, 12, and replace it with the last element, 3; iii) process Max-Heapify onthe remaining 11-element array at the root, and the nodes affected are shown in dark blue; iii) recurse ii) and iii). In the end we will obtain an array sorted by ascending order. Heapsort operates in-place, storing only constant amount of data outside of the input array." }, { "code": null, "e": 3388, "s": 3290, "text": "We can analyze the cost of Heapsort by examining sub-functions of Max-Heapify and Build-Max-Heap." }, { "code": null, "e": 3634, "s": 3388, "text": "The cost of Max-Heapify is O(lgn). Comparing a node and its two children nodes costs Θ(1), and in the worst case, we recurse ⌊log2n⌋ times to the bottom. Alternatively, the cost of Max-Heapify can be expressed with the height h of the heap O(h)." }, { "code": null, "e": 3858, "s": 3634, "text": "The cost of Build-Max-Heap is O(n). As an n-element heap has a depth of ⌊lgn⌋ and at any height, there are ⌈n/2h+ 1⌉ nodes except the leaves, we can derive the cost as a total of Max-Heapify costs O(h) as shown on the left." }, { "code": null, "e": 3974, "s": 3858, "text": "The total cost of Heapsort is O(nlgn), as it calls Build-Max-Heap (O(n)) and Max-Heapify (O(lgn)) over (n-1) times." }, { "code": null, "e": 4184, "s": 3974, "text": "The following chart describes different sorting algorithms. As expected, Heapsort follows other O(nlgn)-cost algorithms, while it is not as inexpensive as Quicksort with a higher constant hidden in O notation." } ]
Create a grouped bar plot in Matplotlib - GeeksforGeeks
17 Dec, 2020 In this article, we will learn how to Create a grouped bar plot in Matplotlib. Let’s discuss some concepts : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduced by John Hunter within the year 2002. A bar plot or bar graph may be a graph that represents the category of knowledge with rectangular bars with lengths and heights that’s proportional to the values which they represent. The bar plots are often plotted horizontally or vertically. A bar chart is a great way to compare categorical data across one or two dimensions. More often than not, it’s more interesting to compare values across two dimensions and for that, a grouped bar chart is needed. Approach: Import Library (Matplotlib)Import / create data.Plot the bars in the grouped manner. Import Library (Matplotlib) Import / create data. Plot the bars in the grouped manner. Example 1: (Simple grouped bar plot) Python3 # importing packageimport matplotlib.pyplot as pltimport numpy as np # create datax = np.arange(5)y1 = [34, 56, 12, 89, 67]y2 = [12, 56, 78, 45, 90]width = 0.40 # plot data in grouped manner of bar typeplt.bar(x-0.2, y1, width)plt.bar(x+0.2, y2, width) Output : Example 2: (Grouped bar chart with more than 2 data) Python3 # importing packageimport matplotlib.pyplot as pltimport numpy as np # create datax = np.arange(5)y1 = [34, 56, 12, 89, 67]y2 = [12, 56, 78, 45, 90]y3 = [14, 23, 45, 25, 89]width = 0.2 # plot data in grouped manner of bar typeplt.bar(x-0.2, y1, width, color='cyan')plt.bar(x, y2, width, color='orange')plt.bar(x+0.2, y3, width, color='green')plt.xticks(x, ['Team A', 'Team B', 'Team C', 'Team D', 'Team E'])plt.xlabel("Teams")plt.ylabel("Scores")plt.legend(["Round 1", "Round 2", "Round 3"])plt.show() Output : Example 3: (Grouped Bar chart using dataframe plot) Python3 # importing packageimport matplotlib.pyplot as pltimport pandas as pd # create datadf = pd.DataFrame([['A', 10, 20, 10, 30], ['B', 20, 25, 15, 25], ['C', 12, 15, 19, 6], ['D', 10, 29, 13, 19]], columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])# view dataprint(df) # plot grouped bar chartdf.plot(x='Team', kind='bar', stacked=False, title='Grouped Bar Graph with dataframe') Output : Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n17 Dec, 2020" }, { "code": null, "e": 24010, "s": 23901, "text": "In this article, we will learn how to Create a grouped bar plot in Matplotlib. Let’s discuss some concepts :" }, { "code": null, "e": 24290, "s": 24010, "text": "Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduced by John Hunter within the year 2002." }, { "code": null, "e": 24534, "s": 24290, "text": "A bar plot or bar graph may be a graph that represents the category of knowledge with rectangular bars with lengths and heights that’s proportional to the values which they represent. The bar plots are often plotted horizontally or vertically." }, { "code": null, "e": 24747, "s": 24534, "text": "A bar chart is a great way to compare categorical data across one or two dimensions. More often than not, it’s more interesting to compare values across two dimensions and for that, a grouped bar chart is needed." }, { "code": null, "e": 24757, "s": 24747, "text": "Approach:" }, { "code": null, "e": 24842, "s": 24757, "text": "Import Library (Matplotlib)Import / create data.Plot the bars in the grouped manner." }, { "code": null, "e": 24870, "s": 24842, "text": "Import Library (Matplotlib)" }, { "code": null, "e": 24892, "s": 24870, "text": "Import / create data." }, { "code": null, "e": 24929, "s": 24892, "text": "Plot the bars in the grouped manner." }, { "code": null, "e": 24966, "s": 24929, "text": "Example 1: (Simple grouped bar plot)" }, { "code": null, "e": 24974, "s": 24966, "text": "Python3" }, { "code": "# importing packageimport matplotlib.pyplot as pltimport numpy as np # create datax = np.arange(5)y1 = [34, 56, 12, 89, 67]y2 = [12, 56, 78, 45, 90]width = 0.40 # plot data in grouped manner of bar typeplt.bar(x-0.2, y1, width)plt.bar(x+0.2, y2, width)", "e": 25229, "s": 24974, "text": null }, { "code": null, "e": 25238, "s": 25229, "text": "Output :" }, { "code": null, "e": 25291, "s": 25238, "text": "Example 2: (Grouped bar chart with more than 2 data)" }, { "code": null, "e": 25299, "s": 25291, "text": "Python3" }, { "code": "# importing packageimport matplotlib.pyplot as pltimport numpy as np # create datax = np.arange(5)y1 = [34, 56, 12, 89, 67]y2 = [12, 56, 78, 45, 90]y3 = [14, 23, 45, 25, 89]width = 0.2 # plot data in grouped manner of bar typeplt.bar(x-0.2, y1, width, color='cyan')plt.bar(x, y2, width, color='orange')plt.bar(x+0.2, y3, width, color='green')plt.xticks(x, ['Team A', 'Team B', 'Team C', 'Team D', 'Team E'])plt.xlabel(\"Teams\")plt.ylabel(\"Scores\")plt.legend([\"Round 1\", \"Round 2\", \"Round 3\"])plt.show()", "e": 25803, "s": 25299, "text": null }, { "code": null, "e": 25812, "s": 25803, "text": "Output :" }, { "code": null, "e": 25864, "s": 25812, "text": "Example 3: (Grouped Bar chart using dataframe plot)" }, { "code": null, "e": 25872, "s": 25864, "text": "Python3" }, { "code": "# importing packageimport matplotlib.pyplot as pltimport pandas as pd # create datadf = pd.DataFrame([['A', 10, 20, 10, 30], ['B', 20, 25, 15, 25], ['C', 12, 15, 19, 6], ['D', 10, 29, 13, 19]], columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])# view dataprint(df) # plot grouped bar chartdf.plot(x='Team', kind='bar', stacked=False, title='Grouped Bar Graph with dataframe')", "e": 26317, "s": 25872, "text": null }, { "code": null, "e": 26326, "s": 26317, "text": "Output :" }, { "code": null, "e": 26333, "s": 26326, "text": "Picked" }, { "code": null, "e": 26351, "s": 26333, "text": "Python-matplotlib" }, { "code": null, "e": 26358, "s": 26351, "text": "Python" }, { "code": null, "e": 26456, "s": 26358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26465, "s": 26456, "text": "Comments" }, { "code": null, "e": 26478, "s": 26465, "text": "Old Comments" }, { "code": null, "e": 26510, "s": 26478, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26566, "s": 26510, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26608, "s": 26566, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26650, "s": 26608, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26686, "s": 26650, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26708, "s": 26686, "text": "Defaultdict in Python" }, { "code": null, "e": 26747, "s": 26708, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26774, "s": 26747, "text": "Python Classes and Objects" }, { "code": null, "e": 26805, "s": 26774, "text": "Python | os.path.join() method" } ]